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/app/services/onetime/deactivate_affiliates_for_stripe_connect_brazil.rb | app/services/onetime/deactivate_affiliates_for_stripe_connect_brazil.rb | # frozen_string_literal: true
# This script deactivates affiliates for Stripe Connect accounts in Brazil
module Onetime::DeactivateAffiliatesForStripeConnectBrazil
extend self
def process
eligible_merchant_accounts.find_each do |merchant_account|
process_merchant_account!(merchant_account)
end
end
private
def eligible_merchant_accounts
MerchantAccount.includes(user: :merchant_accounts)
.alive
.charge_processor_alive
.stripe_connect
.where(country: Compliance::Countries::BRA.alpha2)
end
def process_merchant_account!(merchant_account)
seller = merchant_account.user
if seller.merchant_account(StripeChargeProcessor.charge_processor_id).is_a_brazilian_stripe_connect_account?
Rails.logger.info("Skipping seller #{seller.id} because their merchant account is not a Stripe Connect account from Brazil")
return
end
Rails.logger.info("SELLER: #{seller.id}")
ActiveRecord::Base.transaction do
# disable global affiliates
seller.update!(disable_global_affiliate: true)
if Affiliate.alive.where(seller_id: seller.id).present?
# email seller
subject = "Gumroad affiliate and collaborator programs are no longer available in Brazil"
body = <<~BODY
Hi there,
You are getting this email because you have affiliates or collaborators and are based out of Brazil.
Unfortunately, recent changes made by Stripe have required us to suspend our affiliate and collaborator programs for Brazilian creators. Going forward, your affiliates and collaborators will be disabled and will no longer receive payments for purchases made through them, including for pre-existing membership subscriptions. They will be separately notified of this change.
We apologize for the inconvenience.
Best,
Sahil and the Gumroad Team.
BODY
OneOffMailer.email(user_id: seller.id, subject:, body:)
# email & deactivate direct affiliates & collaborators
Affiliate.alive.where(seller_id: seller.id).find_each do |affiliate|
Rails.logger.info("- affiliate: #{affiliate.id}")
affiliate_type = affiliate.collaborator? ? "collaborator" : "affiliate"
subject = "Gumroad #{affiliate_type} program is no longer available in Brazil"
body = <<~BODY
Hi there,
You are getting this email because you are #{affiliate.collaborator? ? "a collaborator" : "an affiliate"} for a Gumroad creator based out of Brazil.
Unfortunately, recent changes made by Stripe have required us to suspend our #{affiliate_type} program for Brazilian creators. Going forward, you will no longer receive affiliate payments for purchases made through these creators, including for pre-existing membership subscriptions. Non-Brazil-based creators are not affected by this change, and you will continue to receive #{affiliate_type} payments as usual for those creators.
We apologize for the inconvenience.
Best,
Sahil and the Gumroad Team.
BODY
OneOffMailer.email(user_id: affiliate.affiliate_user_id, subject:, body:)
affiliate.mark_deleted!
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/enable_refund_policy_for_sellers_without_refund_policies.rb | app/services/onetime/enable_refund_policy_for_sellers_without_refund_policies.rb | # frozen_string_literal: true
class Onetime::EnableRefundPolicyForSellersWithoutRefundPolicies < Onetime::Base
LAST_PROCESSED_SELLER_ID_KEY = :last_processed_existing_seller_without_refund_policies_id
def self.reset_last_processed_seller_id
$redis.del(LAST_PROCESSED_SELLER_ID_KEY)
end
def initialize(max_id: User.last!.id)
@max_id = max_id
end
def process
invalid_seller_ids = []
ReplicaLagWatcher.watch
eligible_sellers.find_in_batches do |batch|
Rails.logger.info "Processing sellers #{batch.first.id} to #{batch.last.id}"
batch.each do |seller|
next if seller.refund_policy_enabled?
next if seller.product_refund_policies.any?
update_invalid_seller_due_to_payout_threshold_if_needed!(seller)
seller.update!(refund_policy_enabled: true)
rescue => e
invalid_seller_ids << { seller.id => e.message }
end
$redis.set(LAST_PROCESSED_SELLER_ID_KEY, batch.last.id, ex: 2.months)
end
Rails.logger.info "Invalid seller ids: #{invalid_seller_ids}" if invalid_seller_ids.any?
end
private
attr_reader :max_id
def eligible_sellers
first_seller_id = [first_eligible_seller_id, $redis.get(LAST_PROCESSED_SELLER_ID_KEY).to_i + 1].max
User.not_refund_policy_enabled.where(id: first_seller_id..max_id)
end
def first_eligible_seller_id
User.first!.id
end
def update_invalid_seller_due_to_payout_threshold_if_needed!(seller)
return if seller.valid?
full_messages = seller.errors.full_messages
return unless full_messages.one? && full_messages.first == "Your payout threshold must be greater than the minimum payout amount"
seller.update!(payout_threshold_cents: seller.minimum_payout_threshold_cents)
Rails.logger.info "Updated payout threshold for seller #{seller.id} to #{seller.minimum_payout_threshold_cents}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/create_product_refund_policies_for_user.rb | app/services/onetime/create_product_refund_policies_for_user.rb | # frozen_string_literal: true
class Onetime::CreateProductRefundPoliciesForUser
attr_reader :user_id, :max_refund_period_in_days, :results
def initialize(user_id:, max_refund_period_in_days: 0)
@user_id = user_id
@max_refund_period_in_days = max_refund_period_in_days
@results = { success: [], errors: [] }
end
def process
user = User.find(user_id)
Rails.logger.info("Creating refund policies for user #{user_id} with max_refund_period_in_days: #{max_refund_period_in_days}")
products_without_policy = user.products.where.missing(:product_refund_policy)
total_count = products_without_policy.count
Rails.logger.info("Found #{total_count} products without refund policies")
products_without_policy.find_each do |product|
refund_policy = product.transaction do
refund_policy = product.create_product_refund_policy!(
seller: user,
max_refund_period_in_days:
)
product.update!(product_refund_policy_enabled: true)
refund_policy
end
success_message = "✓ Created refund policy for product #{product.id}: #{product.name}. Policy: #{refund_policy.title}"
Rails.logger.info(success_message)
results[:success] << {
product_id: product.id,
product_name: product.name,
policy_title: refund_policy.title
}
rescue StandardError => e
error_message = "✗ Error creating refund policy for product #{product.id}: #{product.name} - #{e.message} - #{e.backtrace.join("\n")}"
Rails.logger.error(error_message)
results[:errors] << {
product_id: product.id,
product_name: product.name,
error: e.message
}
end
log_summary
results
end
private
def log_summary
Rails.logger.info("=" * 60)
Rails.logger.info("Summary for user #{user_id}:")
Rails.logger.info("Successfully created #{results[:success].count} refund policies")
Rails.logger.info("Failed to create #{results[:errors].count} refund policies")
Rails.logger.info("=" * 60)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/add_new_vr_taxonomies.rb | app/services/onetime/add_new_vr_taxonomies.rb | # frozen_string_literal: true
class Onetime::AddNewVrTaxonomies
def self.process
move_vr_chat_to_3d
old_taxonomy_count = Taxonomy.count
taxonomy_names.each do |taxonomy_name|
ancestor_slugs = taxonomy_name.split(",")
parent = Taxonomy.find_by!(slug: ancestor_slugs.second_to_last)
Taxonomy.find_or_create_by!(slug: ancestor_slugs.last, parent:)
end
puts "Added #{Taxonomy.count - old_taxonomy_count}/#{taxonomy_names.length} new taxonomies"
Rails.cache.clear
true
end
private
def self.move_vr_chat_to_3d
gaming = Taxonomy.find_by(slug: "gaming")
vrchat = Taxonomy.find_by(slug: "vrchat", parent: gaming)
return unless vrchat
vrchat.update!(parent: Taxonomy.find_by!(slug: "3d"))
end
def self.taxonomy_names
%w(
3d,avatars,
3d,avatars,female,
3d,avatars,male,
3d,avatars,non-binary,
3d,avatars,optimized,
3d,avatars,quest,
3d,avatars,species,
3d,3d-assets,avatar-components,
3d,3d-assets,avatar-components,bases
3d,3d-assets,avatar-components,ears
3d,3d-assets,avatar-components,feet
3d,3d-assets,avatar-components,hair
3d,3d-assets,avatar-components,heads
3d,3d-assets,avatar-components,horns
3d,3d-assets,avatar-components,tails
3d,3d-assets,accessories,
3d,3d-assets,accessories,bags
3d,3d-assets,accessories,belts
3d,3d-assets,accessories,chokers
3d,3d-assets,accessories,gloves
3d,3d-assets,accessories,harnesses
3d,3d-assets,accessories,jewelry
3d,3d-assets,accessories,masks
3d,3d-assets,accessories,wings
3d,3d-assets,clothing,
3d,3d-assets,clothing,bodysuits
3d,3d-assets,clothing,bottoms
3d,3d-assets,clothing,bras
3d,3d-assets,clothing,dresses
3d,3d-assets,clothing,jackets
3d,3d-assets,clothing,lingerie
3d,3d-assets,clothing,outfits
3d,3d-assets,clothing,pants
3d,3d-assets,clothing,shirts
3d,3d-assets,clothing,shorts
3d,3d-assets,clothing,skirts
3d,3d-assets,clothing,sweaters
3d,3d-assets,clothing,swimsuits
3d,3d-assets,clothing,tops
3d,3d-assets,clothing,underwear
3d,3d-assets,footwear,
3d,3d-assets,footwear,boots
3d,3d-assets,footwear,leggings
3d,3d-assets,footwear,shoes
3d,3d-assets,footwear,socks
3d,3d-assets,footwear,stockings
3d,3d-assets,headwear,
3d,3d-assets,headwear,hats
3d,3d-assets,props,
3d,3d-assets,props,companions
3d,3d-assets,props,handheld
3d,3d-assets,props,plushies
3d,3d-assets,props,prefabs
3d,3d-assets,props,weapons
3d,3d-assets,unity,animations
3d,3d-assets,unity,particle-systems
3d,3d-assets,unity,shaders
3d,vrchat,avatar-systems,
3d,vrchat,followers,
3d,vrchat,osc,
3d,vrchat,setup-scripts,
3d,vrchat,spring-joints,
3d,vrchat,tools,
3d,vrchat,world-constraints,
3d,vrchat,worlds,
3d,vrchat,worlds,assets
3d,vrchat,worlds,midi
3d,vrchat,worlds,quest
3d,vrchat,worlds,tools
3d,vrchat,worlds,udon
3d,vrchat,worlds,udon-system
3d,vrchat,worlds,udon2
3d,vrchat,tutorials-guides,
3d,textures,
3d,textures,base,
3d,textures,eyes,
3d,textures,face,
3d,textures,icons,
3d,textures,matcap,
3d,textures,pbr,
3d,textures,tattoos,
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/index_products_with_allowed_offer_codes.rb | app/services/onetime/index_products_with_allowed_offer_codes.rb | # frozen_string_literal: true
class Onetime::IndexProductsWithAllowedOfferCodes
def self.process
allowed_codes = SearchProducts::ALLOWED_OFFER_CODES
offer_codes = OfferCode.alive.where(code: allowed_codes)
indexed_product_ids = Set.new
batch_index = 0
offer_codes.find_each do |offer_code|
offer_code.applicable_products.pluck(:id).each do |product_id|
next if indexed_product_ids.include?(product_id)
indexed_product_ids << product_id
SendToElasticsearchWorker.perform_in(
(batch_index / 100 * 30).seconds,
product_id,
"update",
["offer_codes"]
)
batch_index += 1
end
end
Rails.logger.info "Enqueued #{indexed_product_ids.size} reindex jobs"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/notify_sellers_with_refund_policies.rb | app/services/onetime/notify_sellers_with_refund_policies.rb | # frozen_string_literal: true
class Onetime::NotifySellersWithRefundPolicies < Onetime::Base
LAST_PROCESSED_ID_KEY = :last_notified_seller_for_refund_policy_id
def self.reset_last_processed_seller_id
$redis.del(LAST_PROCESSED_ID_KEY)
end
def initialize(max_id: ProductRefundPolicy.last!.id)
@max_id = max_id
end
def process
invalid_seller_ids = []
eligible_product_refund_policies.find_in_batches do |batch|
ReplicaLagWatcher.watch
Rails.logger.info "Processing product refund policies #{batch.first.id} to #{batch.last.id}"
batch.each do |product_refund_policy|
seller = product_refund_policy.seller
seller.with_lock do
if seller.upcoming_refund_policy_change_email_sent?
Rails.logger.info "Seller: #{seller.id}: skipped"
next
else
seller.update!(upcoming_refund_policy_change_email_sent: true)
ContactingCreatorMailer.upcoming_refund_policy_change(seller.id).deliver_later
Rails.logger.info "Seller: #{seller.id}: email sent"
end
end
rescue => e
invalid_seller_ids << { seller.id => e.message }
end
$redis.set(LAST_PROCESSED_ID_KEY, batch.last.id, ex: 2.months)
end
Rails.logger.info "Invalid seller ids: #{invalid_seller_ids}" if invalid_seller_ids.any?
end
private
attr_reader :max_id
def eligible_product_refund_policies
first_product_refund_policy_id = [first_eligible_product_refund_policy_id, $redis.get(LAST_PROCESSED_ID_KEY).to_i + 1].max
ProductRefundPolicy.where.not(product_id: nil).where(id: first_product_refund_policy_id..max_id)
end
def first_eligible_product_refund_policy_id
ProductRefundPolicy.first!.id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/remove_stale_recipients.rb | app/services/onetime/remove_stale_recipients.rb | # frozen_string_literal: true
class Onetime::RemoveStaleRecipients
def self.process
# Process followers
last_follower_id = $redis.get(last_follower_id_key)&.to_i || 0
Follower.alive.where("id > ?", last_follower_id).find_each do |follower|
if EmailEvent.stale_recipient?(follower.email)
follower.mark_deleted!
EmailEvent.mark_as_stale(follower.email, Time.current)
end
$redis.set(last_follower_id_key, follower.id)
end
# Process purchases
last_purchase_id = $redis.get(last_purchase_id_key)&.to_i || 0
Purchase.where("id > ?", last_purchase_id).where(can_contact: true).find_each do |purchase|
if EmailEvent.stale_recipient?(purchase.email)
begin
purchase.update!(can_contact: false)
rescue ActiveRecord::RecordInvalid
Rails.logger.info "Could not update purchase (#{purchase.id}) with validations turned on. Unsubscribing the buyer without running validations."
purchase.can_contact = false
purchase.save(validate: false)
end
EmailEvent.mark_as_stale(purchase.email, Time.current)
end
$redis.set(last_purchase_id_key, purchase.id)
end
end
private
def self.last_follower_id_key
"remove_stale_recipients_last_follower_id"
end
def self.last_purchase_id_key
"remove_stale_recipients_last_purchase_id"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/base.rb | app/services/onetime/base.rb | # frozen_string_literal: true
# Usage:
#
# class Onetime::MyScript < Onetime::Base
# def initialize(args)
# @args = args
# end
#
# def process
# Rails.logger.info "I do great things"
# end
# end
#
# To execute without logging:
# Onetime::MyScript.new(args).process
# To execute with logging:
# Onetime::MyScript.new(args).process_with_logging
#
class Onetime::Base
def process_with_logging(...)
with_logging do
process(...)
end
end
private
def with_logging
custom_logger = enable_logger
start_time = Time.current
Rails.logger.info "Started process at #{start_time}"
yield
finish_time = Time.current
Rails.logger.info "Finished process at #{finish_time} in #{ActiveSupport::Duration.build(finish_time - start_time).inspect}"
close_logger(custom_logger)
end
def enable_logger
custom_logger = Logger.new(
"log/#{self.class.name.split('::').last.underscore}_#{Time.current.strftime('%Y-%m-%d_%H-%M-%S')}.log",
level: Logger::INFO
)
Rails.logger.broadcast_to(custom_logger)
custom_logger
end
def close_logger(custom_logger)
Rails.logger.stop_broadcasting_to(custom_logger)
custom_logger.close
end
def process
raise NotImplementedError, "Subclasses must implement a process method"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/set_max_allowed_refund_period_for_purchase_refund_policies.rb | app/services/onetime/set_max_allowed_refund_period_for_purchase_refund_policies.rb | # frozen_string_literal: true
class Onetime::SetMaxAllowedRefundPeriodForPurchaseRefundPolicies < Onetime::Base
LAST_PROCESSED_ID_KEY = :last_processed_id
def self.reset_last_processed_id
$redis.del(LAST_PROCESSED_ID_KEY)
end
def initialize(max_id: PurchaseRefundPolicy.last!.id)
@max_id = max_id
end
def process
invalid_policy_ids = []
eligible_purchase_refund_policies.find_in_batches do |batch|
ReplicaLagWatcher.watch
Rails.logger.info "Processing purchase refund policies #{batch.first.id} to #{batch.last.id}"
batch.each do |purchase_refund_policy|
next if purchase_refund_policy.max_refund_period_in_days.present?
max_refund_period_in_days = purchase_refund_policy.determine_max_refund_period_in_days
if max_refund_period_in_days.nil?
Rails.logger.debug("No exact match found for title '#{purchase_refund_policy.title}', skipping")
next
end
begin
purchase_refund_policy.with_lock do
purchase_refund_policy.update!(max_refund_period_in_days: max_refund_period_in_days)
Rails.logger.info "PurchaseRefundPolicy: #{purchase_refund_policy.id}: updated with max allowed refund period of #{max_refund_period_in_days} days"
end
rescue => e
invalid_policy_ids << { purchase_refund_policy.id => e.message }
end
end
$redis.set(LAST_PROCESSED_ID_KEY, batch.last.id, ex: 1.month)
end
Rails.logger.info "Invalid purchase refund policy ids: #{invalid_policy_ids}" if invalid_policy_ids.any?
end
private
attr_reader :max_id
def eligible_purchase_refund_policies
first_policy_id = [first_eligible_policy_id, $redis.get(LAST_PROCESSED_ID_KEY).to_i + 1].max
PurchaseRefundPolicy.where(id: first_policy_id..max_id)
end
def first_eligible_policy_id
PurchaseRefundPolicy.first!.id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/assign_physical_product_types.rb | app/services/onetime/assign_physical_product_types.rb | # frozen_string_literal: true
# This script updates products marked as `is_physical` with a `native_type` of "digital" to have a `native_type` of "physical"
#
# Steps:
# 1. In Rails console: Onetime::AssignPhysicalProductTypes.process
class Onetime::AssignPhysicalProductTypes
def self.process
invalid_products = Link.is_physical.where(native_type: Link::NATIVE_TYPE_DIGITAL)
invalid_products.find_in_batches do |products|
ReplicaLagWatcher.watch
Link.where(id: products.map(&:id)).update_all(native_type: Link::NATIVE_TYPE_PHYSICAL)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/send_gumroad_day_fee_saved_email.rb | app/services/onetime/send_gumroad_day_fee_saved_email.rb | # frozen_string_literal: true
class Onetime::SendGumroadDayFeeSavedEmail
def self.process
start_time = DateTime.new(2024, 4, 4, 0, 0, 0, "+14:00")
end_time = DateTime.new(2024, 4, 5, 0, 0, 0, "-13:00")
Purchase.joins(:seller)
.non_free
.not_recurring_charge
.where(purchase_state: Purchase::NON_GIFT_SUCCESS_STATES)
.where("purchases.created_at >= ? AND purchases.created_at < ?", start_time, end_time)
.where("users.json_data LIKE '%gumroad_day_timezone%'")
.where("users.id > ?", $redis.get("gumroad_day_fee_saved_email_last_user_id").to_i)
.select("users.id")
.distinct
.order("users.id")
.each do |user|
ReplicaLagWatcher.watch
next unless User.find(user.id).gumroad_day_saved_fee_cents > 0
CreatorMailer.gumroad_day_fee_saved(seller_id: user.id).deliver_later(queue: "mongo")
$redis.set("gumroad_day_fee_saved_email_last_user_id", user.id)
puts "Enqueued gumroad_day_fee_saved email for #{user.id}"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/disable_recurring_subscription_notifications.rb | app/services/onetime/disable_recurring_subscription_notifications.rb | # frozen_string_literal: true
# One-time script to disable recurring subscription charge notifications
# (both email and push) for existing users.
#
# Usage:
# Onetime::DisableRecurringSubscriptionNotifications.process
class Onetime::DisableRecurringSubscriptionNotifications
def self.process
updated_users = 0
User.alive.find_in_batches(batch_size: 1000) do |batch|
batch.each do |user|
changed = false
if user.enable_recurring_subscription_charge_email?
user.enable_recurring_subscription_charge_email = false
changed = true
end
if user.enable_recurring_subscription_charge_push_notification?
user.enable_recurring_subscription_charge_push_notification = false
changed = true
end
if changed
# Skip validations/callbacks; we are only toggling flags.
user.save!(validate: false)
updated_users += 1
end
end
end
Rails.logger.info "Onetime::DisableRecurringSubscriptionNotifications: disabled flags for #{updated_users} users"
true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/enable_refund_policy_for_sellers_with_refund_policies.rb | app/services/onetime/enable_refund_policy_for_sellers_with_refund_policies.rb | # frozen_string_literal: true
# About 40K sellers out of 22M have product refund policies
#
class Onetime::EnableRefundPolicyForSellersWithRefundPolicies < Onetime::Base
LAST_PROCESSED_ID_KEY = :last_processed_seller_for_refund_policy_id
def self.reset_last_processed_seller_id
$redis.del(LAST_PROCESSED_ID_KEY)
end
def initialize(max_id: ProductRefundPolicy.last!.id)
@max_id = max_id
end
def process
invalid_seller_ids = []
eligible_product_refund_policies.find_in_batches do |batch|
ReplicaLagWatcher.watch
Rails.logger.info "Processing product refund policies #{batch.first.id} to #{batch.last.id}"
batch.each do |product_refund_policy|
seller = product_refund_policy.seller
if seller.refund_policy_enabled?
Rails.logger.info "Seller: #{seller.id}: skipped"
next
else
max_refund_period_in_days = seller.has_all_eligible_refund_policies_as_no_refunds? ? 0 : 30
seller.with_lock do
seller.refund_policy.update!(max_refund_period_in_days:)
seller.update!(refund_policy_enabled: true)
ContactingCreatorMailer.refund_policy_enabled_email(seller.id).deliver_later
Rails.logger.info "Seller: #{seller.id}: processed and email sent"
end
end
rescue => e
invalid_seller_ids << { seller.id => e.message }
end
$redis.set(LAST_PROCESSED_ID_KEY, batch.last.id, ex: 1.month)
end
Rails.logger.info "Invalid seller ids: #{invalid_seller_ids}" if invalid_seller_ids.any?
end
private
attr_reader :max_id
def eligible_product_refund_policies
first_product_refund_policy_id = [first_eligible_product_refund_policy_id, $redis.get(LAST_PROCESSED_ID_KEY).to_i + 1].max
ProductRefundPolicy.where.not(product_id: nil).where(id: first_product_refund_policy_id..max_id)
end
def first_eligible_product_refund_policy_id
ProductRefundPolicy.first!.id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/backfill_user_tax_forms.rb | app/services/onetime/backfill_user_tax_forms.rb | # frozen_string_literal: true
class Onetime::BackfillUserTaxForms
def initialize(stripe_account_ids:, tax_year:, tax_form_type:)
@stripe_account_ids = stripe_account_ids
@tax_year = tax_year
@tax_form_type = tax_form_type
@results = { created: 0, skipped: 0, errors: {} }
validate_inputs!
end
def perform
stripe_account_ids.each { backfill_stripe_account(_1) }
puts "Done!"
end
private
attr_reader :stripe_account_ids, :tax_year, :tax_form_type, :results
def validate_inputs!
unless UserTaxForm::TAX_FORM_TYPES.include?(tax_form_type)
raise ArgumentError, "Invalid tax_form_type: #{tax_form_type}. Must be one of: #{UserTaxForm::TAX_FORM_TYPES.join(', ')}"
end
unless tax_year.is_a?(Integer) && tax_year >= UserTaxForm::MIN_TAX_YEAR && tax_year <= Time.current.year
raise ArgumentError, "Invalid year: #{tax_year}. Must be between #{MIN_TAX_YEAR} and #{Time.current.year}"
end
unless stripe_account_ids.is_a?(Array) && stripe_account_ids.all? { |id| id.is_a?(String) }
raise ArgumentError, "stripe_account_ids must be an array of strings"
end
end
def backfill_stripe_account(stripe_account_id)
merchant_account = MerchantAccount.stripe.find_by(charge_processor_merchant_id: stripe_account_id)
unless merchant_account
@results[:errors][stripe_account_id] ||= []
@results[:errors][stripe_account_id] << "Stripe account not found"
return
end
user = merchant_account.user
tax_form = UserTaxForm.find_or_initialize_by(user:, tax_year:, tax_form_type:)
if tax_form.new_record?
tax_form.stripe_account_id = stripe_account_id
if tax_form.save
@results[:created] += 1
puts "[CREATED] user_id=#{user.id}, year=#{tax_year}, type=#{tax_form_type}, stripe_account_id=#{stripe_account_id}"
else
@results[:errors][stripe_account_id] ||= []
@results[:errors][stripe_account_id] << "Failed to save for user_id=#{user.id}: #{tax_form.errors.full_messages.join(', ')}"
end
else
@results[:skipped] += 1
puts "[SKIPPED] user_id=#{user.id}, year=#{tax_year}, type=#{tax_form_type}"
end
rescue => e
@results[:errors][stripe_account_id] ||= []
@results[:errors][stripe_account_id] << "Error processing #{stripe_account_id}: #{e.message}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/revert_to_product_level_refund_policies.rb | app/services/onetime/revert_to_product_level_refund_policies.rb | # frozen_string_literal: true
# Used to process select sellers manually
# For the rest, we'll use `seller_refund_policy_disabled_for_all` feature flag to override User#refund_policy_enabled flag
#
class Onetime::RevertToProductLevelRefundPolicies < Onetime::Base
LAST_PROCESSED_ID_KEY = :last_processed_seller_for_revert_to_product_level_refund_policy_id
attr_reader :seller_ids, :invalid_seller_ids
def self.reset_last_processed_id
$redis.del(LAST_PROCESSED_ID_KEY)
end
def initialize(seller_ids: [])
raise ArgumentError, "Seller ids not found" if seller_ids.blank?
@seller_ids = seller_ids
@invalid_seller_ids = []
@last_processed_index = ($redis.get(LAST_PROCESSED_ID_KEY) || -1).to_i
end
def process
ReplicaLagWatcher.watch()
seller_ids.each_with_index do |seller_id, index|
if index <= @last_processed_index
Rails.logger.info "Seller: #{seller_id} (#{index + 1}/#{seller_ids.size}): skipped (already processed in previous run)"
next
end
message_prefix = "Seller: #{seller_id} (#{index + 1}/#{seller_ids.size})"
seller = User.find(seller_id)
if !seller.account_active?
Rails.logger.info "#{message_prefix}: skipped (not active)"
next
end
if seller.refund_policy_enabled?
seller.with_lock do
seller.update!(refund_policy_enabled: false)
ContactingCreatorMailer.product_level_refund_policies_reverted(seller.id).deliver_later
Rails.logger.info "#{message_prefix}: processed and email sent"
end
else
Rails.logger.info "#{message_prefix}: skipped (already processed)"
next
end
$redis.set(LAST_PROCESSED_ID_KEY, index, ex: 1.month)
rescue => e
Rails.logger.info "#{message_prefix}: error: #{e.message}"
invalid_seller_ids << { seller_id => e.message }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/compile_gumroad_daily_analytics_from_beginning.rb | app/services/onetime/compile_gumroad_daily_analytics_from_beginning.rb | # frozen_string_literal: true
class Onetime::CompileGumroadDailyAnalyticsFromBeginning
def self.process
start_date = GUMROAD_STARTED_DATE
end_date = Date.today
(start_date..end_date).each do |date|
GumroadDailyAnalytic.import(date)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/set_max_allowed_refund_period_for_product_refund_policies.rb | app/services/onetime/set_max_allowed_refund_period_for_product_refund_policies.rb | # frozen_string_literal: true
class Onetime::SetMaxAllowedRefundPeriodForProductRefundPolicies < Onetime::Base
LAST_PROCESSED_ID_KEY = :last_processed_id
def self.reset_last_processed_id
$redis.del(LAST_PROCESSED_ID_KEY)
end
def initialize(max_id: ProductRefundPolicy.last!.id)
@max_id = max_id
end
def process
invalid_policy_ids = []
eligible_product_refund_policies.find_in_batches do |batch|
ReplicaLagWatcher.watch
Rails.logger.info "Processing product refund policies #{batch.first.id} to #{batch.last.id}"
batch.each do |product_refund_policy|
next if product_refund_policy.max_refund_period_in_days.present?
max_refund_period_in_days = product_refund_policy.determine_max_refund_period_in_days
begin
product_refund_policy.with_lock do
product_refund_policy.update!(max_refund_period_in_days:)
Rails.logger.info "ProductRefundPolicy: #{product_refund_policy.id}: updated with max allowed refund period of #{max_refund_period_in_days} days"
end
rescue => e
invalid_policy_ids << { product_refund_policy.id => e.message }
end
end
$redis.set(LAST_PROCESSED_ID_KEY, batch.last.id, ex: 1.month)
end
Rails.logger.info "Invalid product refund policy ids: #{invalid_policy_ids}" if invalid_policy_ids.any?
end
private
attr_reader :max_id
def eligible_product_refund_policies
first_product_refund_policy_id = [first_eligible_product_refund_policy_id, $redis.get(LAST_PROCESSED_ID_KEY).to_i + 1].max
ProductRefundPolicy.where.not(product_id: nil).where(id: first_product_refund_policy_id..max_id)
end
def first_eligible_product_refund_policy_id
ProductRefundPolicy.where.not(product_id: nil).first!.id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/email_creators_quarterly_recap.rb | app/services/onetime/email_creators_quarterly_recap.rb | # frozen_string_literal: true
class Onetime::EmailCreatorsQuarterlyRecap
DEFAULT_REPLY_TO_EMAIL = "Sahil Lavingia <sahil@gumroad.com>"
MIN_QUARTER_SIZE_IN_DAYS = 85.days
private_constant :MIN_QUARTER_SIZE_IN_DAYS
attr_reader :installment_external_id, :start_time, :end_time, :reply_to, :skip_user_ids, :emailed_user_ids
def initialize(installment_external_id:, start_time:, end_time:, skip_user_ids: [], reply_to: DEFAULT_REPLY_TO_EMAIL)
@installment_external_id = installment_external_id
@start_time = start_time.to_date
@end_time = end_time.to_date
@skip_user_ids = skip_user_ids
@reply_to = reply_to
@emailed_user_ids = []
end
def process
installment = Installment.find_by_external_id(installment_external_id)
raise "Installment not found" unless installment.present?
raise "Installment must not allow comments" if installment.allow_comments?
raise "Installment must not be published or scheduled to publish" if installment.published? || installment.ready_to_publish?
raise "Date range must be at least 85 days" if (end_time - start_time).days < MIN_QUARTER_SIZE_IN_DAYS
WithMaxExecutionTime.timeout_queries(seconds: 10.minutes) do
Purchase.where(created_at: start_time..end_time).successful.select(:seller_id).distinct.pluck(:seller_id).each_slice(1000) do |user_ids_slice|
User.where(id: user_ids_slice).not_suspended.alive.find_each do |seller|
next if seller.id.in?(skip_user_ids)
next if seller.form_email.blank?
OneOffMailer.email_using_installment(email: seller.form_email, installment_external_id:, reply_to:).deliver_later(queue: "low")
@emailed_user_ids << seller.id
end
end
end
emailed_user_ids
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/create_seller_refund_policies.rb | app/services/onetime/create_seller_refund_policies.rb | # frozen_string_literal: true
class Onetime::CreateSellerRefundPolicies < Onetime::Base
LAST_PROCESSED_SELLER_ID_KEY = :last_processed_seller_for_refund_policy_id
def self.reset_last_processed_seller_id
$redis.del(LAST_PROCESSED_SELLER_ID_KEY)
end
def initialize(max_id: User.last!.id)
@max_id = max_id
end
def process
invalid_seller_ids = []
eligible_sellers.find_in_batches do |batch|
ReplicaLagWatcher.watch
Rails.logger.info "Processing sellers #{batch.first.id} to #{batch.last.id}"
batch.each do |seller|
seller.create_refund_policy!
rescue => e
invalid_seller_ids << { seller.id => e.message }
end
$redis.set(LAST_PROCESSED_SELLER_ID_KEY, batch.last.id, ex: 2.months)
end
Rails.logger.info "Invalid seller ids: #{invalid_seller_ids}" if invalid_seller_ids.any?
end
private
attr_reader :max_id
def eligible_sellers
first_seller_id = [first_eligible_seller_id, $redis.get(LAST_PROCESSED_SELLER_ID_KEY).to_i + 1].max
User.left_joins(:refund_policy)
.where(refund_policies: { id: nil })
.where(id: first_seller_id..max_id)
end
def first_eligible_seller_id
User.first!.id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product_review/update_service.rb | app/services/product_review/update_service.rb | # frozen_string_literal: true
class ProductReview::UpdateService
def initialize(product_review, rating:, message:, video_options: {})
@product_review = product_review
@rating = rating
@message = message
@video_options = video_options.to_h.with_indifferent_access
end
def update
@product_review.transaction do
# Lock to avoid race condition as we update the aggregated stats based on
# the changes.
@product_review.with_lock do
update_rating_and_message
update_video
end
end
@product_review
end
private
def update_rating_and_message
@product_review.update!(rating: @rating, message: @message)
end
def update_video
create_video(@video_options[:create] || {})
destroy_video(@video_options[:destroy] || {})
end
def create_video(options)
return unless options[:url]
@product_review.videos.alive.pending_review.each(&:mark_deleted!)
@product_review.videos.create!(
approval_status: :pending_review,
video_file_attributes: {
url: options[:url],
thumbnail: options[:thumbnail_signed_id],
user_id: @product_review.purchase.purchaser_id
}
)
end
def destroy_video(options)
return unless options[:id]
@product_review.videos.find_by_external_id(options[:id])&.mark_deleted
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/create_bundle_product_purchase_service.rb | app/services/purchase/create_bundle_product_purchase_service.rb | # frozen_string_literal: true
class Purchase::CreateBundleProductPurchaseService
def initialize(purchase, bundle_product)
@purchase = purchase
@bundle_product = bundle_product
end
def perform
product_purchase = Purchase.create!(
link: @bundle_product.product,
seller: @purchase.seller,
purchaser: @purchase.purchaser,
price_cents: 0,
total_transaction_cents: 0,
displayed_price_cents: 0,
gumroad_tax_cents: 0,
shipping_cents: 0,
fee_cents: 0,
email: @purchase.email,
full_name: @purchase.full_name,
street_address: @purchase.street_address,
country: @purchase.country,
state: @purchase.state,
zip_code: @purchase.zip_code,
city: @purchase.city,
ip_address: @purchase.ip_address,
ip_state: @purchase.ip_state,
ip_country: @purchase.ip_country,
browser_guid: @purchase.browser_guid,
referrer: @purchase.referrer,
was_product_recommended: @purchase.was_product_recommended,
variant_attributes: @bundle_product.variant.present? ? [@bundle_product.variant] : [],
quantity: @bundle_product.quantity * @purchase.quantity,
is_bundle_product_purchase: true,
is_gift_sender_purchase: @purchase.is_gift_sender_purchase,
is_gift_receiver_purchase: @purchase.is_gift_receiver_purchase
)
# Custom fields for bundle products are temporarily saved on the bundle purchase until we can assign them
# to their respective purchase records.
@purchase.purchase_custom_fields.where(bundle_product: @bundle_product).each { _1.update!(purchase: product_purchase, bundle_product: nil) }
BundleProductPurchase.create!(bundle_purchase: @purchase, product_purchase:)
product_purchase.update_balance_and_mark_successful!
Purchase::AssociateBundleProductLevelGiftService
.new(bundle_purchase: @purchase, bundle_product: @bundle_product)
.perform
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/variant_updater_service.rb | app/services/purchase/variant_updater_service.rb | # frozen_string_literal: true
class Purchase::VariantUpdaterService
attr_reader :purchase, :variant_id, :new_variant, :product, :new_quantity
def initialize(purchase:, variant_id:, quantity:)
@purchase = purchase
@variant_id = variant_id
@new_quantity = quantity
end
def perform
@product = purchase.link
if product.skus_enabled?
@new_variant = product.skus.find_by_external_id!(variant_id)
new_variants = [new_variant]
else
@new_variant = Variant.find_by_external_id!(variant_id)
variant_category = new_variant.variant_category
if variant_category.link != product
return false
end
new_variants = purchase.variant_attributes.where.not(variant_category_id: variant_category.id).to_a
new_variants << new_variant
end
return false unless new_variants.all? { |variant| sufficient_inventory?(variant, new_quantity - (purchase.variant_attributes == new_variants ? purchase.quantity : 0)) }
purchase.quantity = new_quantity
purchase.variant_attributes = new_variants
purchase.save!
if purchase.is_gift_sender_purchase?
Purchase::VariantUpdaterService.new(
purchase: purchase.gift.giftee_purchase,
variant_id:,
quantity: new_quantity
).perform
end
Purchase::Searchable::VariantAttributeCallbacks.variants_changed(purchase)
true
rescue ActiveRecord::RecordNotFound
false
end
private
def sufficient_inventory?(variant, quantity)
variant.quantity_left ? variant.quantity_left >= quantity : true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/create_service.rb | app/services/purchase/create_service.rb | # frozen_string_literal: true
class Purchase::CreateService < Purchase::BaseService
include CurrencyHelper
RESERVED_URL_PARAMETERS = %w[code wanted referrer email as_modal as_embed debug affiliate_id].freeze
INVENTORY_LOCK_ACQUISITION_TIMEOUT = 50.seconds
attr_reader :product, :params, :purchase_params, :gift_params, :buyer
attr_accessor :purchase, :gift
def initialize(product:, params:, buyer: nil)
@product = product
@params = params
@purchase_params = params[:purchase]
@gift_params = params[:gift].presence
@buyer = buyer
end
def perform
unless @product.allow_parallel_purchases?
inventory_semaphore = SuoSemaphore.product_inventory(@product.id, acquisition_timeout: INVENTORY_LOCK_ACQUISITION_TIMEOUT)
inventory_lock_token = inventory_semaphore.lock
if inventory_lock_token.nil?
Rails.logger.warn("Could not acquire lock for product_inventory semaphore (product id: #{@product.id})")
return nil, "Sorry, something went wrong. Please try again."
end
end
begin
# create gift if necessary
self.gift = create_gift if is_gift?
# run pre-build validations
validate_perceived_price
validate_zip_code
# build primary (non-gift) purchase
self.purchase = build_purchase(purchase_params.merge(gift_given: gift))
purchase.is_part_of_combined_charge = params[:is_part_of_combined_charge]
# run post-build validations (to ensure a purchase is present along with the
# error message, required for rendering errors in bundle checkout)
validate_perceived_free_trial_params
if @product.user.account_level_refund_policy_enabled?
purchase.build_purchase_refund_policy(
max_refund_period_in_days: @product.user.refund_policy.max_refund_period_in_days,
title: @product.user.refund_policy.title,
fine_print: @product.user.refund_policy.fine_print
)
elsif @product.product_refund_policy_enabled?
purchase.build_purchase_refund_policy(
max_refund_period_in_days: @product.product_refund_policy.max_refund_period_in_days,
title: @product.product_refund_policy.title,
fine_print: @product.product_refund_policy.fine_print
)
end
# build pre-order if purchase is for pre-order product & return
if purchase.is_preorder_authorization
build_preorder
return purchase, nil
elsif product.is_in_preorder_state?
# This should never happen unless the request is tampered with:
raise Purchase::PurchaseInvalid, "Something went wrong. Please refresh the page to pre-order the product."
end
purchase.is_commission_deposit_purchase = product.native_type == Link::NATIVE_TYPE_COMMISSION
# associate correct price for membership product
if product.is_recurring_billing || purchase.is_installment_payment
# For membership products, params[:price_id] should be provided but if
# not, or if a price_id is invalid, associate the default price.
price = params[:price_id].present? ?
product.prices.alive.find_by_external_id(params[:price_id]) :
product.default_price
purchase.price = price || product.default_price
end
if purchase.offer_code&.minimum_amount_cents.present?
valid_items = params[:cart_items]
valid_items = valid_items.filter { purchase.offer_code.products.find_by(unique_permalink: _1[:permalink]).present? } unless purchase.offer_code.universal
if valid_items.map { _1[:price_cents].to_i }.sum < purchase.offer_code.minimum_amount_cents
raise Purchase::PurchaseInvalid, "Sorry, you have not met the offer code's minimum amount."
end
end
if params[:accepted_offer].present?
upsell = Upsell.available_to_customers.find_by_external_id(params[:accepted_offer][:id])
raise Purchase::PurchaseInvalid, "Sorry, this offer is no longer available." unless upsell.present?
if upsell.cross_sell?
if upsell.not_replace_selected_products?
cart_product_permalinks = params[:cart_items].reject { _1[:permalink] == product.unique_permalink }.map { _1[:permalink] }
if upsell.not_is_content_upsell? && (upsell.universal ? product.user.products : upsell.selected_products).where(unique_permalink: cart_product_permalinks).empty?
raise Purchase::PurchaseInvalid, "The cart does not have any products to which the upsell applies."
end
end
# The original discount is retained if it is better than the upsell
# discount. The client can't automatically set the upsell discount
# because it doesn't have a "code". Thus, upsell discount should only
# be applied when the purchase does not already have a discount code.
purchase.offer_code ||= upsell.offer_code unless params[:is_purchasing_power_parity_discounted]
end
purchase.build_upsell_purchase(
upsell:,
selected_product: Link.find_by_external_id(params[:accepted_offer][:original_product_id]),
upsell_variant: params[:accepted_offer][:original_variant_id].present? ?
upsell.upsell_variants.alive.find_by(
selected_variant: BaseVariant.find_by_external_id(params[:accepted_offer][:original_variant_id])
) :
nil
)
raise Purchase::PurchaseInvalid, purchase.upsell_purchase.errors.first.message unless purchase.upsell_purchase.valid?
end
if params[:tip_cents].present? && params[:tip_cents] > 0
raise Purchase::PurchaseInvalid, "Tip is not allowed for this product" unless purchase.seller.tipping_enabled? && product.not_is_tiered_membership?
raise Purchase::PurchaseInvalid, "Tip is too large for this purchase" if (purchase_params[:perceived_price_cents].ceil - params[:tip_cents].floor) < purchase.minimum_paid_price_cents
purchase.build_tip(value_cents: params[:tip_cents], value_usd_cents: get_usd_cents(product.price_currency_type, params[:tip_cents]))
end
validate_bundle_products
purchase.prepare_for_charge!
purchase.build_purchase_wallet_type(wallet_type: params[:wallet_type]) if params[:wallet_type].present?
# Make sure the giftee purchase is created successfully before attempting a charge
create_giftee_purchase if purchase.is_gift_sender_purchase
# For bundle purchases we create a payment method and set up future charges for it,
# then process all purchases off-session in order to avoid multiple SCA pop-ups.
purchase.charge!(off_session: purchase_params[:is_multi_buy]) unless purchase.is_part_of_combined_charge?
raise Purchase::PurchaseInvalid, purchase.errors.full_messages[0] if purchase.errors.present?
# TODO(helen): remove after debugging potential offer code vulnerability
if purchase.displayed_price_cents == 0 && purchase.offer_code.present?
logger.info("Free purchase with offer code - purchaser_email: #{purchase.email} | offer_code: #{purchase_params[:discount_code]} | id: #{purchase.id} | params: #{params}")
end
rescue Purchase::PurchaseInvalid => e
if purchase.present?
handle_purchase_failure
else
gift.mark_failed if gift.present?
end
return purchase, e.message
end
if purchase.requires_sca?
# Check back later to see if the purchase has been completed. If not, transition to a failed state.
FailAbandonedPurchaseWorker.perform_in(ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase.id)
else
handle_purchase_success unless purchase.is_part_of_combined_charge?
end
return purchase, nil
ensure
inventory_semaphore.unlock(inventory_lock_token) if inventory_lock_token
handle_purchase_failure if purchase&.persisted? && purchase.in_progress? &&
!purchase.requires_sca? && !purchase.is_part_of_combined_charge?
end
private
def is_gift?
!!params[:is_gift]
end
def create_gift
raise Purchase::PurchaseInvalid, "Test gift purchases have not been enabled yet." if buyer == product.user
raise Purchase::PurchaseInvalid, "You cannot gift a product to yourself. Please try gifting to another email." if giftee_email == purchase_params[:email]
raise Purchase::PurchaseInvalid, "Gift purchases cannot be on installment plans." if params[:pay_in_installments]
if product.can_gift?
gift = product.gifts.build(giftee_email:, gift_note: gift_params[:gift_note], gifter_email: params[:purchase][:email], is_recipient_hidden: gift_params[:giftee_email].blank?)
error_message = gift.save ? nil : gift.errors.full_messages[0]
raise Purchase::PurchaseInvalid, error_message if error_message.present?
gift
else
raise Purchase::PurchaseInvalid, "Gifting is not yet enabled for pre-orders."
end
end
def validate_perceived_price
if purchase_params[:perceived_price_cents] && !Purchase::MAX_PRICE_RANGE.cover?(purchase_params[:perceived_price_cents])
raise Purchase::PurchaseInvalid, "Purchase price is invalid. Please check the price."
end
end
def validate_zip_code
country_code_for_validation = purchase_params[:country].presence || purchase_params[:sales_tax_country_code_election]
if purchase_params[:perceived_price_cents].to_i > 0 && country_code_for_validation == Compliance::Countries::USA.alpha2 && UsZipCodes.identify_state_code(purchase_params[:zip_code]).nil?
Rails.logger.info("Zip code #{purchase_params[:zip_code]} is invalid, customer email #{purchase_params[:email]}")
raise Purchase::PurchaseInvalid, "You entered a ZIP Code that doesn't exist within your country."
end
end
def validate_perceived_free_trial_params
return if is_gift?
free_trial_params = params[:perceived_free_trial_duration]
if product.free_trial_enabled?
if !free_trial_params.present? || !free_trial_params[:amount].present? || !free_trial_params[:unit].present?
raise Purchase::PurchaseInvalid, "Invalid free trial information provided. Please try again."
elsif free_trial_params[:amount].to_i != product.free_trial_duration_amount || free_trial_params[:unit] != product.free_trial_duration_unit
raise Purchase::PurchaseInvalid, "The product's free trial has changed, please refresh the page!"
end
elsif free_trial_params.present?
raise Purchase::PurchaseInvalid, "Invalid free trial information provided. Please try again."
end
end
def validate_bundle_products
return unless product.is_bundle?
product.bundle_products.alive.each do |bundle_product|
if params[:bundle_products].none? { _1[:product_id] == bundle_product.product.external_id && _1[:variant_id] == bundle_product.variant&.external_id && _1[:quantity].to_i == bundle_product.quantity }
raise Purchase::PurchaseInvalid, "The bundle's contents have changed. Please refresh the page!"
end
end
end
def build_purchase(params_for_purchase)
params_for_purchase[:country] = ISO3166::Country[params_for_purchase[:country]]&.common_name
purchase = product.sales.build(params_for_purchase)
purchase.affiliate = product.collaborator if product.collaborator.present?
should_ship = product.is_physical || product.require_shipping
purchase.country = nil unless should_ship
purchase.country ||= ISO3166::Country[params_for_purchase[:sales_tax_country_code_election]]&.common_name
set_purchaser_for(purchase, params_for_purchase[:email])
purchase.is_installment_payment = params[:pay_in_installments] && product.allow_installment_plan?
purchase.installment_plan = product.installment_plan if purchase.is_installment_payment
purchase.save_card = !!params_for_purchase[:save_card] || (product.is_recurring_billing && !is_gift?) || purchase.is_preorder_authorization || purchase.is_installment_payment
purchase.seller = product.user
purchase.is_gift_sender_purchase = is_gift? unless params_for_purchase.has_key?(:is_gift_receiver_purchase)
purchase.offer_code = product.find_offer_code(code: purchase.discount_code.downcase.strip) if purchase.discount_code.present?
purchase.business_vat_id = (params_for_purchase[:business_vat_id] && params_for_purchase[:business_vat_id].size > 0 ? params_for_purchase[:business_vat_id] : nil)
purchase.is_original_subscription_purchase = (product.is_recurring_billing && !params_for_purchase[:is_gift_receiver_purchase]) || purchase.is_installment_payment
purchase.is_free_trial_purchase = product.free_trial_enabled? && !is_gift?
purchase.should_exclude_product_review = product.free_trial_enabled? && !is_gift?
Shipment.create(purchase:) if should_ship
if params[:variants].present?
params[:variants].each do |external_id|
variant = product.current_base_variants.find_by_external_id(external_id)
if variant.present?
purchase.variant_attributes << variant
else
purchase.errors.add(:base, "The product's variants have changed, please refresh the page!")
raise Purchase::PurchaseInvalid, "The product's variants have changed, please refresh the page!"
end
end
elsif product.is_tiered_membership
purchase.variant_attributes << product.tiers.first
elsif product.is_physical && product.skus.is_default_sku.present?
purchase.variant_attributes << product.skus.is_default_sku.first
end
if product.native_type == Link::NATIVE_TYPE_CALL
start_time = Time.zone.parse(params[:call_start_time] || "")
duration_in_minutes = purchase.variant_attributes.first&.duration_in_minutes
if start_time.blank? || duration_in_minutes.blank?
raise Purchase::PurchaseInvalid, "Please select a start time."
end
end_time = start_time + duration_in_minutes.minutes
purchase.build_call(start_time:, end_time:)
end
build_custom_fields(purchase, params[:custom_fields] || [], product:)
product.bundle_products.alive.each do |bundle_product|
# Temporarily create custom fields on the bundle purchase in case it can't complete yet due to SCA.
# The custom fields will be moved to each product purchase when the receipt is generated.
custom_fields_params = params[:bundle_products]&.find { _1[:product_id] == bundle_product.product.external_id }&.dig(:custom_fields)
build_custom_fields(purchase, custom_fields_params || [], bundle_product:)
end
purchase.url_parameters = parse_url_parameters(params_for_purchase[:url_parameters])
purchase
end
def build_custom_fields(purchase, custom_fields_params, product: nil, bundle_product: nil)
values = custom_fields_params.to_h { [_1[:id], _1[:value]] }
(product || bundle_product.product).checkout_custom_fields.each do |custom_field|
next if custom_field.type == CustomField::TYPE_TEXT && !custom_field.required? && values[custom_field.external_id].blank?
purchase.purchase_custom_fields << PurchaseCustomField.build_from_custom_field(custom_field:, value: values[custom_field.external_id], bundle_product:)
end
end
def create_giftee_purchase
giftee_purchase_params = purchase_params.except(:discount_code, :paypal_order_id).merge(
email: giftee_email,
is_multi_buy: false,
is_preorder_authorization: false,
perceived_price_cents: 0,
is_gift_sender_purchase: false,
is_gift_receiver_purchase: true
)
giftee_purchase = build_purchase(giftee_purchase_params)
giftee_purchase.purchaser = giftee_purchaser
giftee_purchase.gift_received = gift
giftee_purchase.process!
raise Purchase::PurchaseInvalid, giftee_purchase.errors.full_messages[0] if giftee_purchase.errors.present?
end
def giftee_purchaser
@_giftee_purchaser ||= gift_params[:giftee_id].present? ? User.alive.find_by_external_id(gift_params[:giftee_id]) : User.alive.by_email(gift_params[:giftee_email]).last
end
def giftee_email
giftee_purchaser&.email || gift_params[:giftee_email]
end
def build_preorder
raise Purchase::PurchaseInvalid, "The product was just released. Refresh the page to purchase it." unless product.is_in_preorder_state?
self.preorder = product.preorder_link.build_preorder(purchase)
if purchase.is_part_of_combined_charge?
purchase.prepare_for_charge!
else
preorder.authorize!
error_message = preorder.errors.full_messages[0]
if purchase.is_test_purchase?
preorder.mark_test_authorization_successful!
elsif error_message.present?
raise Purchase::PurchaseInvalid, error_message
elsif purchase.requires_sca?
# Leave the preorder in `in_progress` state until the the required UI action is completed.
# Check back later to see if it has been completed. If not, transition to a failed state.
FailAbandonedPurchaseWorker.perform_in(ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase.id)
else
preorder.mark_authorization_successful!
end
end
end
def set_purchaser_for(purchase, purchase_email)
if buyer.present?
purchase.purchaser = buyer unless purchase.is_gift_receiver_purchase
else
user_from_email = User.find_by(email: purchase_email)
# This limits test purchase to be done in logged out mode
if purchase.link.user != user_from_email
purchase.purchaser = user_from_email
end
end
end
def parse_url_parameters(url_parameters_string)
# Turns string into json object and removes reserved paramters
return nil if url_parameters_string.blank?
url_parameters_string.tr!("'", "\"") if /{ *'/.match?(url_parameters_string)
url_params = begin
JSON.parse(url_parameters_string)
rescue StandardError
nil
end
# TODO: Only filter on the frontend once the new checkout experience is rolled out
if url_params.present?
url_params.reject do |parameter_name, _parameter_value|
RESERVED_URL_PARAMETERS.include?(parameter_name)
end
end
end
end
class Purchase::PurchaseInvalid < StandardError; end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/confirm_service.rb | app/services/purchase/confirm_service.rb | # frozen_string_literal: true
# Finalizes the purchase once the charge has been confirmed by the user on the front-end.
class Purchase::ConfirmService < Purchase::BaseService
attr_reader :params
def initialize(purchase:, params:)
@purchase = purchase
@preorder = purchase.preorder
@params = params
end
def perform
# Free purchases included in the order are already marked successful
# as they are not dependent on the SCA response. We can safely return no-error response
# for any purchase that is already successful.
return if purchase.successful?
# In the purchase has changed its state and is no longer in_progress, we can't confirm it.
# Example 1: the time to complete SCA has expired and we have marked this purchase as failed in the background.
# Example 2: user has purchased the same product in another tab and we canceled this purchase as potential duplicate.
return "There is a temporary problem, please try again (your card was not charged)." unless purchase.in_progress?
error_message = check_for_card_handling_error
return error_message if error_message.present?
if purchase.is_preorder_authorization?
mark_preorder_authorized
return
end
purchase.confirm_charge_intent!
if purchase.errors.present?
error_message = purchase.errors.full_messages[0]
handle_purchase_failure
return error_message
end
if purchase.is_upgrade_purchase? || purchase.subscription&.is_resubscription_pending_confirmation?
purchase.subscription.handle_purchase_success(purchase)
if purchase.subscription.is_resubscription_pending_confirmation?
purchase.subscription.send_restart_notifications!
purchase.subscription.update_flag!(:is_resubscription_pending_confirmation, false, true)
end
UpdateIntegrationsOnTierChangeWorker.perform_async(purchase.subscription.id)
else
handle_purchase_success
end
nil
end
private
def check_for_card_handling_error
card_data_handling_error = CardParamsHelper.check_for_errors(params)
if card_data_handling_error.present?
purchase.stripe_error_code = card_data_handling_error.card_error_code
handle_purchase_failure
PurchaseErrorCode.customer_error_message(card_data_handling_error.error_message)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/sync_status_with_charge_processor_service.rb | app/services/purchase/sync_status_with_charge_processor_service.rb | # frozen_string_literal: true
# Syncs the purchase status with Stripe/PayPal
class Purchase::SyncStatusWithChargeProcessorService
attr_accessor :purchase, :mark_as_failed
def initialize(purchase, mark_as_failed: false)
@purchase = purchase
@mark_as_failed = mark_as_failed
end
def perform
return false unless purchase.in_progress? || purchase.failed?
ActiveRecord::Base.transaction do
if purchase.failed?
purchase.update!(purchase_state: "in_progress")
if purchase.is_gift_sender_purchase
purchase.gift_given&.update!(state: "in_progress")
purchase.gift_given&.giftee_purchase&.update!(purchase_state: "in_progress")
end
end
charge = ChargeProcessor.get_or_search_charge(purchase)
success_statuses = ChargeProcessor.charge_processor_success_statuses(purchase.charge_processor_id)
if charge && success_statuses.include?(charge.status) && !charge.try(:refunded) && !charge.try(:refunded?) && !charge.try(:disputed)
purchase.flow_of_funds = if purchase.is_part_of_combined_charge?
purchase.build_flow_of_funds_from_combined_charge(charge.flow_of_funds)
else
charge.flow_of_funds
end
purchase.stripe_transaction_id = charge.id unless purchase.stripe_transaction_id.present?
purchase.charge.processor_transaction_id = charge.id if purchase.charge.present? && purchase.charge.processor_transaction_id.blank?
purchase.merchant_account = purchase.send(:prepare_merchant_account, purchase.charge_processor_id) unless purchase.merchant_account.present?
if purchase.balance_transactions.exists?
purchase.mark_successful!
else
Purchase::MarkSuccessfulService.new(purchase).perform
end
true
elsif charge.nil? && purchase.free_purchase?
Purchase::MarkSuccessfulService.new(purchase).perform
true
else
purchase.mark_failed! if mark_as_failed
false
end
end
rescue StandardError => e
Bugsnag.notify(e) { |report| report.add_metadata(:purchase, { id: purchase.id }) }
purchase.mark_failed! if mark_as_failed
false
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/mark_successful_service.rb | app/services/purchase/mark_successful_service.rb | # frozen_string_literal: true
# Transitions the purchase to successful state and marks linked items (subscription, gift, giftee purchase, preorder) as successful too.
class Purchase::MarkSuccessfulService < Purchase::BaseService
def initialize(purchase)
@purchase = purchase
@preorder = purchase.preorder
end
def perform
handle_purchase_success
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/associate_bundle_product_level_gift_service.rb | app/services/purchase/associate_bundle_product_level_gift_service.rb | # frozen_string_literal: true
class Purchase::AssociateBundleProductLevelGiftService
def initialize(bundle_purchase:, bundle_product:)
@bundle_purchase = bundle_purchase
@bundle_product = bundle_product
end
def perform
return unless bundle_product_belongs_to_bundle?
return if bundle_level_gift.blank?
product_level_gift = existing_product_level_gift || Gift.new
product_level_gift.update!(product_level_gift_params)
end
private
def bundle_product_belongs_to_bundle?
@bundle_product.bundle_id == @bundle_purchase.link_id
end
def existing_product_level_gift
query = Gift.none
if gift_sender_bundle_product_purchase.present?
query = query.or(Gift.where(gifter_purchase: gift_sender_bundle_product_purchase))
end
if gift_receiver_bundle_product_purchase.present?
query = query.or(Gift.where(giftee_purchase: gift_receiver_bundle_product_purchase))
end
query.first
end
def product_level_gift_params
bundle_level_gift.attributes
.except("id", "created_at", "updated_at")
.merge(
giftee_purchase: gift_receiver_bundle_product_purchase,
gifter_purchase: gift_sender_bundle_product_purchase,
link_id: @bundle_product.product_id,
)
end
def bundle_level_gift
@bundle_level_gift ||= @bundle_purchase.gift
end
def gift_sender_bundle_purchase
@gift_sender_bundle_purchase ||= bundle_level_gift.gifter_purchase
end
def gift_receiver_bundle_purchase
@gift_receiver_bundle_purchase ||= bundle_level_gift.giftee_purchase
end
def gift_sender_bundle_product_purchase
@gift_sender_bundle_product_purchase ||= gift_sender_bundle_purchase
.product_purchases
.find_by(link_id: @bundle_product.product_id)
end
def gift_receiver_bundle_product_purchase
@gift_receiver_bundle_product_purchase ||= gift_receiver_bundle_purchase
.product_purchases
.find_by(link_id: @bundle_product.product_id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/mark_failed_service.rb | app/services/purchase/mark_failed_service.rb | # frozen_string_literal: true
# Transitions the purchase to corresponding failed state and marks linked items (preorder, gift, giftee purchase) as failed, too.
class Purchase::MarkFailedService < Purchase::BaseService
def initialize(purchase)
@purchase = purchase
@preorder = purchase.preorder
end
def perform
mark_items_failed
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/base_service.rb | app/services/purchase/base_service.rb | # frozen_string_literal: true
class Purchase::BaseService
include AfterCommitEverywhere
attr_accessor :purchase, :preorder
protected
def handle_purchase_success
if purchase.free_purchase? && purchase.is_preorder_authorization?
mark_preorder_authorized
return
end
giftee_purchase = nil
if purchase.is_gift_sender_purchase
giftee_purchase = purchase.gift_given.giftee_purchase
giftee_purchase.mark_gift_receiver_purchase_successful
end
create_subscription(giftee_purchase) if purchase.link.is_recurring_billing || purchase.is_installment_payment
purchase.update_balance_and_mark_successful!
purchase.gift_given.mark_successful! if purchase.is_gift_sender_purchase
purchase.seller.save_gumroad_day_timezone
after_commit do
ActivateIntegrationsWorker.perform_async(purchase.id)
end
end
def create_subscription(giftee_purchase)
return if purchase.subscription.present?
is_gift = purchase.is_gift_sender_purchase
charge_occurrence_count =
if purchase.is_installment_payment
purchase.link.installment_plan.number_of_installments
elsif purchase.link.duration_in_months.present?
purchase.link.duration_in_months / BasePrice::Recurrence.number_of_months_in_recurrence(purchase.price.recurrence)
end
subscription = purchase.link.subscriptions.build(
user: is_gift ? giftee_purchase.purchaser : purchase.purchaser,
credit_card: is_gift ? nil : purchase.credit_card,
is_test_subscription: purchase.is_test_purchase?,
is_installment_plan: purchase.is_installment_payment,
charge_occurrence_count:,
free_trial_ends_at: purchase.is_free_trial_purchase? ? purchase.created_at + purchase.link.free_trial_duration : nil
)
payment_option = PaymentOption.new(
price: purchase.price,
installment_plan: purchase.is_installment_payment ? purchase.link.installment_plan : nil
)
if purchase.is_installment_payment && purchase.link.installment_plan.present?
total_price = purchase.total_price_before_installments
if total_price.present? && total_price > 0
payment_option.build_installment_plan_snapshot(
number_of_installments: purchase.link.installment_plan.number_of_installments,
recurrence: purchase.link.installment_plan.recurrence,
total_price_cents: total_price
)
end
end
subscription.payment_options << payment_option
subscription.save!
subscription.purchases << [purchase, giftee_purchase].compact
end
def handle_purchase_failure
mark_items_failed
end
def mark_items_failed
if purchase.is_preorder_authorization?
mark_preorder_failed
else
purchase.mark_failed
end
if purchase.is_gift_sender_purchase
purchase.gift_given.mark_failed!
purchase.gift_given.giftee_purchase&.mark_gift_receiver_purchase_failed!
end
subscription = purchase.subscription
if subscription&.is_resubscription_pending_confirmation?
subscription.unsubscribe_and_fail!
subscription.update_flag!(:is_resubscription_pending_confirmation, false, true)
elsif purchase.is_upgrade_purchase?
new_original_purchase = subscription.original_purchase
previous_original_purchase = subscription.purchases.is_archived_original_subscription_purchase.last
new_original_purchase.update_flag!(:is_archived_original_subscription_purchase, true, true)
previous_original_purchase.update_flag!(:is_archived_original_subscription_purchase, false, true)
subscription.last_payment_option.update!(price: previous_original_purchase.price) if previous_original_purchase.price.present?
end
end
def mark_preorder_authorized
if purchase.is_test_purchase?
purchase.mark_test_preorder_successful!
preorder.mark_test_authorization_successful!
else
purchase.mark_preorder_authorization_successful!
preorder.mark_authorization_successful!
end
end
def mark_preorder_failed
if purchase.is_test_purchase?
purchase.mark_test_preorder_successful!
preorder&.mark_test_authorization_successful!
else
purchase.mark_preorder_authorization_failed
preorder&.mark_authorization_failed!
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchase/update_bundle_purchase_content_service.rb | app/services/purchase/update_bundle_purchase_content_service.rb | # frozen_string_literal: true
class Purchase::UpdateBundlePurchaseContentService
def initialize(purchase)
@purchase = purchase
end
def perform
existing_product_purchases = @purchase.product_purchases.pluck(:created_at, :link_id)
content_needed_after = existing_product_purchases.map(&:first).max
purchases = @purchase.link
.bundle_products
.alive
.where(updated_at: content_needed_after..)
.where.not(product_id: existing_product_purchases.map(&:second))
.map do |bundle_product|
Purchase::CreateBundleProductPurchaseService.new(@purchase, bundle_product).perform
end
CustomerLowPriorityMailer.bundle_content_updated(@purchase.id).deliver_later if purchases.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/workflow/manage_service.rb | app/services/workflow/manage_service.rb | # frozen_string_literal: true
class Workflow::ManageService
include Rails.application.routes.url_helpers
attr_reader :workflow, :error
def initialize(seller:, params:, product:, workflow:)
@seller = seller
@params = params
@product = product
@workflow = workflow || build_workflow
@error = nil
end
def process
workflow.name = params[:name]
if workflow.new_record? && params[:workflow_type] == Workflow::ABANDONED_CART_TYPE && !seller.eligible_for_abandoned_cart_workflows?
workflow.errors.add(:base, "You must have at least one completed payout to create an abandoned cart workflow")
return [false, workflow.errors.full_messages.first]
end
if workflow.has_never_been_published?
workflow.workflow_type = params[:workflow_type]
workflow.base_variant = params[:workflow_type] == Workflow::VARIANT_TYPE ? BaseVariant.find_by_external_id(params[:variant_external_id]) : nil
workflow.link = product_or_variant_type? ? product : nil
workflow.send_to_past_customers = params[:send_to_past_customers]
workflow.add_and_validate_filters(params, seller)
if workflow.errors.any?
return [false, workflow.errors.full_messages.first]
end
end
begin
ActiveRecord::Base.transaction do
was_just_created = workflow.new_record?
workflow.save!
if workflow.abandoned_cart_type? && (was_just_created || workflow.installments.alive.where(installment_type: Installment::ABANDONED_CART_TYPE).none?)
workflow.installments.alive.find_each(&:mark_deleted!) unless was_just_created
installment = workflow.installments.create!(
name: "You left something in your cart",
message: "<p>When you're ready to buy, <a href=\"#{checkout_index_url(host: DOMAIN)}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">complete checking out</a>.</p><#{Installment::PRODUCT_LIST_PLACEHOLDER_TAG_NAME} />",
installment_type: workflow.workflow_type,
json_data: workflow.json_data,
seller_id: workflow.seller_id,
send_emails: true,
)
installment.create_installment_rule!(time_period: InstallmentRule::HOUR, delayed_delivery_time: InstallmentRule::ABANDONED_CART_DELAYED_DELIVERY_TIME_IN_SECONDS)
end
if !was_just_created && !workflow.abandoned_cart_type?
workflow.installments.alive.where(installment_type: Installment::ABANDONED_CART_TYPE).find_each(&:mark_deleted!)
end
sync_installments! if workflow.has_never_been_published?
unless was_just_created
workflow.publish! if params[:save_action_name] == Workflow::SAVE_AND_PUBLISH_ACTION
workflow.unpublish! if params[:save_action_name] == Workflow::SAVE_AND_UNPUBLISH_ACTION
end
end
rescue ActiveRecord::RecordInvalid => e
@error = e.record.errors.full_messages.first
rescue Installment::InstallmentInvalid => e
workflow.errors.add(:base, e.message)
@error = workflow.errors.full_messages.first
end
[error.nil?, error]
end
private
attr_reader :params, :seller, :product
def sync_installments!
workflow.installments.alive.find_each do |installment|
installment.installment_type = workflow.workflow_type
installment.json_data = workflow.json_data
installment.seller_id = workflow.seller_id
installment.link_id = workflow.link_id
installment.base_variant_id = workflow.base_variant_id
installment.is_for_new_customers_of_workflow = !workflow.send_to_past_customers
installment.save!
end
end
def build_workflow
if product_or_variant_type?
product.workflows.build(seller: product.user)
else
seller.workflows.build
end
end
def product_or_variant_type?
[Workflow::PRODUCT_TYPE, Workflow::VARIANT_TYPE].include?(params[:workflow_type])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/workflow/save_installments_service.rb | app/services/workflow/save_installments_service.rb | # frozen_string_literal: true
class Workflow::SaveInstallmentsService
include InstallmentRuleHelper
attr_reader :errors, :old_and_new_installment_id_mapping
def initialize(seller:, params:, workflow:, preview_email_recipient:)
@seller = seller
@params = params
@workflow = workflow
@preview_email_recipient = preview_email_recipient
@errors = nil
@old_and_new_installment_id_mapping = {}
end
def process
if params[:installments].nil?
workflow.errors.add(:base, "Installments data is required")
@errors = workflow.errors
return [false, errors]
end
if workflow.abandoned_cart_type? && params[:installments].size != 1
workflow.errors.add(:base, "An abandoned cart workflow can only have one email.")
@errors = workflow.errors
return [false, errors]
end
begin
ActiveRecord::Base.transaction do
if @workflow.has_never_been_published?
@workflow.update!(send_to_past_customers: params[:send_to_past_customers])
end
delete_removed_installments
params[:installments].each do |installment_params|
installment = workflow.installments.alive.find_by_external_id(installment_params[:id]) || workflow.installments.build
installment.name = installment_params[:name]
installment.message = installment_params[:message]
if workflow.abandoned_cart_type? && installment.message.exclude?(Installment::PRODUCT_LIST_PLACEHOLDER_TAG_NAME)
installment.message += "<#{Installment::PRODUCT_LIST_PLACEHOLDER_TAG_NAME} />"
end
installment.message = SaveContentUpsellsService.new(seller:, content: installment.message, old_content: installment.message_was).from_html
installment.send_emails = true
inherit_workflow_info(installment)
installment.save!
SaveFilesService.perform(installment, { files: installment_params[:files] || [] }.with_indifferent_access)
save_installment_rule_and_reschedule_installment(installment, installment_params)
installment.send_preview_email(preview_email_recipient) if installment_params[:send_preview_email]
@old_and_new_installment_id_mapping[installment_params[:id]] = installment.external_id
end
workflow.publish! if params[:save_action_name] == Workflow::SAVE_AND_PUBLISH_ACTION
workflow.unpublish! if params[:save_action_name] == Workflow::SAVE_AND_UNPUBLISH_ACTION
end
rescue ActiveRecord::RecordInvalid => e
@errors = e.record.errors
rescue Installment::InstallmentInvalid, Installment::PreviewEmailError => e
workflow.errors.add(:base, e.message)
@errors = workflow.errors
end
[errors.nil?, errors]
end
private
attr_reader :params, :seller, :workflow, :preview_email_recipient
def delete_removed_installments
deleted_external_ids = workflow.installments.alive.map(&:external_id) - params[:installments].pluck(:id)
workflow.installments.by_external_ids(deleted_external_ids).find_each do |installment|
installment.mark_deleted!
installment.installment_rule&.mark_deleted!
end
end
def inherit_workflow_info(installment)
if installment.new_record? || workflow.has_never_been_published?
installment.installment_type = workflow.workflow_type
installment.json_data = workflow.json_data
installment.seller_id = workflow.seller_id
installment.link_id = workflow.link_id
installment.base_variant_id = workflow.base_variant_id
installment.is_for_new_customers_of_workflow = !workflow.send_to_past_customers
end
installment.published_at = workflow.published_at
installment.workflow_installment_published_once_already = workflow.first_published_at.present?
end
def save_installment_rule_and_reschedule_installment(installment, installment_params)
rule = installment.installment_rule || installment.build_installment_rule
rule.time_period = installment_params[:time_period]
new_delayed_delivery_time = convert_to_seconds(installment_params[:time_duration], installment_params[:time_period])
old_delayed_delivery_time = rule.delayed_delivery_time
# only reschedule new jobs if delivery time changes
if old_delayed_delivery_time == new_delayed_delivery_time
rule.save!
return
end
rule.delayed_delivery_time = new_delayed_delivery_time
rule.save!
if installment.published_at.present? && params[:save_action_name] == Workflow::SAVE_ACTION
installment.workflow.schedule_installment(installment, old_delayed_delivery_time:)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/product/mark_compliant_service.rb | app/services/iffy/product/mark_compliant_service.rb | # frozen_string_literal: true
class Iffy::Product::MarkCompliantService
attr_reader :product
def initialize(product_id)
@product = Link.find_by_external_id!(product_id)
end
def perform
product.update!(is_unpublished_by_admin: false)
product.publish!
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/product/ingest_service.rb | app/services/iffy/product/ingest_service.rb | # frozen_string_literal: true
class Iffy::Product::IngestService
include SignedUrlHelper
include Rails.application.routes.url_helpers
URL = Rails.env.production? ? "https://api.iffy.com/api/v1/ingest" : "http://localhost:3000/api/v1/ingest"
def initialize(product)
@product = product
end
def perform
iffy_api_request
end
private
attr_reader :product
PERMITTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
def iffy_api_request
user_data = {
clientId: product.user.external_id,
protected: product.user.vip_creator?
}
user_data[:email] = product.user.email if product.user.email.present?
user_data[:username] = product.user.username if product.user.username.present?
user_data[:stripeAccountId] = product.user.stripe_account&.charge_processor_merchant_id if product.user.stripe_account&.charge_processor_merchant_id.present?
response = HTTParty.post(
URL,
{
body: {
clientId: product.external_id,
clientUrl: product.long_url,
name: product.name,
entity: "Product",
text:,
fileUrls: image_urls,
user: user_data
}.to_json,
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}"
}
}
)
if response.success?
response.parsed_response
else
message = if response.parsed_response.is_a?(Hash)
response.parsed_response.dig("error", "message")
elsif response.parsed_response.is_a?(String)
response.parsed_response
else
response.body
end
error_message = "Iffy error for product ID #{product.id}: #{response.code} - #{message}"
raise error_message
end
end
def text
"Name: #{product.name} Description: #{product.description} " + text_content(rich_contents)
end
def image_urls
cover_image_urls = product.display_asset_previews.joins(file_attachment: :blob)
.where(active_storage_blobs: { content_type: PERMITTED_IMAGE_TYPES })
.map(&:url)
thumbnail_image_urls = product.thumbnail.present? ? [product.thumbnail.url] : []
product_description_image_urls = Nokogiri::HTML(product.link.description).css("img").filter_map { |img| img["src"] }
rich_content_file_image_urls = rich_contents.flat_map do |rich_content|
ProductFile.where(id: rich_content.embedded_product_file_ids_in_order, filegroup: "image").map do
# the only way to generate a permanent Cloudfront signed url is to set a long expiry time
# see https://stackoverflow.com/a/55729193
signed_download_url_for_s3_key_and_filename(_1.s3_key, _1.s3_filename, expires_in: 99.years)
end
end
rich_content_embedded_image_urls = rich_contents.flat_map do |rich_content|
rich_content.description.filter_map do |node|
node.dig("attrs", "src") if node["type"] == "image"
end
end.compact
(cover_image_urls +
thumbnail_image_urls +
product_description_image_urls +
rich_content_file_image_urls +
rich_content_embedded_image_urls
).reject(&:empty?)
end
def text_content(rich_contents)
rich_contents.flat_map do |rich_content|
extract_text(rich_content.description)
end.join(" ")
end
def extract_text(content)
case content
when Array
content.flat_map { |item| extract_text(item) }
when Hash
if content["text"]
Array.wrap(content["text"])
else
content.values.flat_map { |value| extract_text(value) }
end
else
[]
end
end
def rich_contents
product.alive_rich_contents
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/product/flag_service.rb | app/services/iffy/product/flag_service.rb | # frozen_string_literal: true
class Iffy::Product::FlagService
attr_reader :product
def initialize(product_id)
@product = Link.find_by_external_id!(product_id)
end
def perform
product.unpublish!(is_unpublished_by_admin: true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/user/mark_compliant_service.rb | app/services/iffy/user/mark_compliant_service.rb | # frozen_string_literal: true
class Iffy::User::MarkCompliantService
attr_reader :user
def initialize(user_id)
@user = User.find_by_external_id!(user_id)
end
def perform
user.mark_compliant!(author_name: "Iffy")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/user/ban_service.rb | app/services/iffy/user/ban_service.rb | # frozen_string_literal: true
class Iffy::User::BanService
attr_reader :user
def initialize(id)
@user = User.find_by_external_id!(id)
end
def perform
ActiveRecord::Base.transaction do
reason = "Adult (18+) content"
user.update!(tos_violation_reason: reason)
comment_content = "Banned for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} (#{reason})"
user.flag_for_tos_violation!(author_name: "Iffy", content: comment_content, bulk: true) unless user.flagged_for_tos_violation? || user.on_probation? || user.suspended?
user.suspend_for_tos_violation!(author_name: "Iffy", content: comment_content, bulk: true) unless user.suspended?
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/user/suspend_service.rb | app/services/iffy/user/suspend_service.rb | # frozen_string_literal: true
class Iffy::User::SuspendService
attr_reader :user
def initialize(id)
@user = User.find_by_external_id!(id)
end
def perform
return if !user.can_flag_for_tos_violation?
ActiveRecord::Base.transaction do
reason = "Adult (18+) content"
user.update!(tos_violation_reason: reason)
comment_content = "Suspended for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} (#{reason})"
user.flag_for_tos_violation!(author_name: "Iffy", content: comment_content, bulk: true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/profile/ingest_service.rb | app/services/iffy/profile/ingest_service.rb | # frozen_string_literal: true
class Iffy::Profile::IngestService
include Rails.application.routes.url_helpers
URL = Rails.env.production? ? "https://api.iffy.com/api/v1/ingest" : "http://localhost:3000/api/v1/ingest"
TEST_MODE = Rails.env.test?
def initialize(user)
@user = user
end
def perform
return if TEST_MODE
iffy_api_request
end
private
attr_reader :user
def iffy_api_request
user_data = {
clientId: user.external_id,
protected: user.vip_creator?
}
user_data[:email] = user.email if user.email.present?
user_data[:username] = user.username if user.username.present?
user_data[:stripeAccountId] = user.stripe_account&.charge_processor_merchant_id if user.stripe_account&.charge_processor_merchant_id.present?
response = HTTParty.post(
URL,
{
body: {
clientId: user.external_id,
clientUrl: user.profile_url,
name: user.display_name,
entity: "Profile",
text: text,
fileUrls: file_urls,
user: user_data
}.to_json,
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}"
}
}
)
if response.success?
response.parsed_response
else
message = if response.parsed_response.is_a?(Hash)
response.parsed_response.dig("error", "message")
elsif response.parsed_response.is_a?(String)
response.parsed_response
else
response.body
end
error_message = "Iffy error for user ID #{user.id}: #{response.code} - #{message}"
raise error_message
end
end
def text
"#{user.display_name} #{user.bio} #{rich_text_content}"
end
def file_urls
rich_text_sections.flat_map do |section|
section.json_data.dig("text", "content")&.filter_map do |content|
content.dig("attrs", "src") if content["type"] == "image"
end
end.compact.reject(&:empty?)
end
def rich_text_content
rich_text_sections.map do |section|
section.json_data.dig("text", "content")&.filter_map do |content|
if content["type"] == "paragraph" && content["content"]
content["content"].map { |item| item["text"] }.join
end
end
end.flatten.join(" ")
end
def rich_text_sections
@rich_text_sections ||= SellerProfileRichTextSection.where(seller_id: user.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/post/mark_compliant_service.rb | app/services/iffy/post/mark_compliant_service.rb | # frozen_string_literal: true
class Iffy::Post::MarkCompliantService
attr_reader :post
def initialize(post_id)
@post = Installment.find_by_external_id!(post_id)
end
def perform
return unless !post.published? && post.is_unpublished_by_admin?
post.is_unpublished_by_admin = false
post.publish!
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/post/ingest_service.rb | app/services/iffy/post/ingest_service.rb | # frozen_string_literal: true
class Iffy::Post::IngestService
URL = Rails.env.production? ? "https://api.iffy.com/api/v1/ingest" : "http://localhost:3000/api/v1/ingest"
def initialize(installment)
@installment = installment
end
def perform
iffy_api_request
end
private
attr_reader :installment
PERMITTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
def iffy_api_request
user_data = {
clientId: installment.user.external_id,
protected: installment.user.vip_creator?
}
user_data[:email] = installment.user.email if installment.user.email.present?
user_data[:username] = installment.user.username if installment.user.username.present?
user_data[:stripeAccountId] = installment.user.stripe_account&.charge_processor_merchant_id if installment.user.stripe_account&.charge_processor_merchant_id.present?
response = HTTParty.post(
URL,
{
body: {
clientId: installment.external_id,
clientUrl: installment.full_url,
name: installment.name,
entity: "Post",
text: text,
fileUrls: file_urls,
user: user_data
}.to_json,
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}"
}
}
)
if response.success?
response.parsed_response
else
message = if response.parsed_response.is_a?(Hash)
response.parsed_response.dig("error", "message")
elsif response.parsed_response.is_a?(String)
response.parsed_response
else
response.body
end
error_message = "Iffy error for installment ID #{installment.id}: #{response.code} - #{message}"
raise error_message
end
end
def text
"Name: #{installment.name} Message: #{extract_text_from_message}"
end
def extract_text_from_message
Nokogiri::HTML(installment.message).text
end
def file_urls
doc = Nokogiri::HTML(installment.message)
doc.css("img").map { |img| img["src"] }.reject(&:empty?)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/iffy/post/flag_service.rb | app/services/iffy/post/flag_service.rb | # frozen_string_literal: true
class Iffy::Post::FlagService
attr_reader :post
def initialize(post_id)
@post = Installment.find_by_external_id!(post_id)
end
def perform
post.unpublish!(is_unpublished_by_admin: true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/auth_presenter.rb | app/presenters/auth_presenter.rb | # frozen_string_literal: true
class AuthPresenter
attr_reader :params, :application
def initialize(params:, application:)
@params = params
@application = application
end
def login_props
{
email: params[:email] || retrieve_team_invitation_email(params[:next]),
application_name: application&.name,
recaptcha_site_key: GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY"),
}
end
def signup_props
referrer = User.find_by_username(params[:referrer]) if params[:referrer].present?
number_of_creators, total_made = $redis.mget(RedisKey.number_of_creators, RedisKey.total_made)
login_props.merge(
recaptcha_site_key: GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY"),
referrer: referrer ? {
id: referrer.external_id,
name: referrer.name_or_username,
} : nil,
stats: {
number_of_creators: number_of_creators.to_i,
total_made: total_made.to_i,
},
)
end
private
def retrieve_team_invitation_email(next_path)
# Do not prefill email unless it matches the team invitation accept path
return unless next_path&.start_with?("/settings/team/invitations")
Rack::Utils.parse_nested_query(URI.parse(next_path.to_s).query).dig("email")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/communities_presenter.rb | app/presenters/communities_presenter.rb | # frozen_string_literal: true
class CommunitiesPresenter
def initialize(current_user:)
@current_user = current_user
end
def props
communities = Community.where(id: current_user.accessible_communities_ids).includes(:resource, :seller)
community_ids = communities.map(&:id)
notification_settings = current_user.community_notification_settings
.where(seller_id: communities.map(&:seller_id).uniq)
.index_by(&:seller_id)
last_read_message_timestamps = LastReadCommunityChatMessage.includes(:community_chat_message)
.where(user_id: current_user.id, community_id: community_ids)
.order(created_at: :desc)
.to_h { [_1.community_id, _1.community_chat_message.created_at] }
unread_counts = {}
if community_ids.any?
values_rows = community_ids.map do |community_id|
last_read_message_created_at = last_read_message_timestamps[community_id]
last_read_message_created_at = "\'#{last_read_message_created_at&.iso8601(6) || Date.new(1970, 1, 1)}\'"
"ROW(#{community_id}, #{last_read_message_created_at})"
end.join(", ")
join_clause = "JOIN (VALUES #{values_rows}) AS t1(community_id, last_read_community_chat_message_created_at) ON community_chat_messages.community_id = t1.community_id"
unread_counts = CommunityChatMessage.alive
.select("community_chat_messages.community_id, COUNT(*) as unread_count")
.joins(join_clause)
.where("community_chat_messages.created_at > t1.last_read_community_chat_message_created_at")
.group(:community_id)
.to_a
.each_with_object({}) do |message, hash|
hash[message.community_id] = message.unread_count
end
end
communities_props = communities.map do |community|
CommunityPresenter.new(
community:,
current_user:,
extras: {
unread_count: unread_counts[community.id] || 0,
last_read_community_chat_message_created_at: last_read_message_timestamps[community.id]&.iso8601,
}
).props
end
seller_id_to_external_id_map = User.where(id: notification_settings.keys).each_with_object({}) do |user, hash|
hash[user.id] = user.external_id
end
{
has_products: current_user.products.visible_and_not_archived.exists?,
communities: communities_props,
notification_settings: notification_settings.each_with_object({}) do |(seller_id, settings), hash|
seller_external_id = seller_id_to_external_id_map[seller_id]
next if seller_external_id.blank?
hash[seller_external_id] = CommunityNotificationSettingPresenter.new(settings: settings.presence || CommunityNotificationSetting.new).props
end,
}
end
private
attr_reader :current_user
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/workflow_presenter.rb | app/presenters/workflow_presenter.rb | # frozen_string_literal: true
class WorkflowPresenter
include Rails.application.routes.url_helpers
include ApplicationHelper
attr_reader :seller, :workflow
def initialize(seller:, workflow: nil)
@seller = seller
@workflow = workflow
end
def new_page_react_props
{ context: workflow_form_context_props }
end
def edit_page_react_props
{ workflow: workflow_props, context: workflow_form_context_props }
end
def workflow_props
recipient_name = "All sales"
if workflow.product_type?
recipient_name = workflow.link.name
elsif workflow.variant_type?
recipient_name = "#{workflow.link.name} - #{workflow.base_variant.name}"
elsif workflow.follower_type?
recipient_name = "Followers only"
elsif workflow.audience_type?
recipient_name = "Everyone"
elsif workflow.affiliate_type?
recipient_name = "Affiliates only"
end
props = {
name: workflow.name,
external_id: workflow.external_id,
workflow_type: workflow.workflow_type,
workflow_trigger: workflow.workflow_trigger,
recipient_name:,
published: workflow.published_at.present?,
first_published_at: workflow.first_published_at,
send_to_past_customers: workflow.send_to_past_customers,
}
props[:installments] = workflow.installments.alive.joins(:installment_rule).order("delayed_delivery_time ASC").map { InstallmentPresenter.new(seller:, installment: _1).props }
props.merge!(workflow.json_filters)
if workflow.product_type? || workflow.variant_type?
props[:unique_permalink] = workflow.link.unique_permalink
props[:variant_external_id] = workflow.base_variant.external_id if workflow.variant_type?
end
if workflow.abandoned_cart_type?
props[:abandoned_cart_products] = workflow.abandoned_cart_products
props[:seller_has_products] = seller.links.visible_and_not_archived.exists?
end
props
end
def workflow_form_context_props
user_presenter = UserPresenter.new(user: seller)
{
products_and_variant_options: user_presenter.products_for_filter_box.flat_map do |product|
[{
id: product.unique_permalink,
label: product.name,
product_permalink: product.unique_permalink,
archived: product.archived?,
type: "product",
}].concat(
(product.is_physical? ? product.skus_alive_not_default : product.alive_variants).map do
{
id: _1.external_id,
label: "#{product.name} — #{_1.name}",
product_permalink: product.unique_permalink,
archived: product.archived?,
type: "variant"
}
end
)
end,
affiliate_product_options: user_presenter.affiliate_products_for_filter_box.map do |product|
{ id: product.unique_permalink, label: product.name, product_permalink: product.unique_permalink, archived: product.archived?, type: "product" }
end,
timezone: ActiveSupport::TimeZone[user_presenter.user.timezone].now.strftime("%Z"),
currency_symbol: user_presenter.user.currency_symbol,
countries: [Compliance::Countries::USA.common_name] + Compliance::Countries.for_select.flat_map { |_, name| Compliance::Countries::USA.common_name === name ? [] : name },
aws_access_key_id: AWS_ACCESS_KEY,
s3_url: s3_bucket_url,
user_id: user_presenter.user.external_id,
gumroad_address: GumroadAddress.full,
eligible_for_abandoned_cart_workflows: user_presenter.user.eligible_for_abandoned_cart_workflows?,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/cart_presenter.rb | app/presenters/cart_presenter.rb | # frozen_string_literal: true
class CartPresenter
attr_reader :logged_in_user, :ip, :cart
def initialize(logged_in_user:, ip:, browser_guid:)
@logged_in_user = logged_in_user
@ip = ip
@cart = Cart.fetch_by(user: logged_in_user, browser_guid:)
end
def cart_props
return if cart.nil?
cart_products = cart.cart_products.alive.order(created_at: :desc)
{
email: cart.email.presence,
returnUrl: cart.return_url.presence || "",
rejectPppDiscount: cart.reject_ppp_discount,
discountCodes: cart.discount_codes.map do |discount_code|
products = cart_products.each_with_object({}) { |cart_product, hash| hash[cart_product.product.unique_permalink] = { permalink: cart_product.product.unique_permalink, quantity: cart_product.quantity } }
result = OfferCodeDiscountComputingService.new(discount_code["code"], products).process
{
code: discount_code["code"],
fromUrl: discount_code["fromUrl"],
products: result[:error_code].present? ? [] : result[:products_data].transform_values { _1[:discount] },
}
end,
items: cart_products.map do |cart_product|
value = {
**checkout_product(cart_product),
url_parameters: cart_product.url_parameters,
referrer: cart_product.referrer,
}
accepted_offer = cart_product.accepted_offer
if cart_product.accepted_offer.present? && cart_product.accepted_offer_details.present?
value[:accepted_offer] = {
id: accepted_offer.external_id,
**cart_product.accepted_offer_details.symbolize_keys,
}
value[:accepted_offer][:discount] = accepted_offer.offer_code.discount if accepted_offer.offer_code.present?
end
value
end
}
end
private
def checkout_product(cart_product)
params = {
recommended_by: cart_product.recommended_by,
affiliate_id: cart_product.affiliate&.external_id_numeric&.to_s,
recommender_model_name: cart_product.recommender_model_name,
}
cart_item = cart_product.product.cart_item(
price: cart_product.price,
option: cart_product.option&.external_id,
rent: cart_product.rent,
recurrence: cart_product.recurrence,
quantity: cart_product.quantity,
call_start_time: cart_product.call_start_time,
pay_in_installments: cart_product.pay_in_installments,
)
CheckoutPresenter.new(logged_in_user:, ip:).checkout_product(cart_product.product, cart_item, params)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/customer_presenter.rb | app/presenters/customer_presenter.rb | # frozen_string_literal: true
class CustomerPresenter
attr_reader :purchase
def initialize(purchase:)
@purchase = purchase
end
def missed_posts
posts = Installment.missed_for_purchase(purchase).order(published_at: :desc)
posts.map do |post|
{
id: post.external_id,
name: post.name,
url: post.full_url,
published_at: post.published_at,
}
end
end
def customer(pundit_user:)
offer_code = purchase.original_offer_code
variant = purchase.variant_attributes.first
review = purchase.original_product_review
product = purchase.link
call = purchase.call
commission = purchase.commission
utm_link = purchase.utm_link
{
id: purchase.external_id,
email: purchase.email,
giftee_email: purchase.giftee_email,
name: purchase.full_name || "",
physical: purchase.sku.present? ?
{
sku: purchase.sku.custom_name_or_external_id,
order_number: purchase.external_id_numeric.to_s,
} : nil,
shipping: purchase.link.require_shipping? ?
{
address: purchase.shipping_information,
price: purchase.formatted_shipping_amount,
tracking: purchase.shipment.present? ?
{
shipped: purchase.shipment.shipped?,
url: purchase.shipment.tracking_url,
} : { shipped: false },
} : nil,
is_bundle_purchase: purchase.is_bundle_purchase,
is_existing_user: purchase.purchaser.present?,
can_contact: purchase.can_contact?,
product: {
name: product.name,
permalink: product.unique_permalink,
native_type: product.native_type,
},
created_at: purchase.created_at.iso8601,
price:
{
cents: purchase.subscription&.current_subscription_price_cents || purchase.displayed_price_cents,
cents_before_offer_code: purchase.displayed_price_cents_before_offer_code(include_deleted: true) || purchase.displayed_price_cents,
cents_refundable: purchase.amount_refundable_cents_in_currency,
currency_type: purchase.displayed_price_currency_type.to_s,
recurrence: (purchase.subscription || purchase.price)&.recurrence,
tip_cents: purchase.tip&.value_cents,
},
quantity: purchase.quantity,
discount: offer_code.present? ?
offer_code.is_cents? ?
{ type: "fixed", cents: offer_code.amount_cents, code: offer_code.code } :
{ type: "percent", percents: offer_code.amount_percentage, code: offer_code.code }
: nil,
upsell: purchase.upsell_purchase&.upsell&.name,
subscription: purchase.subscription.present? ?
{
id: purchase.subscription.external_id,
status: purchase.subscription.status,
is_installment_plan: purchase.subscription.is_installment_plan,
remaining_charges: purchase.subscription.has_fixed_length? ? purchase.subscription.remaining_charges_count : nil,
} : nil,
is_multiseat_license: purchase.is_multiseat_license,
referrer: purchase.display_referrer,
is_additional_contribution: purchase.is_additional_contribution,
ppp: purchase.ppp_info,
is_preorder: purchase.preorder.present? && purchase.is_preorder_authorization,
affiliate: purchase.affiliate.present? ?
{
email: purchase.affiliate.affiliate_user.form_email,
amount: Money.new(purchase.affiliate_credit_cents).format(no_cents_if_whole: true, symbol: true),
type: purchase.affiliate.type,
} : nil,
license: purchase.linked_license.present? ?
{
id: purchase.linked_license.external_id,
key: purchase.linked_license.serial,
enabled: !purchase.linked_license.disabled?,
} : nil,
review: review.present? ?
{
rating: review.rating,
message: review.message.presence,
response: review.response ? {
message: review.response.message,
} : nil,
videos: review_videos_props(alive_videos: review.alive_videos, pundit_user:),
} : nil,
call: call.present? ?
{
id: call.external_id,
call_url: call.call_url,
start_time: call.start_time.iso8601,
end_time: call.end_time.iso8601,
} : nil,
commission: commission.present? ? {
id: commission.external_id,
files: commission.files.map { file_details(_1) },
status: commission.status,
} : nil,
custom_fields: purchase.purchase_custom_fields.map do |field|
if field[:type] == CustomField::TYPE_FILE
{ attribute: field.name, type: "file", files: field.files.map { file_details(_1) } }
else
{ attribute: field.name, type: "text", value: field.value.to_s }
end
end,
transaction_url_for_seller: purchase.transaction_url_for_seller,
is_access_revoked: purchase.is_access_revoked? ?
(Pundit.policy!(pundit_user, [:audience, purchase]).undo_revoke_access? || nil) :
(Pundit.policy!(pundit_user, [:audience, purchase]).revoke_access? ? false : nil),
paypal_refund_expired: purchase.paypal_refund_expired?,
refunded: purchase.stripe_refunded?,
partially_refunded: purchase.stripe_partially_refunded?,
chargedback: purchase.chargedback? && !purchase.chargeback_reversed?,
has_options: variant.present? || purchase.link.alive_variants.any?,
option: variant.present? ?
(variant.is_a?(Sku) ? variant.to_option_for_product : variant.to_option) :
nil,
utm_link: utm_link.present? ? {
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,
} : nil,
download_count: download_count
}
end
def download_count
return nil if purchase.is_bundle_purchase?
product = purchase.link
return nil if product.native_type == Link::NATIVE_TYPE_COFFEE
purchase.url_redirect&.uses || 0
end
def charge
{
id: purchase.external_id,
created_at: purchase.created_at.iso8601,
partially_refunded: purchase.stripe_partially_refunded?,
refunded: purchase.stripe_refunded?,
amount_refundable: purchase.amount_refundable_cents_in_currency,
currency_type: purchase.link.price_currency_type,
transaction_url_for_seller: purchase.transaction_url_for_seller,
is_upgrade_purchase: purchase.is_upgrade_purchase?,
chargedback: purchase.chargedback? && !purchase.chargeback_reversed?,
paypal_refund_expired: purchase.paypal_refund_expired?,
}
end
private
def file_details(file)
{
id: file.signed_id,
name: File.basename(file.filename.to_s, ".*"),
size: file.byte_size,
extension: File.extname(file.filename.to_s).delete(".").upcase,
key: file.key
}
end
def review_videos_props(alive_videos:, pundit_user:)
# alive_videos of different states are pre-loaded together to simplify
# the query, and there is guaranteed to be at-most one pending and
# at-most one approved video.
pending = alive_videos.find(&:pending_review?)
approved = alive_videos.find(&:approved?)
[pending, approved]
.compact
.map { |video| ProductReviewVideoPresenter.new(video).props(pundit_user:) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/collab_products_page_presenter.rb | app/presenters/collab_products_page_presenter.rb | # frozen_string_literal: true
class CollabProductsPagePresenter
include ProductsHelper
include Rails.application.routes.url_helpers
PER_PAGE = 50
def initialize(pundit_user:, page: 1, sort_params: {}, query: nil)
@pundit_user = pundit_user
@page = page
@sort_params = sort_params
@query = query
end
def initial_page_props
build_stats
{
stats: {
total_revenue:,
total_customers:,
total_members:,
total_collaborations:,
},
archived_tab_visible: seller.archived_products_count > 0,
**products_table_props,
**memberships_table_props,
collaborators_disabled_reason: seller.has_brazilian_stripe_connect_account? ? "Collaborators with Brazilian Stripe accounts are not supported." : nil,
}
end
def products_table_props
products_pagination, products = paginated_collabs(for_memberships: false)
{
products: products_data(products),
products_pagination:,
}
end
def memberships_table_props
memberships_pagination, memberships = paginated_collabs(for_memberships: true)
{
memberships: memberships_data(memberships),
memberships_pagination:,
}
end
private
attr_reader :pundit_user, :page, :sort_params, :query, :total_revenue, :total_customers, :total_members, :total_collaborations
def seller
pundit_user.seller
end
def fetch_collabs(only: nil)
collabs = Link.collabs_as_seller_or_collaborator(seller)
if only == "memberships"
collabs = collabs.membership
elsif only == "products"
collabs = collabs.non_membership
end
collabs = collabs.where("links.name like ?", "%#{query}%") if query.present?
collabs
end
def paginated_collabs(for_memberships:)
sort_and_paginate_products(**sort_params.to_h.symbolize_keys, page:, collection: fetch_collabs(only: for_memberships ? "memberships" : "products"), per_page: PER_PAGE, user_id: seller.id)
end
def build_stats
@total_revenue = 0
@total_customers = 0
@total_members = 0
@total_collaborations = 0
collabs = fetch_collabs
collabs.each do |product|
@total_collaborations += 1 unless product.deleted? || product.archived?
@total_revenue += product.total_usd_cents_earned_by_user(seller)
if product.is_recurring_billing?
@total_members += product.active_customers_count
else
@total_customers += product.active_customers_count
end
end
end
def memberships_data(memberships)
Product::Caching.dashboard_collection_data(memberships, cache: true) do |membership|
product_base_data(membership)
end
end
def products_data(products)
Product::Caching.dashboard_collection_data(products, cache: true) do |product|
product_base_data(product)
end
end
def product_base_data(product)
{
"id" => product.id,
"edit_url" => edit_link_path(product),
"name" => product.name,
"permalink" => product.unique_permalink,
"price_formatted" => product.price_formatted_including_rental_verbose,
"revenue" => product.total_usd_cents_earned_by_user(seller),
"thumbnail" => product.thumbnail&.alive&.as_json,
"display_price_cents" => product.display_price_cents,
"url" => product.long_url,
"url_without_protocol" => product.long_url(include_protocol: false),
"has_duration" => product.duration_in_months.present?,
"cut" => product.percentage_revenue_cut_for_user(seller),
"can_edit" => Pundit.policy!(pundit_user, product).edit?,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/checkout_presenter.rb | app/presenters/checkout_presenter.rb | # frozen_string_literal: true
class CheckoutPresenter
include Rails.application.routes.url_helpers
include ActionView::Helpers::SanitizeHelper
include CardParamsHelper
include ProductsHelper
include CurrencyHelper
include PreorderHelper
include CardParamsHelper
attr_reader :logged_in_user, :ip
def initialize(logged_in_user:, ip:)
@logged_in_user = logged_in_user
@ip = ip
end
def checkout_props(params:, browser_guid:)
geo = GeoIp.lookup(@ip)
detected_country = geo.try(:country_name)
country = logged_in_user&.country || detected_country
detected_state = geo.try(:region_name) if [Compliance::Countries::USA, Compliance::Countries::CAN].any? { |country| country.common_name == detected_country }
credit_card = logged_in_user&.credit_card
user = params[:username] && User.find_by_username(params[:username])
{
**checkout_common,
country: Compliance::Countries.find_by_name(country)&.alpha2,
state: logged_in_user&.state || detected_state,
address: logged_in_user ? {
street: logged_in_user.street_address,
zip: logged_in_user.zip_code,
city: logged_in_user.city,
} : nil,
saved_credit_card: CheckoutPresenter.saved_card(credit_card),
gift: nil,
clear_cart: false,
**add_single_product_props(params:, user:),
**checkout_wishlist_props(params:),
**checkout_wishlist_gift_props(params:),
cart: CartPresenter.new(logged_in_user:, ip:, browser_guid:).cart_props,
max_allowed_cart_products: Cart::MAX_ALLOWED_CART_PRODUCTS,
tip_options: TipOptionsService.get_tip_options,
default_tip_option: TipOptionsService.get_default_tip_option,
}
end
def checkout_product(product, cart_item, params, include_cross_sells: true)
return unless product.present?
upsell_variants = product.available_upsell_variants.alive.includes(:selected_variant, :offered_variant)
bundle_products = product.bundle_products.in_order.includes(:product, :variant).alive.load
accepted_offer = params[:accepted_offer_id] ? Upsell.available_to_customers.where(product:).find_by_external_id(params[:accepted_offer_id]) : nil
option_id = accepted_offer&.variant&.external_id || cart_item[:option]&.fetch(:id)
value = {
product: {
**product_common(product, recommended_by: params[:recommended_by]),
id: product.external_id,
duration_in_months: product.duration_in_months,
url: product.long_url,
thumbnail_url: product.thumbnail&.alive&.url,
native_type: product.native_type,
is_preorder: product.is_in_preorder_state,
is_multiseat_license: product.is_multiseat_license?,
is_quantity_enabled: product.quantity_enabled,
quantity_remaining: product.remaining_for_sale_count,
free_trial: product.free_trial_enabled ? {
duration: {
unit: product.free_trial_duration_unit,
amount: product.free_trial_duration_amount
}
} : nil,
cross_sells: [],
has_offer_codes: product.has_offer_codes?,
has_tipping_enabled: product.user.tipping_enabled && !product.is_tiered_membership && !product.is_recurring_billing?,
require_shipping: product.require_shipping? || bundle_products.any? { _1.product.require_shipping? },
analytics: product.analytics_data,
rental: product.rental,
recurrences: product.recurrences,
can_gift: product.can_gift?,
options: product.options.map do |option|
upsell_variant = upsell_variants.find { |upsell_variant| upsell_variant.selected_variant.external_id == option[:id] }
option.merge(
{
upsell_offered_variant_id: upsell_variant.present? &&
(
product.upsell.seller == logged_in_user ||
purchases.none? { |purchase| purchase[:product] == product && purchase[:variant] == upsell_variant.offered_variant }
) &&
upsell_variant.offered_variant.available? ?
upsell_variant.offered_variant.external_id :
nil
}
)
end,
ppp_details: product.ppp_details(@ip),
upsell: product.available_upsell.present? ? {
id: product.available_upsell.external_id,
text: product.available_upsell.text,
description: Rinku.auto_link(sanitize(product.available_upsell.description), :all, 'target="_blank" rel="noopener"'),
} : nil,
archived: product.archived?,
bundle_products: bundle_products.map do |bundle_product|
{
product_id: bundle_product.product.external_id,
name: bundle_product.product.name,
native_type: bundle_product.product.native_type,
thumbnail_url: bundle_product.product.thumbnail_alive&.url,
quantity: bundle_product.quantity,
variant: bundle_product.variant.present? ? { id: bundle_product.variant.external_id, name: bundle_product.variant.name } : nil,
custom_fields: bundle_product.product.custom_field_descriptors,
}
end,
},
price: cart_item[:price],
option_id:,
rent: cart_item[:rental],
recurrence: cart_item[:recurrence],
quantity: cart_item[:quantity],
call_start_time: cart_item[:call_start_time],
pay_in_installments: cart_item[:pay_in_installments],
affiliate_id: params[:affiliate_id],
recommended_by: params[:recommended_by],
recommender_model_name: params[:recommender_model_name],
accepted_offer: accepted_offer ? { id: accepted_offer.external_id, variant_id: accepted_offer&.variant&.external_id, discount: accepted_offer.offer_code&.discount } : nil,
}
if include_cross_sells
value[:product][:cross_sells] = product.available_cross_sells.filter_map do |cross_sell|
next unless cross_sell.product.alive? &&
(cross_sell.product.remaining_for_sale_count.nil? || cross_sell.product.remaining_for_sale_count > 0) &&
(cross_sell.variant.blank? || cross_sell.variant.available?) &&
(
cross_sell.seller == logged_in_user ||
purchases.none? { |purchase| purchase[:product] == cross_sell.product && purchase[:variant] == cross_sell.variant }
)
offered_product = cross_sell.product
offered_product_cart_item = offered_product.cart_item(
{
option: cross_sell.variant&.external_id,
recurrence: offered_product.default_price_recurrence&.recurrence
}
)
{
id: cross_sell.external_id,
replace_selected_products: cross_sell.replace_selected_products,
text: cross_sell.text,
description: Rinku.auto_link(sanitize(cross_sell.description), :all, 'target="_blank" rel="noopener"'),
offered_product: checkout_product(offered_product, offered_product_cart_item, {}, include_cross_sells: false),
discount: cross_sell.offer_code&.discount,
ratings: offered_product.display_product_reviews? ? {
count: offered_product.reviews_count,
average: offered_product.average_rating,
} : nil,
}
end
end
value
end
def subscription_manager_props(subscription:)
return nil unless subscription.present? && subscription.original_purchase.present?
product = subscription.link
tier_attrs = {
recurrence: subscription.recurrence,
variants: subscription.original_purchase.tiers,
price_cents: subscription.current_plan_displayed_price_cents / subscription.original_purchase.quantity,
}
options = (variant_category = product.variant_categories_alive.first) ? variant_category.variants.in_order.alive.map do
|variant| subscription.alive? && !subscription.overdue_for_charge? && product.recurrence_price_enabled?(subscription.recurrence) ? variant.to_option : variant.to_option(subscription_attrs: tier_attrs)
end : []
tier = subscription.original_purchase.variant_attributes.first
if tier.present? && !options.any? { |option| option[:id] == tier.external_id }
options << tier.to_option(subscription_attrs: tier_attrs)
end
offer_code = subscription.discount_applies_to_next_charge? ? subscription.original_offer_code : nil
prices = product.prices.alive.is_buy.to_a
if !prices.any? { |price| price.recurrence == subscription.recurrence }
prices << product.prices.is_buy.where(recurrence: subscription.recurrence).order(deleted_at: :desc).take
end
{
**checkout_common,
product: {
**product_common(product, recommended_by: nil),
native_type: product.native_type,
require_shipping: product.require_shipping?,
recurrences: subscription.is_installment_plan ? [] : prices
.sort_by { |price| BasePrice::Recurrence.number_of_months_in_recurrence(price.recurrence) }
.map { |price| { id: price.external_id, recurrence: price.recurrence, price_cents: price.price_cents } },
options:,
},
contact_info: {
email: subscription.email,
full_name: subscription.original_purchase.full_name || "",
street: subscription.original_purchase.street_address || "",
city: subscription.original_purchase.city || "",
state: subscription.original_purchase.state || "",
zip: subscription.original_purchase.zip_code || "",
country: Compliance::Countries.find_by_name(subscription.original_purchase.country || subscription.original_purchase.ip_country)&.alpha2 || "",
},
used_card: CheckoutPresenter.saved_card(subscription.credit_card_to_charge),
subscription: {
id: subscription.external_id,
option_id: (subscription.original_purchase.variant_attributes[0] || product.default_tier)&.external_id,
recurrence: subscription.recurrence,
price: subscription.current_subscription_price_cents,
prorated_discount_price_cents: subscription.prorated_discount_price_cents,
quantity: subscription.original_purchase.quantity,
alive: subscription.alive?(include_pending_cancellation: false),
pending_cancellation: subscription.pending_cancellation?,
discount: offer_code&.discount,
end_time_of_subscription: subscription.end_time_of_subscription.iso8601,
successful_purchases_count: subscription.purchases.successful.count,
is_in_free_trial: subscription.in_free_trial?,
is_test: subscription.is_test_subscription,
is_overdue_for_charge: subscription.overdue_for_charge?,
is_gift: subscription.gift?,
is_installment_plan: subscription.is_installment_plan,
}
}
end
def self.saved_card(card)
card.present? && card.card_type != "paypal" ? { type: card.card_type, number: card.visual, expiration_date: card.expiry_visual, requires_mandate: card.requires_mandate? } : nil
end
private
def add_single_product_props(params:, user:)
product = params[:product] && (user ? Link.fetch_leniently(params[:product], user:) : Link.find_by_unique_permalink(params[:product]))
cart_item = product.cart_item(params) if product
{
add_products: [checkout_product(product, cart_item, params)].compact
}
end
def checkout_wishlist_props(params:)
return {} if params[:wishlist].blank?
wishlist = Wishlist.alive.includes(wishlist_products: [:product, :variant]).find_by_external_id(params[:wishlist])
return {} if wishlist.blank?
{
add_products: wishlist.alive_wishlist_products.available_to_buy.map do |wishlist_product|
checkout_wishlist_product(wishlist_product, params.reverse_merge(affiliate_id: wishlist_product.wishlist.user.global_affiliate.external_id_numeric.to_s))
end
}
end
def checkout_wishlist_gift_props(params:)
return {} if params[:gift_wishlist_product].blank?
wishlist_product = WishlistProduct.alive.find_by_external_id(params[:gift_wishlist_product])
return {} if wishlist_product.blank? || wishlist_product.wishlist.user == logged_in_user
{
clear_cart: true,
add_products: [checkout_wishlist_product(wishlist_product, params)],
gift: { type: "anonymous", id: wishlist_product.wishlist.user.external_id, name: wishlist_product.wishlist.user.name_or_username, note: "" }
}
end
def checkout_wishlist_product(wishlist_product, params)
cart_item = wishlist_product.product.cart_item(
option: wishlist_product.variant&.external_id,
rent: wishlist_product.rent,
recurrence: wishlist_product.recurrence,
quantity: wishlist_product.quantity,
)
checkout_product(
wishlist_product.product,
cart_item,
params.reverse_merge(recommended_by: RecommendationType::WISHLIST_RECOMMENDATION),
)
end
def checkout_common
{
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),
recaptcha_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"),
paypal_client_id: PAYPAL_PARTNER_CLIENT_ID,
}
end
def product_common(product, recommended_by:)
{
permalink: product.unique_permalink,
name: product.name,
creator: product.user.username ? {
name: product.user.name || product.user.username,
profile_url: product.user.profile_url(recommended_by:),
avatar_url: product.user.avatar_url,
id: product.user.external_id,
} : nil,
currency_code: product.price_currency_type.downcase,
price_cents: product.price_cents,
supports_paypal: supports_paypal(product),
custom_fields: product.custom_field_descriptors,
exchange_rate: get_rate(product.price_currency_type).to_f / (is_currency_type_single_unit?(product.price_currency_type) ? 100 : 1),
is_tiered_membership: product.is_tiered_membership,
is_legacy_subscription: product.is_legacy_subscription?,
pwyw: product.customizable_price ? { suggested_price_cents: product.suggested_price_cents } : nil,
installment_plan: product.installment_plan ? {
number_of_installments: product.installment_plan.number_of_installments,
recurrence: product.installment_plan.recurrence,
} : nil,
is_multiseat_license: product.is_tiered_membership && product.is_multiseat_license,
shippable_country_codes: product.is_physical ? product.shipping_destinations.alive.flat_map { |shipping_destination| shipping_destination.country_or_countries.keys } : [],
}
end
def supports_paypal(product)
return if Feature.active?(:disable_paypal_sales)
return if Feature.active?(:disable_nsfw_paypal_connect_sales) && product.rated_as_adult?
if Feature.active?(:disable_paypal_connect_sales)
return if product.is_recurring_billing? || !product.user.pay_with_paypal_enabled?
"braintree"
elsif product.user.native_paypal_payment_enabled?
"native"
elsif product.user.pay_with_paypal_enabled?
"braintree"
end
end
def purchases
@_purchases ||= logged_in_user&.purchases&.map { |purchase| { product: purchase.link, variant: purchase.variant_attributes.first } } || []
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/product_review_presenter.rb | app/presenters/product_review_presenter.rb | # frozen_string_literal: true
class ProductReviewPresenter
include ActionView::Helpers::DateHelper
attr_reader :product_review
def initialize(product_review)
@product_review = product_review
end
def product_review_props
purchase = product_review.purchase
purchaser = purchase.purchaser
{
id: product_review.external_id,
rating: product_review.rating,
message: product_review.message,
rater: purchaser.present? ?
{
avatar_url: purchaser.avatar_url,
name: purchaser.name.presence || purchase.full_name.presence || "Anonymous",
} :
{
avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"),
name: purchase.full_name.presence || "Anonymous",
},
purchase_id: purchase.external_id,
is_new: product_review.created_at > 1.month.ago,
response: product_review.response.present? ?
{
message: product_review.response.message,
} :
nil,
video: video_props(product_review.approved_video),
}
end
def review_form_props
{
rating: product_review.rating,
message: product_review.message,
video: video_props(product_review.editable_video),
}
end
private
def video_props(video)
return nil unless video.present?
{
id: video.external_id,
thumbnail_url: video.video_file.thumbnail_url,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/paginated_product_posts_presenter.rb | app/presenters/paginated_product_posts_presenter.rb | # frozen_string_literal: true
class PaginatedProductPostsPresenter
include Pagy::Backend
PER_PAGE = 10
private_constant :PER_PAGE
def initialize(product:, variant_external_id:, options: {})
@product = product
@variant_external_id = variant_external_id
@options = options
@page = [options[:page].to_i, 1].max
end
def index_props
posts = Installment.receivable_by_customers_of_product(product:, variant_external_id:)
pagination, paginated_posts = pagy_array(posts, limit: PER_PAGE, page:)
{
total: pagination.count,
next_page: pagination.next,
posts: paginated_posts.map do |post|
date = if post.workflow_id.present? && post.installment_rule.present?
{ type: "workflow_email_rule", time_duration: post.installment_rule.displayable_time_duration, time_period: post.installment_rule.time_period }
else
{ type: "date", value: post.published_at }
end
{ id: post.external_id, name: post.name, date:, url: post.full_url }
end
}
end
private
attr_reader :product, :variant_external_id, :options, :page
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/profile_presenter.rb | app/presenters/profile_presenter.rb | # frozen_string_literal: true
class ProfilePresenter
attr_reader :pundit_user, :seller
# seller is the profile being viewed within the consumer area
# pundit_user.seller is the selected seller for the logged-in user (pundit_user.user) - which may be different from seller
def initialize(pundit_user:, seller:)
@pundit_user = pundit_user
@seller = seller
end
def creator_profile
{
external_id: seller.external_id,
avatar_url: seller.avatar_url,
name: seller.name || seller.username,
twitter_handle: seller.twitter_handle,
subdomain: seller.subdomain,
}
end
def profile_props(seller_custom_domain_url:, request:)
shared_profile_props(seller_custom_domain_url:, request:)
end
def profile_settings_props(request:)
memberships = seller.products.membership.alive.not_archived.includes(ProductPresenter::ASSOCIATIONS_FOR_CARD)
shared_profile_props(seller_custom_domain_url: nil, request:, as_logged_out_user: true).merge(
{
profile_settings: {
username: seller.username,
name: seller.name,
bio: seller.bio,
font: seller.seller_profile.font,
background_color: seller.seller_profile.background_color,
highlight_color: seller.seller_profile.highlight_color,
profile_picture_blob_id: seller.avatar.signed_id,
},
memberships: memberships.map { |product| ProductPresenter.card_for_web(product:, show_seller: false) },
}
)
end
private
def shared_profile_props(seller_custom_domain_url:, request:, as_logged_out_user: false)
pundit_user = as_logged_out_user ? SellerContext.logged_out : @pundit_user
{
**profile_sections_presenter.props(request:, pundit_user:, seller_custom_domain_url:),
bio: seller.bio,
tabs: (seller.seller_profile.json_data["tabs"] || [])
.map { |tab| { name: tab["name"], sections: tab["sections"].map { ObfuscateIds.encrypt(_1) } } },
}
end
def profile_sections_presenter
ProfileSectionsPresenter.new(seller:, query: seller.seller_profile_sections.on_profile)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/product_review_video_presenter.rb | app/presenters/product_review_video_presenter.rb | # frozen_string_literal: true
class ProductReviewVideoPresenter
attr_reader :video
def initialize(video)
@video = video
end
def props(pundit_user:)
{
id: video.external_id,
approval_status: video.approval_status,
thumbnail_url: video.video_file.thumbnail_url,
can_approve: Pundit.policy!(pundit_user, video).approve?,
can_reject: Pundit.policy!(pundit_user, video).reject?,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/community_chat_message_presenter.rb | app/presenters/community_chat_message_presenter.rb | # frozen_string_literal: true
class CommunityChatMessagePresenter
def initialize(message:)
@message = message
end
def props
{
id: message.external_id,
community_id: message.community.external_id,
content: message.content,
created_at: message.created_at.iso8601,
updated_at: message.updated_at.iso8601,
user: {
id: message.user.external_id,
name: message.user.display_name,
avatar_url: message.user.avatar_url,
is_seller: message.user_id == message.community.seller_id
}
}
end
private
attr_reader :message
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/tax_center_presenter.rb | app/presenters/tax_center_presenter.rb | # frozen_string_literal: true
class TaxCenterPresenter
include CurrencyHelper
def initialize(seller:, year:)
@seller = seller
@year = available_years.include?(year) ? year : available_years.first
end
def props
{
documents: fetch_documents,
available_years:,
selected_year: year
}
end
private
attr_reader :seller, :year
def fetch_documents
documents = []
tax_form_type = seller.user_tax_forms.for_year(year).first&.tax_form_type
return documents unless tax_form_type
documents << Rails.cache.fetch("tax_form_data_#{tax_form_type}_#{year}_#{seller.id}") do
{
document: format_tax_form_type_for_display(tax_form_type),
type: "IRS form",
year:,
form_type: tax_form_type,
gross: format_cents_as_dollars(calculate_gross),
fees: format_cents_as_dollars(calculate_fees),
taxes: format_cents_as_dollars(calculate_taxes),
affiliate_credit: format_cents_as_dollars(calculate_affiliate_credit),
net: format_cents_as_dollars(calculate_net)
}
end
documents
end
def calculate_gross
@_gross ||= sales_scope.sum(:total_transaction_cents)
end
def calculate_fees
@_fees ||= sales_scope.sum(:fee_cents)
end
def calculate_taxes
@_taxes ||= sales_scope.sum("COALESCE(gumroad_tax_cents, 0) + COALESCE(tax_cents, 0)")
end
def calculate_affiliate_credit
@_affiliate_credit ||= sales_scope.sum(:affiliate_credit_cents)
end
def calculate_net
calculate_gross - calculate_fees - calculate_taxes - calculate_affiliate_credit
end
def sales_scope
start_date = Date.new(year).beginning_of_year
end_date = start_date.end_of_year
seller.sales
.successful
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.where(created_at: start_date..end_date)
.where("purchases.price_cents > 0")
end
def available_years
start_year = seller.created_at.year
end_year = Time.current.year - 1
(start_year..end_year).to_a.reverse
end
def format_cents_as_dollars(cents)
Money.new(cents, Currency::USD).format(symbol: true)
end
def format_tax_form_type_for_display(form_type)
form_type.delete_prefix("us_").tr("_", "-").upcase
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/payouts_presenter.rb | app/presenters/payouts_presenter.rb | # frozen_string_literal: true
class PayoutsPresenter
include CurrencyHelper
include PayoutsHelper
include Pagy::Backend
PAST_PAYMENTS_PER_PAGE = 3
attr_reader :seller, :params
def initialize(seller:, params: {})
@seller = seller
@params = params
end
def past_payout_period_data
past_payouts.map { payout_period_data(seller, _1) }
end
def next_payout_period_data
seller_stats[:next_payout_period_data]&.merge(
has_stripe_connect: seller.stripe_connect_account.present?
)
end
def processing_payout_periods_data
seller_stats[:processing_payout_periods_data].map do |item|
item.merge(has_stripe_connect: seller.stripe_connect_account.present?)
end
end
def instant_payout_data
return nil unless seller.instant_payouts_supported?
{
payable_amount_cents: seller.instantly_payable_unpaid_balance_cents,
payable_balances: seller.instantly_payable_unpaid_balances.sort_by(&:date).reverse.map do |balance|
{
id: balance.external_id,
date: balance.date,
amount_cents: balance.holding_amount_cents,
}
end,
bank_account_type: seller.active_bank_account.bank_account_type,
bank_name: seller.active_bank_account.bank_name,
routing_number: seller.active_bank_account.routing_number,
account_number: seller.active_bank_account.account_number_visual,
}
end
def pagination_data
PagyPresenter.new(pagination).props
end
private
def seller_stats
@seller_stats ||= UserBalanceStatsService.new(user: seller).fetch
end
def pagination
paginated_payouts.first
end
def past_payouts
paginated_payouts.last
end
def paginated_payouts
@paginated_payouts ||= begin
payouts = seller.payments
.completed
.displayable
.order(created_at: :desc)
page_num = validated_page_num(payouts.count)
pagy(payouts, page: page_num, limit: PAST_PAYMENTS_PER_PAGE)
end
end
def validated_page_num(payouts_count)
total_pages = (payouts_count / PAST_PAYMENTS_PER_PAGE.to_f).ceil
page_num = params[:page].to_i
if page_num <= 0
1
elsif page_num > total_pages && total_pages != 0
total_pages
else
page_num
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/utm_link_presenter.rb | app/presenters/utm_link_presenter.rb | # frozen_string_literal: true
class UtmLinkPresenter
include CurrencyHelper
def initialize(seller:, utm_link: nil)
@seller = seller
@utm_link = utm_link
end
def new_page_react_props(copy_from: nil)
reference_utm_link = seller.utm_links.alive.find_by_external_id(copy_from) if copy_from.present?
context_props = utm_link_form_context_props
if reference_utm_link.present?
utm_link_props = self.class.new(seller:, utm_link: reference_utm_link).utm_link_props.except(:id)
utm_link_props[:short_url] = context_props[:short_url]
end
{ context: context_props, utm_link: utm_link_props }
end
def edit_page_react_props
{ context: utm_link_form_context_props, utm_link: utm_link_props }
end
def utm_link_props
{
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: destination_option(type: utm_link.target_resource_type, resource: utm_link.target_resource, add_label_prefix: false),
sales_count: utm_link.respond_to?(:sales_count) ? utm_link.sales_count : nil,
revenue_cents: utm_link.respond_to?(:revenue_cents) ? utm_link.revenue_cents : nil,
conversion_rate: utm_link.respond_to?(:conversion_rate) ? utm_link.conversion_rate.round(4) : nil,
}
end
private
attr_reader :seller, :utm_link
def utm_link_form_context_props
products = *seller.products.includes(:user).alive.order(:name).map { destination_option(type: UtmLink.target_resource_types[:product_page], resource: _1) }
posts = *seller.installments.audience_type.shown_on_profile.not_workflow_installment.published.includes(:seller).order(:name).map { destination_option(type: UtmLink.target_resource_types[:post_page], resource: _1) }
utm_fields_values = seller.utm_links.alive.pluck(:utm_campaign, :utm_medium, :utm_source, :utm_term, :utm_content)
.each_with_object({
campaigns: Set.new,
mediums: Set.new,
sources: Set.new,
terms: Set.new,
contents: Set.new
}) do |(campaign, medium, source, term, content), result|
result[:campaigns] << campaign if campaign.present?
result[:mediums] << medium if medium.present?
result[:sources] << source if source.present?
result[:terms] << term if term.present?
result[:contents] << content if content.present?
end.transform_values(&:to_a)
{
destination_options: [
destination_option(type: UtmLink.target_resource_types[:profile_page]),
destination_option(type: UtmLink.target_resource_types[:subscribe_page]),
*products,
*posts,
],
short_url: utm_link.present? ? utm_link.short_url : UtmLink.new(permalink: UtmLink.generate_permalink).short_url,
utm_fields_values:,
}
end
def destination_option_id(resource_type, resource_external_id)
return resource_type if resource_type.in?(target_resource_types.values_at(:profile_page, :subscribe_page))
[resource_type, resource_external_id].compact_blank.join("-")
end
def destination_option(type:, resource: nil, add_label_prefix: true)
external_id = resource.external_id if resource.present?
id = destination_option_id(type, external_id)
case type
when target_resource_types[:product_page]
{ id:, label: "#{add_label_prefix ? "Product — " : ""}#{resource.name}", url: resource.long_url }
when target_resource_types[:post_page]
{ id:, label: "#{add_label_prefix ? "Post — " : ""}#{resource.name}", url: resource.full_url }
when target_resource_types[:profile_page]
{ id:, label: "Profile page", url: seller.profile_url }
when target_resource_types[:subscribe_page]
{ id:, label: "Subscribe page", url: Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: seller.subdomain_with_protocol) }
end
end
def target_resource_types = UtmLink.target_resource_types
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/product_presenter.rb | app/presenters/product_presenter.rb | # frozen_string_literal: true
class ProductPresenter
include Rails.application.routes.url_helpers
include ProductsHelper
include CurrencyHelper
include PreorderHelper
extend PreorderHelper
attr_reader :product, :editing_page_id, :pundit_user, :request
delegate :user, :skus,
:skus_enabled, :is_licensed, :is_multiseat_license, :quantity_enabled, :description,
:is_recurring_billing, :should_include_last_post, :should_show_all_posts, :should_show_sales_count,
:block_access_after_membership_cancellation, :duration_in_months, to: :product, allow_nil: true
def initialize(product:, editing_page_id: nil, request: nil, pundit_user: nil)
@product = product
@editing_page_id = editing_page_id
@request = request
@pundit_user = pundit_user
end
def self.new_page_props(current_seller:)
native_product_types = Link::NATIVE_TYPES - Link::LEGACY_TYPES - Link::SERVICE_TYPES
native_product_types -= [Link::NATIVE_TYPE_PHYSICAL] unless current_seller.can_create_physical_products?
service_product_types = Link::SERVICE_TYPES
service_product_types -= [Link::NATIVE_TYPE_COMMISSION] unless Feature.active?(:commissions, current_seller)
release_at_date = displayable_release_at_date(1.month.from_now, current_seller.timezone)
{
current_seller_currency_code: current_seller.currency_type,
native_product_types:,
service_product_types:,
release_at_date:,
show_orientation_text: current_seller.products.visible.none?,
eligible_for_service_products: current_seller.eligible_for_service_products?,
ai_generation_enabled: current_seller.eligible_for_ai_product_generation?,
ai_promo_dismissed: current_seller.dismissed_create_products_with_ai_promo_alert?,
}
end
ASSOCIATIONS_FOR_CARD = ProductPresenter::Card::ASSOCIATIONS
def self.card_for_web(product:, request: nil, recommended_by: nil, recommender_model_name: nil, target: nil, show_seller: true, affiliate_id: nil, query: nil, offer_code: nil, compute_description: true)
ProductPresenter::Card.new(product:).for_web(request:, recommended_by:, recommender_model_name:, target:, show_seller:, affiliate_id:, query:, offer_code:, compute_description:)
end
def self.card_for_email(product:)
ProductPresenter::Card.new(product:).for_email
end
def product_props(**kwargs)
ProductPresenter::ProductProps.new(product:).props(request:, pundit_user:, **kwargs)
end
def product_page_props(seller_custom_domain_url:, **kwargs)
sections_props = ProfileSectionsPresenter.new(seller: user, query: product.seller_profile_sections).props(request:, pundit_user:, seller_custom_domain_url:)
{
**product_props(seller_custom_domain_url:, **kwargs),
**sections_props,
sections: product.sections.filter_map { |id| sections_props[:sections].find { |section| section[:id] === ObfuscateIds.encrypt(id) } },
main_section_index: product.main_section_index || 0,
}
end
def covers
{
covers: product.display_asset_previews.as_json,
main_cover_id: product.main_preview&.guid
}
end
def existing_files
user.alive_product_files_preferred_for_product(product)
.limit($redis.get(RedisKey.product_presenter_existing_product_files_limit))
.order(id: :desc)
.includes(:alive_subtitle_files).map { _1.as_json(existing_product_file: true) }
end
def edit_props
refund_policy = product.find_or_initialize_product_refund_policy
profile_sections = product.user.seller_profile_products_sections
collaborator = product.collaborator_for_display
cancellation_discount = product.cancellation_discount_offer_code
{
product: {
name: product.name,
custom_permalink: product.custom_permalink,
description: product.description || "",
price_cents: product.price_cents,
customizable_price: !!product.customizable_price,
suggested_price_cents: product.suggested_price_cents,
**ProductPresenter::InstallmentPlanProps.new(product:).props,
custom_button_text_option: product.custom_button_text_option.presence,
custom_summary: product.custom_summary,
custom_view_content_button_text: product.custom_view_content_button_text,
custom_view_content_button_text_max_length: Product::Validations::MAX_VIEW_CONTENT_BUTTON_TEXT_LENGTH,
custom_receipt_text: product.custom_receipt_text,
custom_receipt_text_max_length: Product::Validations::MAX_CUSTOM_RECEIPT_TEXT_LENGTH,
custom_attributes: product.custom_attributes,
file_attributes: product.file_info_for_product_page.map { { name: _1.to_s, value: _2 } },
max_purchase_count: product.max_purchase_count,
quantity_enabled: product.quantity_enabled,
can_enable_quantity: product.can_enable_quantity?,
should_show_sales_count: product.should_show_sales_count,
hide_sold_out_variants: product.hide_sold_out_variants?,
is_epublication: product.is_epublication?,
product_refund_policy_enabled: product.product_refund_policy_enabled?,
refund_policy: {
allowed_refund_periods_in_days: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.keys.map do
{
key: _1,
value: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[_1]
}
end,
max_refund_period_in_days: refund_policy.max_refund_period_in_days,
fine_print: refund_policy.fine_print,
fine_print_enabled: refund_policy.fine_print.present?,
title: refund_policy.title,
},
covers: product.display_asset_previews.as_json,
is_published: !product.draft && product.alive?,
require_shipping: product.require_shipping?,
integrations: Integration::ALL_NAMES.index_with { |name| @product.find_integration_by_name(name).as_json },
variants: product.alive_variants.in_order.map do |variant|
props = {
id: variant.external_id,
name: variant.name || "",
description: variant.description || "",
max_purchase_count: variant.max_purchase_count,
integrations: Integration::ALL_NAMES.index_with { |name| variant.find_integration_by_name(name).present? },
rich_content: variant.rich_content_json,
sales_count_for_inventory: variant.max_purchase_count? ? variant.sales_count_for_inventory : 0,
active_subscribers_count: variant.active_subscribers_count,
}
props[:duration_in_minutes] = variant.duration_in_minutes if product.native_type == Link::NATIVE_TYPE_CALL
if product.native_type == Link::NATIVE_TYPE_MEMBERSHIP
props.merge!(
customizable_price: !!variant.customizable_price,
recurrence_price_values: variant.recurrence_price_values(for_edit: true),
apply_price_changes_to_existing_memberships: variant.apply_price_changes_to_existing_memberships?,
subscription_price_change_effective_date: variant.subscription_price_change_effective_date,
subscription_price_change_message: variant.subscription_price_change_message,
)
else
props[:price_difference_cents] = variant.price_difference_cents
end
props
end,
availabilities: product.native_type == Link::NATIVE_TYPE_CALL ?
product.call_availabilities.map do |availability|
{
id: availability.external_id,
start_time: availability.start_time.iso8601,
end_time: availability.end_time.iso8601,
}
end : [],
shipping_destinations: product.shipping_destinations.alive.map do |shipping_destination|
{
country_code: shipping_destination.country_code,
one_item_rate_cents: shipping_destination.one_item_rate_cents,
multiple_items_rate_cents: shipping_destination.multiple_items_rate_cents,
}
end,
section_ids: profile_sections.filter_map { |section| section.external_id if section.shown_products.include?(product.id) },
taxonomy_id: product.taxonomy_id&.to_s,
tags: product.tags.pluck(:name),
display_product_reviews: product.display_product_reviews,
is_adult: product.is_adult,
discover_fee_per_thousand: product.discover_fee_per_thousand,
custom_domain: product.custom_domain&.domain || "",
free_trial_enabled: product.free_trial_enabled,
free_trial_duration_amount: product.free_trial_duration_amount,
free_trial_duration_unit: product.free_trial_duration_unit,
should_include_last_post: product.should_include_last_post,
should_show_all_posts: product.should_show_all_posts,
block_access_after_membership_cancellation: product.block_access_after_membership_cancellation,
duration_in_months: product.duration_in_months,
subscription_duration: product.subscription_duration,
collaborating_user: collaborator.present? ? UserPresenter.new(user: collaborator).author_byline_props : nil,
rich_content: product.rich_content_json,
files: files_data(product),
has_same_rich_content_for_all_variants: @product.has_same_rich_content_for_all_variants?,
is_multiseat_license:,
call_limitation_info: product.native_type == Link::NATIVE_TYPE_CALL && product.call_limitation_info.present? ?
{
minimum_notice_in_minutes: product.call_limitation_info.minimum_notice_in_minutes,
maximum_calls_per_day: product.call_limitation_info.maximum_calls_per_day,
} : nil,
native_type: product.native_type,
cancellation_discount: cancellation_discount.present? ? {
discount:
cancellation_discount.is_cents? ?
{ type: "fixed", cents: cancellation_discount.amount_cents } :
{ type: "percent", percents: cancellation_discount.amount_percentage },
duration_in_billing_cycles: cancellation_discount.duration_in_billing_cycles,
} : nil,
public_files: product.alive_public_files.attached.map { PublicFilePresenter.new(public_file: _1).props },
audio_previews_enabled: Feature.active?(:audio_previews, product.user),
community_chat_enabled: Feature.active?(:communities, product.user) ? product.community_chat_enabled? : nil,
},
id: product.external_id,
unique_permalink: product.unique_permalink,
thumbnail: product.thumbnail&.alive&.as_json,
refund_policies: product.user
.product_refund_policies
.for_visible_and_not_archived_products
.where.not(product_id: product.id)
.order(updated_at: :desc)
.select("refund_policies.*", "links.name")
.as_json,
currency_type: product.price_currency_type,
is_tiered_membership: product.is_tiered_membership,
is_listed_on_discover: product.recommendable?,
is_physical: product.is_physical,
profile_sections: profile_sections.map do |section|
{
id: section.external_id,
header: section.header || "",
product_names: section.product_names,
default: section.add_new_products,
}
end,
taxonomies: Discover::TaxonomyPresenter.new.taxonomies_for_nav,
earliest_membership_price_change_date: BaseVariant::MINIMUM_DAYS_TIL_EXISTING_MEMBERSHIP_PRICE_CHANGE.days.from_now.in_time_zone(product.user.timezone).iso8601,
custom_domain_verification_status:,
sales_count_for_inventory: product.max_purchase_count? ? product.sales_count_for_inventory : 0,
successful_sales_count: product.successful_sales_count,
ratings: product.rating_stats,
seller: UserPresenter.new(user:).author_byline_props,
existing_files:,
s3_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}",
aws_key: AWS_ACCESS_KEY,
available_countries: ShippingDestination::Destinations.shipping_countries.map { { code: _1[0], name: _1[1] } },
google_client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
google_calendar_enabled: Feature.active?(:google_calendar_link, product.user),
seller_refund_policy_enabled: product.user.account_level_refund_policy_enabled?,
seller_refund_policy: {
title: product.user.refund_policy.title,
fine_print: product.user.refund_policy.fine_print,
},
cancellation_discounts_enabled: Feature.active?(:cancellation_discounts, product.user),
}
end
def admin_info
{
custom_summary: product.custom_summary.presence,
file_info_attributes: product.file_info_for_product_page.map do |k, v|
{ name: k.to_s, value: v }
end,
custom_attributes: product.custom_attributes.filter_map do |attr|
{ name: attr["name"], value: attr["value"] } if attr["name"].present? || attr["value"].present?
end,
preorder: product.is_in_preorder_state ? { release_date_fmt: displayable_release_at_date_and_time(product.preorder_link.release_at, product.user.timezone) } : nil,
has_stream_only_files: product.has_stream_only_files?,
should_show_sales_count: product.should_show_sales_count,
sales_count: product.should_show_sales_count ? product.successful_sales_count : 0,
is_recurring_billing: product.is_recurring_billing,
price_cents: product.price_cents,
}
end
private
def default_sku
skus_enabled && skus.alive.not_is_default_sku.empty? ? skus.is_default_sku.first : nil
end
def collaborating_user
return @_collaborating_user if defined?(@_collaborating_user)
collaborator = product.collaborator_for_display
@_collaborating_user = collaborator.present? ? UserPresenter.new(user: collaborator).author_byline_props : nil
end
def rich_content_pages
variants = @product.alive_variants.includes(:alive_rich_contents, variant_category: { link: :user })
if refer_to_product_level_rich_content?(has_variants: variants.size > 0)
product.rich_content_json
else
variants.flat_map(&:rich_content_json)
end
end
def refer_to_product_level_rich_content?(has_variants:)
product.is_physical? || !has_variants || product.has_same_rich_content_for_all_variants?
end
def custom_domain_verification_status
custom_domain = @product.custom_domain
return if custom_domain.blank?
domain = custom_domain.domain
if custom_domain.verified?
{
success: true,
message: "#{domain} domain is correctly configured!",
}
else
{
success: false,
message: "Domain verification failed. Please make sure you have correctly configured the DNS record for #{domain}.",
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/dashboard_products_page_presenter.rb | app/presenters/dashboard_products_page_presenter.rb | # frozen_string_literal: true
class DashboardProductsPagePresenter
include Product::Caching
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::TextHelper
include Rails.application.routes.url_helpers
attr_reader :memberships, :memberships_pagination, :products, :products_pagination, :pundit_user
def initialize(pundit_user:, memberships:, memberships_pagination:, products:, products_pagination:)
@pundit_user = pundit_user
@memberships = memberships
@memberships_pagination = memberships_pagination
@products = products
@products_pagination = products_pagination
end
def page_props
{
memberships: memberships_data,
memberships_pagination:,
products: products_data,
products_pagination:,
archived_products_count: @pundit_user.seller.archived_products_count,
can_create_product: Pundit.policy!(@pundit_user, Link).create?,
}
end
def memberships_table_props
{
memberships: memberships_data,
memberships_pagination:,
}
end
def products_table_props
{
products: products_data,
products_pagination:,
}
end
private
def memberships_data
Product::Caching.dashboard_collection_data(memberships, cache: true) do |membership|
product_base_data(membership, pundit_user:)
end
end
def products_data
Product::Caching.dashboard_collection_data(products, cache: true) do |product|
product_base_data(product, pundit_user:)
end
end
def product_base_data(product, pundit_user:)
{
"id" => product.id,
"edit_url" => edit_link_path(product),
"is_duplicating" => product.is_duplicating?,
"is_unpublished" => product.draft? || product.purchase_disabled_at?,
"name" => product.name,
"permalink" => product.unique_permalink,
"price_formatted" => product.price_formatted_including_rental_verbose,
"revenue" => product.total_usd_cents,
"status" => product_status(product),
"thumbnail" => product.thumbnail&.alive&.as_json,
"display_price_cents" => product.display_price_cents,
"url" => product.long_url,
"url_without_protocol" => product.long_url(include_protocol: false),
"has_duration" => product.duration_in_months.present?,
"can_edit" => Pundit.policy!(pundit_user, product).edit?,
"can_destroy" => Pundit.policy!(pundit_user, product).destroy?,
"can_duplicate" => Pundit.policy!(pundit_user, [:product_duplicates, product]).create?,
"can_archive" => Pundit.policy!(pundit_user, [:products, :archived, product]).create?,
"can_unarchive" => Pundit.policy!(pundit_user, [:products, :archived, product]).destroy?,
}
end
def product_status(product)
if product.draft? || product.purchase_disabled_at?
"unpublished"
elsif product.is_in_preorder_state?
"preorder"
else
"published"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/public_file_presenter.rb | app/presenters/public_file_presenter.rb | # frozen_string_literal: true
class PublicFilePresenter
include CdnUrlHelper
def initialize(public_file:)
@public_file = public_file
end
def props
{
id: public_file.public_id,
name: public_file.display_name,
extension: public_file.file_type&.upcase,
file_size: public_file.file_size,
url: public_file.file.attached? ? cdn_url_for(public_file.file.blob.url) : nil,
status: { type: "saved" },
}
end
private
attr_reader :public_file
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings_presenter.rb | app/presenters/settings_presenter.rb | # frozen_string_literal: true
class SettingsPresenter
include CurrencyHelper
include ActiveSupport::NumberHelper
attr_reader :pundit_user, :seller
ALL_PAGES = %w(
main
profile
team
payments
authorized_applications
password
third_party_analytics
advanced
).freeze
private_constant :ALL_PAGES
def initialize(pundit_user:)
@pundit_user = pundit_user
@seller = pundit_user.seller
end
def pages
@_pages ||= ALL_PAGES.select do |page|
case page
when "main", "payments", "password", "third_party_analytics", "advanced"
Pundit.policy!(pundit_user, [:settings, page.to_sym, seller]).show?
when "profile"
Pundit.policy!(pundit_user, [:settings, page.to_sym]).show?
when "team"
Pundit.policy!(pundit_user, [:settings, :team, seller]).show?
when "authorized_applications"
Pundit.policy!(pundit_user, [:settings, :authorized_applications, OauthApplication]).index? &&
OauthApplication.alive.authorized_for(seller).present?
else
raise StandardError, "Unsupported page `#{page}`"
end
end
end
def main_props
{
settings_pages: pages,
is_form_disabled: !Pundit.policy!(pundit_user, [:settings, :main, seller]).update?,
invalidate_active_sessions: Pundit.policy!(pundit_user, [:settings, :main, seller]).invalidate_active_sessions?,
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 { |name, code| { name:, code: } },
user: {
email: seller.form_email,
support_email: seller.support_email,
locale: seller.locale,
timezone: seller.timezone,
currency_type: seller.currency_type,
has_unconfirmed_email: seller.has_unconfirmed_email?,
compliance_country: seller.alive_user_compliance_info&.country,
purchasing_power_parity_enabled: seller.purchasing_power_parity_enabled?,
purchasing_power_parity_limit: seller.purchasing_power_parity_limit,
purchasing_power_parity_payment_verification_disabled: seller.purchasing_power_parity_payment_verification_disabled?,
products: seller.products.visible.map { |product| { id: product.external_id, name: product.name } },
purchasing_power_parity_excluded_product_ids: seller.purchasing_power_parity_excluded_product_external_ids,
enable_payment_email: seller.enable_payment_email,
enable_payment_push_notification: seller.enable_payment_push_notification,
enable_recurring_subscription_charge_email: seller.enable_recurring_subscription_charge_email,
enable_recurring_subscription_charge_push_notification: seller.enable_recurring_subscription_charge_push_notification,
enable_free_downloads_email: seller.enable_free_downloads_email,
enable_free_downloads_push_notification: seller.enable_free_downloads_push_notification,
announcement_notification_enabled: seller.announcement_notification_enabled,
disable_comments_email: seller.disable_comments_email,
disable_reviews_email: seller.disable_reviews_email,
show_nsfw_products: seller.show_nsfw_products?,
disable_affiliate_requests: seller.disable_affiliate_requests?,
seller_refund_policy:,
product_level_support_emails: seller.product_level_support_emails_enabled? ? seller.product_level_support_emails : nil
}
}
end
def application_props(application)
{
settings_pages: pages,
application: {
id: application.external_id,
name: application.name,
redirect_uri: application.redirect_uri,
icon_url: application.icon_url,
uid: application.uid,
secret: application.secret,
}
}
end
def advanced_props
if seller.custom_domain&.unverified?
domain = seller.custom_domain.domain
has_valid_configuration = CustomDomainVerificationService.new(domain:).process
message = has_valid_configuration ? "#{domain} domain is correctly configured!"
: "Domain verification failed. Please make sure you have correctly configured the DNS record for #{domain}."
custom_domain_verification_status = { success: has_valid_configuration, message: }
else
custom_domain_verification_status = nil
end
{
settings_pages: pages,
user_id: ObfuscateIds.encrypt(seller.id),
notification_endpoint: seller.notification_endpoint || "",
blocked_customer_emails: seller.blocked_customer_objects.active.email.pluck(:object_value).join("\n"),
custom_domain_verification_status:,
custom_domain_name: seller.custom_domain&.domain || "",
applications: seller.oauth_applications.alive.map do |oauth_application|
{
id: oauth_application.external_id,
name: oauth_application.name,
icon_url: oauth_application.icon_url
}
end,
allow_deactivation: Pundit.policy!(pundit_user, [:user]).deactivate?,
formatted_balance_to_forfeit_on_account_deletion: seller.formatted_balance_to_forfeit(:account_closure),
}
end
def profile_props
{
settings_pages: pages
}
end
def third_party_analytics_props
{
disable_third_party_analytics: seller.disable_third_party_analytics,
google_analytics_id: seller.google_analytics_id || "",
facebook_pixel_id: seller.facebook_pixel_id || "",
skip_free_sale_analytics: seller.skip_free_sale_analytics,
facebook_meta_tag: seller.facebook_meta_tag || "",
enable_verify_domain_third_party_services: seller.enable_verify_domain_third_party_services,
snippets: seller.third_party_analytics.alive.map do |third_party_analytic|
{
id: third_party_analytic.external_id,
product: third_party_analytic.link&.unique_permalink,
name: third_party_analytic.name.presence || "",
location: third_party_analytic.location,
code: third_party_analytic.analytics_code,
}
end
}
end
def password_props
{
require_old_password: seller.provider.blank?,
settings_pages: pages,
}
end
def authorized_applications_props
authorized_applications = OauthApplication.alive.authorized_for(seller)
application_grants = {}
valid_applications = []
authorized_applications.each do |application|
access_grant = Doorkeeper::AccessGrant.order("created_at").where(application_id: application.id, resource_owner_id: seller.id).first
next if access_grant.nil?
valid_applications << application
application_grants[application.id] = access_grant
end
valid_applications = valid_applications.sort_by { |application| application_grants[application.id].created_at }
authorized_applications = valid_applications.map do |application| {
name: application.name,
icon_url: application.icon_url,
is_own_app: application.owner == seller,
first_authorized_at: application_grants[application.id].created_at.iso8601,
scopes: application_grants[application.id].scopes,
id: application.external_id,
} end
{
settings_pages: pages,
authorized_applications:
}
end
def payments_props(remote_ip: nil)
user_compliance_info = seller.fetch_or_build_user_compliance_info
{
settings_pages: pages,
is_form_disabled: !Pundit.policy!(pundit_user, [:settings, :payments, seller]).update?,
should_show_country_modal: !seller.fetch_or_build_user_compliance_info.country.present? &&
Pundit.policy!(pundit_user, [:settings, :payments, seller]).set_country?,
aus_backtax_details: aus_backtax_details(user_compliance_info),
stripe_connect:,
countries: Compliance::Countries.for_select.to_h,
ip_country_code: GeoIp.lookup(remote_ip)&.country_code,
bank_account_details:,
paypal_address: seller.payment_address,
show_verification_section: seller.user_compliance_info_requests.requested.present? && seller.stripe_account.present? && Pundit.policy!(pundit_user, [:settings, :payments, seller]).update?,
paypal_connect:,
fee_info: fee_info(user_compliance_info),
user: user_details(user_compliance_info),
compliance_info: compliance_info_details(user_compliance_info),
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:,
saved_card: CheckoutPresenter.saved_card(seller.credit_card),
formatted_balance_to_forfeit_on_country_change: seller.formatted_balance_to_forfeit(:country_change),
formatted_balance_to_forfeit_on_payout_method_change: seller.formatted_balance_to_forfeit(:payout_method_change),
payouts_paused_internally: seller.payouts_paused_internally?,
payouts_paused_by: seller.payouts_paused_by_source,
payouts_paused_for_reason: seller.payouts_paused_for_reason,
payouts_paused_by_user: seller.payouts_paused_by_user?,
payout_threshold_cents: seller.minimum_payout_amount_cents,
minimum_payout_threshold_cents: seller.minimum_payout_threshold_cents,
payout_frequency: seller.payout_frequency,
payout_frequency_daily_supported: seller.instant_payouts_supported?,
}
end
def seller_refund_policy
{
enabled: seller.account_level_refund_policy_enabled?,
allowed_refund_periods_in_days: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.keys.map do
{
key: _1,
value: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[_1]
}
end,
max_refund_period_in_days: seller.refund_policy.max_refund_period_in_days,
fine_print: seller.refund_policy.fine_print,
fine_print_enabled: seller.refund_policy.fine_print.present?,
}
end
private
def user_details(user_compliance_info)
{
country_supports_native_payouts: seller.native_payouts_supported?,
country_supports_iban: seller.country_supports_iban?,
need_full_ssn: seller.has_ever_been_requested_for_user_compliance_info_field?(UserComplianceInfoFields::Individual::TAX_ID),
country_code: user_compliance_info.legal_entity_country_code,
payout_currency: Country.new(user_compliance_info.country_code).payout_currency,
is_from_europe: seller.signed_up_from_europe?,
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: user_compliance_info.individual_tax_id.present?,
business_tax_id_entered: user_compliance_info.business_tax_id.present?,
requires_credit_card: seller.requires_credit_card?,
can_connect_stripe: seller.can_connect_stripe?,
is_charged_paypal_payout_fee: seller.charge_paypal_payout_fee?,
joined_at: seller.created_at.iso8601
}
end
def compliance_info_details(user_compliance_info)
{
is_business: user_compliance_info.is_business?,
business_name: user_compliance_info.business_name,
business_name_kanji: user_compliance_info.business_name_kanji,
business_name_kana: user_compliance_info.business_name_kana,
business_type: user_compliance_info.business_type,
business_street_address: user_compliance_info.business_street_address,
business_building_number: user_compliance_info.business_building_number,
business_street_address_kanji: user_compliance_info.business_street_address_kanji,
business_street_address_kana: user_compliance_info.business_street_address_kana,
business_city: user_compliance_info.business_city,
business_state: user_compliance_info.business_state,
business_country: user_compliance_info.business_country_code || user_compliance_info.country_code,
business_zip_code: user_compliance_info.business_zip_code,
business_phone: user_compliance_info.business_phone,
job_title: user_compliance_info.job_title,
first_name: user_compliance_info.first_name,
last_name: user_compliance_info.last_name,
first_name_kanji: user_compliance_info.first_name_kanji,
last_name_kanji: user_compliance_info.last_name_kanji,
first_name_kana: user_compliance_info.first_name_kana,
last_name_kana: user_compliance_info.last_name_kana,
street_address: user_compliance_info.street_address,
building_number: user_compliance_info.building_number,
street_address_kanji: user_compliance_info.street_address_kanji,
street_address_kana: user_compliance_info.street_address_kana,
city: user_compliance_info.city,
state: user_compliance_info.state,
country: user_compliance_info.country_code,
zip_code: user_compliance_info.zip_code,
phone: user_compliance_info.phone,
nationality: user_compliance_info.nationality,
dob_month: user_compliance_info.birthday.try(:month).to_i,
dob_day: user_compliance_info.birthday.try(:day).to_i,
dob_year: user_compliance_info.birthday.try(:year).to_i,
}
end
def bank_account_details
bank_account = seller.active_bank_account
{
show_bank_account: seller.can_setup_bank_payouts?,
show_paypal: seller.can_setup_paypal_payouts?,
card_data_handling_mode: CardDataHandlingMode.get_card_data_handling_mode(seller),
is_a_card: bank_account.is_a?(CardBankAccount),
card: bank_account.is_a?(CardBankAccount) ? {
type: bank_account.credit_card.card_type,
number: bank_account.credit_card.visual,
expiration_date: bank_account.credit_card.expiry_visual,
requires_mandate: false
} : nil,
routing_number: bank_account.present? && !bank_account.is_a?(CardBankAccount) ? bank_account.routing_number : nil,
account_number_visual: bank_account.present? && !bank_account.is_a?(CardBankAccount) ? bank_account.account_number_visual : nil,
bank_account: bank_account.present? && !bank_account.is_a?(CardBankAccount) ? {
account_holder_full_name: bank_account.account_holder_full_name,
} : nil,
}
end
def aus_backtax_details(user_compliance_info)
{
show_au_backtax_prompt: Feature.active?(:au_backtaxes, seller) &&
seller.au_backtax_owed_cents >= User::MIN_AU_BACKTAX_OWED_CENTS_FOR_CONTACT &&
AustraliaBacktaxEmailInfo.where(user_id: seller.id).exists?,
total_amount_to_au: Money.new(seller.au_backtax_sales_cents).format(no_cents_if_whole: false, symbol: true),
au_backtax_amount: Money.new(seller.au_backtax_owed_cents).format(no_cents_if_whole: false, symbol: true),
opt_in_date: seller.au_backtax_agreement_date&.strftime("%B %e, %Y"),
credit_creation_date: seller.credit_creation_date,
opted_in_to_au_backtax: seller.opted_in_to_australia_backtaxes?,
legal_entity_name: user_compliance_info.legal_entity_name,
are_au_backtaxes_paid: seller.paid_for_austalia_backtaxes?,
au_backtaxes_paid_date: seller.date_paid_australia_backtaxes,
}
end
def stripe_connect
{
has_connected_stripe: seller.stripe_connect_account.present?,
stripe_connect_account_id: seller.stripe_connect_account&.charge_processor_merchant_id,
stripe_disconnect_allowed: seller.stripe_disconnect_allowed?,
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.",
}
end
def paypal_connect
paypal_merchant_account = seller.merchant_accounts.alive.paypal.first
if paypal_merchant_account
payment_integration_api = PaypalIntegrationRestApi.new(seller, authorization_header: PaypalPartnerRestCredentials.new.auth_token)
merchant_account_response = payment_integration_api.get_merchant_account_by_merchant_id(paypal_merchant_account.charge_processor_merchant_id)
parsed_response = merchant_account_response.parsed_response
paypal_merchant_account_email = parsed_response["primary_email"]
end
{
show_paypal_connect: Pundit.policy!(pundit_user, [:settings, :payments, seller]).paypal_connect? && seller.paypal_connect_enabled?,
allow_paypal_connect: seller.paypal_connect_allowed?,
unsupported_countries: PaypalMerchantAccountManager::COUNTRY_CODES_NOT_SUPPORTED_BY_PCP.map { |code| ISO3166::Country[code].common_name },
email: paypal_merchant_account_email,
charge_processor_merchant_id: paypal_merchant_account&.charge_processor_merchant_id,
charge_processor_verified: paypal_merchant_account.present? && paypal_merchant_account.charge_processor_verified?,
needs_email_confirmation: paypal_merchant_account.present? && paypal_merchant_account.meta.present? && paypal_merchant_account.meta["isEmailConfirmed"] == "false",
paypal_disconnect_allowed: seller.paypal_disconnect_allowed?,
}
end
def 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: } },
}
end
def fee_info(user_compliance_info)
processor_fee_percent = (Purchase::PROCESSOR_FEE_PER_THOUSAND / 10.0).round(1)
processor_fee_percent = processor_fee_percent.to_i == processor_fee_percent ? processor_fee_percent.to_i : processor_fee_percent
processor_fee_fixed_cents = Purchase::PROCESSOR_FIXED_FEE_CENTS
discover_fee_percent = (Purchase::GUMROAD_DISCOVER_FEE_PER_THOUSAND / 10.0).round(1)
discover_fee_percent = discover_fee_percent.to_i == discover_fee_percent ? discover_fee_percent.to_i : discover_fee_percent
direct_fee_percent = ((seller.custom_fee_per_thousand.presence || Purchase::GUMROAD_FLAT_FEE_PER_THOUSAND) / 10.0).round(1)
direct_fee_percent = direct_fee_percent.to_i == direct_fee_percent ? direct_fee_percent.to_i : direct_fee_percent
fixed_fee_cents = Purchase::GUMROAD_FIXED_FEE_CENTS
if user_compliance_info&.country_code == Compliance::Countries::BRA.alpha2
{
card_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: #{direct_fee_percent}% + #{fixed_fee_cents}¢ Gumroad fee + #{processor_fee_percent}% + #{processor_fee_fixed_cents}¢ credit card fee.\n• Discover sales: #{discover_fee_percent}% flat\n",
connect_account_fee_info_text: "All sales will incur a 0% Gumroad fee.",
paypal_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: #{direct_fee_percent}% + #{fixed_fee_cents}¢ Gumroad fee + #{processor_fee_percent}% + #{processor_fee_fixed_cents}¢ PayPal fee.\n• Discover sales: #{discover_fee_percent}% flat\n"
}
else
{
card_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: #{direct_fee_percent}% + #{fixed_fee_cents}¢ Gumroad fee + #{processor_fee_percent}% + #{processor_fee_fixed_cents}¢ credit card fee.\n• Discover sales: #{discover_fee_percent}% flat\n",
connect_account_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: #{direct_fee_percent}% + #{fixed_fee_cents}¢\n• Discover sales: #{discover_fee_percent}% flat\n",
paypal_fee_info_text: "All sales will incur fees based on how customers find your product:\n\n• Direct sales: #{direct_fee_percent}% + #{fixed_fee_cents}¢ Gumroad fee + #{processor_fee_percent}% + #{processor_fee_fixed_cents}¢ PayPal fee.\n• Discover sales: #{discover_fee_percent}% flat\n",
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/paginated_installments_presenter.rb | app/presenters/paginated_installments_presenter.rb | # frozen_string_literal: true
class PaginatedInstallmentsPresenter
include Pagy::Backend
PER_PAGE = 25
private_constant :PER_PAGE
def initialize(seller:, type:, page: nil, query: nil)
@type = type
@seller = seller
@page = [page.to_i, 1].max
@query = query&.strip
raise ArgumentError, "Invalid type" unless type.in? [Installment::PUBLISHED, Installment::SCHEDULED, Installment::DRAFT]
end
def props
if query.blank?
installments = Installment.includes(:installment_rule).all
installments = installments.ordered_updates(seller, type).public_send(type)
installments = installments.unscope(:order).order("installment_rules.to_be_published_at ASC") if type == Installment::SCHEDULED
pagination, installments = pagy(installments, page:, limit: PER_PAGE, overflow: :empty_page)
pagiation_metadata = { count: pagination.count, next: pagination.next }
else
offset = (page - 1) * PER_PAGE
search_options = {
exclude_deleted: true,
type:,
exclude_workflow_installments: true,
seller:,
q: query,
fields: %w[name message],
from: offset,
size: PER_PAGE,
sort: [:_score, { created_at: :desc }, { id: :desc }]
}
es_search = InstallmentSearchService.search(search_options)
installments = es_search.records.load
can_paginate_further = es_search.results.total > (offset + PER_PAGE)
pagiation_metadata = { count: es_search.results.total, next: can_paginate_further ? page + 1 : nil }
end
current_seller = seller
{
installments: installments.map { InstallmentPresenter.new(seller:, installment: _1).props },
pagination: pagiation_metadata,
has_posts: current_seller.installments.alive.not_workflow_installment.public_send(type).exists?,
}
end
private
attr_reader :seller, :type, :page, :query
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/paginated_community_chat_messages_presenter.rb | app/presenters/paginated_community_chat_messages_presenter.rb | # frozen_string_literal: true
class PaginatedCommunityChatMessagesPresenter
include Pagy::Backend
MESSAGES_PER_PAGE = 100
def initialize(community:, timestamp:, fetch_type:)
@community = community
@timestamp = timestamp
@fetch_type = fetch_type
raise ArgumentError, "Invalid timestamp" unless timestamp.present?
raise ArgumentError, "Invalid fetch type" unless %w[older newer around].include?(fetch_type)
end
def props
base_query = community.community_chat_messages.alive.includes(:community, user: :avatar_attachment)
messages, next_older_timestamp, next_newer_timestamp = fetch_messages(base_query)
{
messages: messages.map { |message| CommunityChatMessagePresenter.new(message:).props },
next_older_timestamp:,
next_newer_timestamp:
}
end
private
attr_reader :community, :timestamp, :fetch_type
def fetch_messages(base_query)
case fetch_type
when "older"
result = base_query.order(created_at: :desc).where("created_at <= ?", timestamp).limit(MESSAGES_PER_PAGE + 1).to_a
messages = result.take(MESSAGES_PER_PAGE)
next_older_timestamp = result.size > MESSAGES_PER_PAGE ? result.last.created_at.iso8601 : nil
next_newer_timestamp = base_query.order(created_at: :asc).where("created_at > ?", timestamp).limit(1).first&.created_at&.iso8601
[messages, next_older_timestamp, next_newer_timestamp]
when "newer"
result = base_query.order(created_at: :asc).where("created_at >= ?", timestamp).limit(MESSAGES_PER_PAGE + 1).to_a
messages = result.take(MESSAGES_PER_PAGE)
next_older_timestamp = base_query.order(created_at: :desc).where("created_at < ?", timestamp).limit(1).first&.created_at&.iso8601
next_newer_timestamp = result.size > MESSAGES_PER_PAGE ? result.last.created_at.iso8601 : nil
[messages, next_older_timestamp, next_newer_timestamp]
when "around"
half_per_page = MESSAGES_PER_PAGE / 2
older = base_query.order(created_at: :desc).where("created_at < ?", timestamp).limit(half_per_page + 1).to_a
newer = base_query.order(created_at: :asc).where("created_at >= ?", timestamp).limit(half_per_page + 1).to_a
messages = older.take(half_per_page) + newer.take(half_per_page)
next_older_timestamp = older.size > half_per_page ? older.last.created_at.iso8601 : nil
next_newer_timestamp = newer.size > half_per_page ? newer.last.created_at.iso8601 : nil
[messages.sort_by(&:created_at), next_older_timestamp, next_newer_timestamp]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/creator_home_presenter.rb | app/presenters/creator_home_presenter.rb | # frozen_string_literal: true
class CreatorHomePresenter
include CurrencyHelper
ACTIVITY_ITEMS_LIMIT = 10
BALANCE_ITEMS_LIMIT = 3
attr_reader :pundit_user, :seller
def initialize(pundit_user)
@seller = pundit_user.seller
@pundit_user = pundit_user
end
def creator_home_props
has_sale = seller.sales.not_is_bundle_product_purchase.successful_or_preorder_authorization_successful.exists?
getting_started_stats = {
"customized_profile" => seller.name.present?,
"first_follower" => seller.followers.exists?,
"first_product" => seller.links.visible.exists?,
"first_sale" => has_sale,
"first_payout" => seller.has_payout_information?,
"first_email" => seller.installments.not_workflow_installment.send_emails.exists?,
"purchased_small_bets" => seller.purchased_small_bets?,
}
today = Time.now.in_time_zone(seller.timezone).to_date
analytics = CreatorAnalytics::CachingProxy.new(seller).data_for_dates(today - 30, today)
top_sales_data = analytics[:by_date][:sales]
.sort_by { |_, sales| -sales&.sum }.take(BALANCE_ITEMS_LIMIT)
# Preload products with thumbnail attachments to avoid N+1 queries
product_permalinks = top_sales_data.map(&:first)
products_by_permalink = seller.products
.where(unique_permalink: product_permalinks)
.includes(thumbnail_alive: { file_attachment: { blob: { variant_records: { image_attachment: :blob } } } })
.select(&:alive?)
.index_by(&:unique_permalink)
sales = top_sales_data.map do |p|
product = products_by_permalink[p[0]]
next unless product
{
"id" => product.unique_permalink,
"name" => product.name,
"thumbnail" => product.thumbnail_alive&.url,
"sales" => product.successful_sales_count,
"revenue" => product.total_usd_cents,
"visits" => product.number_of_views,
"today" => analytics[:by_date][:totals][product.unique_permalink]&.last || 0,
"last_7" => analytics[:by_date][:totals][product.unique_permalink]&.last(7)&.sum || 0,
"last_30" => analytics[:by_date][:totals][product.unique_permalink]&.sum || 0,
}
end.compact
balances = UserBalanceStatsService.new(user: seller).fetch[:overview]
stripe_verification_message = nil
if seller.stripe_account.present?
seller.user_compliance_info_requests.requested.each do |request|
if request.verification_error_message.present?
stripe_verification_message = request.verification_error_message
end
end
end
tax_center_enabled = Feature.active?(:tax_center, seller)
if tax_center_enabled
tax_forms = []
show_1099_download_notice = seller.user_tax_forms.for_year(Time.current.prev_year.year).exists?
else
tax_forms = (Time.current.year.downto(seller.created_at.year)).each_with_object({}) do |year, hash|
url = seller.eligible_for_1099?(year) ? seller.tax_form_1099_download_url(year: year) : nil
hash[year] = url if url.present?
end
show_1099_download_notice = tax_forms[Time.current.prev_year.year].present?
end
{
name: seller.alive_user_compliance_info&.first_name || "",
has_sale:,
getting_started_stats:,
balances: {
balance: formatted_dollar_amount(balances.fetch(:balance), with_currency: seller.should_be_shown_currencies_always?),
last_seven_days_sales_total: formatted_dollar_amount(balances.fetch(:last_seven_days_sales_total), with_currency: seller.should_be_shown_currencies_always?),
last_28_days_sales_total: formatted_dollar_amount(balances.fetch(:last_28_days_sales_total), with_currency: seller.should_be_shown_currencies_always?),
total: formatted_dollar_amount(balances.fetch(:sales_cents_total), with_currency: seller.should_be_shown_currencies_always?),
},
sales:,
activity_items:,
stripe_verification_message:,
tax_forms:,
show_1099_download_notice:,
tax_center_enabled: Feature.active?(:tax_center, seller)
}
end
private
def activity_items
items = followers_activity_items + sales_activity_items
items.sort_by { |item| item["timestamp"] }.last(ACTIVITY_ITEMS_LIMIT).reverse
end
# Returns an array for sales to be processed by the frontend.
# {
# "type" => String ("new_sale"),
# "timestamp" => String (iso8601 UTC, example: "2022-05-16T01:01:01Z"),
# "details" => {
# "price_cents" => Integer,
# "email" => String,
# "full_name" => Nullable String,
# "product_name" => String,
# "product_unique_permalink" => String,
# }
# }
def sales_activity_items
sales = seller.sales.successful.not_is_bundle_product_purchase.includes(:link).order(created_at: :desc).limit(ACTIVITY_ITEMS_LIMIT).load
sales.map do |sale|
{
"type" => "new_sale",
"timestamp" => sale.created_at.iso8601,
"details" => {
"price_cents" => sale.price_cents,
"email" => sale.email,
"full_name" => sale.full_name,
"product_name" => sale.link.name,
"product_unique_permalink" => sale.link.unique_permalink,
}
}
end
end
# Returns an array for followers activity to be processed by the frontend.
# {
# "type" => String (one of: "follower_added" | "follower_removed"),
# "timestamp" => String (iso8601 UTC, example: "2022-05-16T01:01:01Z"),
# "details" => {
# "email" => String,
# "name" => Nullable String,
# }
# }
def followers_activity_items
results = ConfirmedFollowerEvent.search(
query: { bool: { filter: [{ term: { followed_user_id: seller.id } }] } },
sort: [{ timestamp: { order: :desc } }],
size: ACTIVITY_ITEMS_LIMIT,
_source: [:name, :email, :timestamp, :follower_user_id],
).map { |result| result["_source"] }
# Collect followers' users in one DB query
followers_user_ids = results.map { |result| result["follower_user_id"] }.compact.uniq
followers_users_by_id = User.where(id: followers_user_ids).select(:id, :name, :timezone).index_by(&:id)
results.map do |result|
follower_user = followers_users_by_id[result["follower_user_id"]]
{
"type" => "follower_#{result["name"]}",
"timestamp" => result["timestamp"],
"details" => {
"email" => result["email"],
"name" => follower_user&.name,
}
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/subscriptions_presenter.rb | app/presenters/subscriptions_presenter.rb | # frozen_string_literal: true
class SubscriptionsPresenter
def initialize(subscription:)
@subscription = subscription
end
def magic_link_props
unique_emails = @subscription.emails.map do |source, email|
{ email: EmailRedactorService.redact(email), source: } unless email.nil?
end.compact.uniq { |email| email[:email] }
@react_component_props = {
subscription_id: @subscription.external_id,
is_installment_plan: @subscription.is_installment_plan,
user_emails: unique_emails,
product_name: @subscription.link.name
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/widget_presenter.rb | app/presenters/widget_presenter.rb | # frozen_string_literal: true
class WidgetPresenter
include Rails.application.routes.url_helpers
attr_reader :seller, :product
def initialize(seller:, product: nil)
@seller = seller
@product = product
end
def widget_props
{
display_product_select: user_signed_in? && product.blank?,
products: products.map { |product| product_props(product) },
affiliated_products: affiliated_products.map { |product| affiliated_product_props(product) },
default_product: product_props(default_product),
}
end
def products
@products ||= if user_signed_in?
seller.links.alive.order(created_at: :desc).presence || demo_products
else
demo_products
end
end
def affiliated_products
@affiliated_products ||= if user_signed_in?
seller.directly_affiliated_products
.select("name, custom_permalink, unique_permalink, affiliates.id AS affiliate_id")
.order("affiliates.created_at DESC")
else
Link.none
end
end
private
def demo_products
[Link.fetch("demo")].compact
end
def user_signed_in?
seller.present?
end
def default_product
@_default_product ||= product.presence || products.first
end
def product_props(product)
{
name: product.name,
script_base_url: non_affiliated_product_script_base_url,
url: product_url(product, host: product_link_base_url),
gumroad_domain_url: product_url(product, host: product_link_base_url(allow_custom_domain: false))
}
end
def affiliated_product_props(product)
referral_url = DirectAffiliate.new(id: product.affiliate_id).referral_url_for_product(product)
{
name: product.name,
script_base_url: affiliated_product_script_base_url,
url: referral_url,
gumroad_domain_url: referral_url
}
end
def product_url(product, host:)
if product.user == seller
short_link_url(product.general_permalink, host:)
else
# Demo product does not belong to user, don't use the user's subdomain or custom domain
product.long_url
end
end
def affiliated_product_script_base_url
UrlService.root_domain_with_protocol
end
def non_affiliated_product_script_base_url
UrlService.widget_script_base_url(seller:)
end
def product_link_base_url(allow_custom_domain: true)
UrlService.widget_product_link_base_url(seller:, allow_custom_domain:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/pagy_presenter.rb | app/presenters/pagy_presenter.rb | # frozen_string_literal: true
class PagyPresenter
attr_reader :pagy
def initialize(pagy)
@pagy = pagy
end
def props
{ pages: pagy.last, page: pagy.page }
end
def metadata
{
count: pagy.count,
items: pagy.limit,
page: pagy.page,
pages: pagy.pages,
prev: pagy.prev,
next: pagy.next,
last: pagy.last
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/paginated_comments_presenter.rb | app/presenters/paginated_comments_presenter.rb | # frozen_string_literal: true
require "pagy/extras/standalone"
class PaginatedCommentsPresenter
include Pagy::Backend
COMMENTS_PER_PAGE = 20
attr_reader :commentable, :pundit_user, :purchase, :options, :page
def initialize(pundit_user:, commentable:, purchase:, options: {})
@pundit_user = pundit_user
@commentable = commentable
@purchase = purchase
@options = options
@page = [options[:page].to_i, 1].max
end
def result
root_comments = commentable.comments.alive.order(:created_at).roots
pagination, paginated_root_comments = pagy(root_comments, limit: COMMENTS_PER_PAGE, url: "", page:)
comments = comments_with_descendants(paginated_root_comments).includes(:commentable, author: { avatar_attachment: :blob }).alive
comments_json = comments.map do |comment|
CommentPresenter.new(pundit_user:, comment:, purchase:).comment_component_props
end
{
comments: comments_json,
count: commentable.comments.alive.count,
pagination: PagyPresenter.new(pagination).metadata
}
end
private
def comments_with_descendants(comments)
comments.inject(Comment.none) do |scope, parent|
scope.or parent.subtree.order(:created_at).to_depth(Comment::MAX_ALLOWED_DEPTH)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/affiliates_presenter.rb | app/presenters/affiliates_presenter.rb | # frozen_string_literal: true
require "pagy/extras/standalone"
class AffiliatesPresenter
include Rails.application.routes.url_helpers
include Pagy::Backend
PER_PAGE = 100
def initialize(pundit_user, query: nil, page: nil, sort: nil, should_get_affiliate_requests: false)
@pundit_user = pundit_user
@seller = pundit_user.seller
@query = query.presence
@page = page
@sort = sort
@should_get_affiliate_requests = should_get_affiliate_requests
end
def index_props
pagination, direct_affiliates = pagy(fetch_direct_affiliates, page:, limit: PER_PAGE)
affiliates = direct_affiliates.map(&:as_json)
affiliate_requests = should_get_affiliate_requests ? fetch_affiliate_requests : []
{
affiliate_requests:,
affiliates:,
pagination: PagyPresenter.new(pagination).props,
allow_approve_all_requests: Feature.active?(:auto_approve_affiliates, seller),
affiliates_disabled_reason:,
}
end
def onboarding_props
{
creator_subdomain: seller.subdomain,
products: products_props,
disable_global_affiliate: seller.disable_global_affiliate?,
global_affiliate_percentage: seller.global_affiliate.affiliate_percentage,
affiliates_disabled_reason:,
}
end
def new_affiliate_props
products = products_props.map do |product|
product.merge(enabled: false, fee_percent: nil, referral_url: "", destination_url: nil)
end
{
products:,
affiliates_disabled_reason:,
}
end
def edit_affiliate_props(affiliate)
{
affiliate: affiliate.affiliate_info.merge(products: affiliate.products_data),
affiliates_disabled_reason:,
}
end
def self_service_affiliate_product_details
existing_self_service_affiliate_products = seller
.self_service_affiliate_products.includes(:product)
.each_with_object({}) do |product, hash|
hash[product.product_id] = existing_self_service_affiliate_product_details(product)
end
seller.links.alive.not_is_collab.each_with_object({}) do |product, hash|
product_details = existing_self_service_affiliate_products.fetch(product.id) { disabled_product_details(product) }
next if product.archived? && !product_details[:enabled]
hash[product.id] = product_details
end
end
private
attr_reader :pundit_user, :seller, :query, :page, :sort, :should_get_affiliate_requests
def affiliates_disabled_reason
seller.has_brazilian_stripe_connect_account? ? "Affiliates with Brazilian Stripe accounts are not supported." : nil
end
def products_props
self_service_affiliate_product_details.values.sort_by { |product| [product[:enabled] ? 0 : 1, product[:name]] }
end
def existing_self_service_affiliate_product_details(self_service_affiliate_product)
fee = self_service_affiliate_product.affiliate_basis_points / 100
{
enabled: self_service_affiliate_product.enabled,
id: self_service_affiliate_product.product.external_id_numeric,
name: self_service_affiliate_product.product.name,
fee_percent: fee.zero? ? nil : fee,
destination_url: self_service_affiliate_product.destination_url,
}
end
def disabled_product_details(product)
{
enabled: false,
id: product.external_id_numeric,
name: product.name,
fee_percent: nil,
destination_url: nil,
}
end
def fetch_direct_affiliates
affiliates = seller.direct_affiliates
.alive
.includes(:affiliate_user, :seller)
.sorted_by(**sort.to_h.symbolize_keys)
affiliates = affiliates.joins(:affiliate_user).where("users.username LIKE :query OR users.email LIKE :query OR users.name LIKE :query", query: "%#{query.strip}%") if query
affiliates
.left_outer_joins(:product_affiliates)
.group(:id)
.order("MAX(affiliates_links.updated_at) DESC")
end
def fetch_affiliate_requests
seller.
affiliate_requests.unattended_or_approved_but_awaiting_requester_to_sign_up.includes(:seller).
order(created_at: :desc, id: :desc).
map { _1.as_json(pundit_user:) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/installment_presenter.rb | app/presenters/installment_presenter.rb | # frozen_string_literal: true
class InstallmentPresenter
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::TextHelper
include ApplicationHelper
attr_reader :installment, :seller, :from_tab
def initialize(seller:, installment: nil, from_tab: nil)
@seller = seller
@installment = installment
@from_tab = from_tab
end
def props
attrs = {
name: installment.displayed_name,
message: installment.message,
files: installment.alive_product_files.map(&:as_json),
published_at: installment.published_at,
updated_at: installment.updated_at,
external_id: installment.external_id,
stream_only: installment.has_stream_only_files?,
call_to_action_text: installment.call_to_action_text,
call_to_action_url: installment.call_to_action_url,
streamable: installment.streamable?,
sent_count: installment.customer_count,
click_count: installment.unique_click_count,
open_count: installment.unique_open_count,
click_rate: installment.click_rate_percent&.round(1),
open_rate: installment.open_rate_percent&.round(1),
send_emails: installment.send_emails?,
shown_on_profile: installment.shown_on_profile?,
installment_type: installment.installment_type,
paid_more_than_cents: installment.paid_more_than_cents,
paid_less_than_cents: installment.paid_less_than_cents,
allow_comments: installment.allow_comments?,
display_type: installment.display_type,
}
attrs.merge!(installment.json_filters)
if installment.product_type? || installment.variant_type?
attrs[:unique_permalink] = installment.link.unique_permalink
attrs[:variant_external_id] = installment.base_variant.external_id if installment.variant_type?
end
if installment.workflow_id.present?
attrs.merge!(
published_once_already: installment.workflow_installment_published_once_already || installment.published?,
member_cancellation: installment.member_cancellation_trigger?,
new_customers_only: installment.is_for_new_customers_of_workflow,
delayed_delivery_time_duration: installment.installment_rule.displayable_time_duration,
delayed_delivery_time_period: installment.installment_rule.time_period,
displayed_delayed_delivery_time_period: installment.installment_rule.time_period.humanize.pluralize(installment.installment_rule.displayable_time_duration)
)
else
attrs.merge!(
clicked_urls: installment.clicked_urls.map do |(url, clicks_count)|
{
url: url == CreatorEmailClickEvent::VIEW_ATTACHMENTS_URL ? "View content" : url.truncate(70),
count: clicks_count
}
end,
view_count: installment.shown_on_profile? ? installment.installment_events_count : nil,
full_url: installment.full_url,
has_been_blasted: installment.has_been_blasted?,
shown_in_profile_sections: seller.seller_profile_posts_sections.filter_map { _1.external_id if _1.shown_posts.include?(installment.id) },
)
unless installment.published?
attrs[:recipient_description] = recipient_description
attrs[:to_be_published_at] = installment.installment_rule.to_be_published_at if installment.ready_to_publish?
end
end
attrs.except(:paid_more_than, :paid_less_than)
end
def new_page_props(copy_from: nil)
reference_installment = seller.installments.not_workflow_installment.alive.find_by_external_id(copy_from) if copy_from.present?
installment_props = self.class.new(seller:, installment: reference_installment).props.except(:external_id) if reference_installment.present?
{ context: installment_form_context_props, installment: installment_props }
end
def edit_page_props
{ context: installment_form_context_props, installment: props }
end
private
def recipient_description
if installment.seller_type?
"Your customers"
elsif installment.product_type?
"Customers of #{installment.link.name}"
elsif installment.variant_type?
"Customers of #{installment.link.name} - #{installment.base_variant.name}"
elsif installment.follower_type?
"Your followers"
elsif installment.audience_type?
"Your customers and followers"
elsif installment.is_affiliate_product_post?
"Affiliates of #{installment.affiliate_product_name}"
elsif installment.affiliate_type?
"Your affiliates"
end
end
def installment_form_context_props
user_presenter = UserPresenter.new(user: seller)
allow_comments_by_default = seller.installments.not_workflow_installment.order(:created_at).last&.allow_comments?
{
audience_types: user_presenter.audience_types,
products: user_presenter.products_for_filter_box.map do |product|
{
permalink: product.unique_permalink,
name: product.name,
archived: product.archived?,
variants: (product.is_physical? ? product.skus_alive_not_default : product.alive_variants).map { { id: _1.external_id, name: _1.name } }
}
end,
affiliate_products: user_presenter.affiliate_products_for_filter_box.map do |product|
{
permalink: product.unique_permalink,
name: product.name,
archived: product.archived?
}
end,
timezone: ActiveSupport::TimeZone[seller.timezone].now.strftime("%Z"),
currency_type: seller.currency_type.to_s,
countries: ([Compliance::Countries::USA.common_name] + Compliance::Countries.for_select.map(&:last)).uniq,
profile_sections: seller.seller_profile_posts_sections.map { { id: _1.external_id, name: _1.header } },
has_scheduled_emails: Installment.alive.not_workflow_installment.scheduled.where(seller:).exists?,
aws_access_key_id: AWS_ACCESS_KEY,
s3_url: s3_bucket_url,
user_id: seller.external_id,
allow_comments_by_default: allow_comments_by_default.nil? || allow_comments_by_default,
from_tab:
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/wishlist_presenter.rb | app/presenters/wishlist_presenter.rb | # frozen_string_literal: true
class WishlistPresenter
include Rails.application.routes.url_helpers
include Pagy::Backend
attr_reader :wishlist
PER_PAGE = 20
private_constant :PER_PAGE
def initialize(wishlist:)
@wishlist = wishlist
end
def self.library_props(wishlists:, is_wishlist_creator: true)
counts = wishlists.joins(:alive_wishlist_products).group("wishlists.id").count
wishlists.map do |wishlist|
new(wishlist:).library_props(product_count: counts[wishlist.id] || 0, is_wishlist_creator:)
end
end
def self.cards_props(wishlists:, pundit_user:, layout: nil, recommended_by: nil)
following_wishlists = pundit_user&.seller ? WishlistFollower.alive.where(follower_user: pundit_user.seller, wishlist_id: wishlists.map(&:id)).pluck(:wishlist_id) : []
wishlists.includes(ASSOCIATIONS_FOR_CARD).map do |wishlist|
new(wishlist:).card_props(pundit_user:, following: following_wishlists.include?(wishlist.id), layout:, recommended_by:)
end
end
def public_items(request:, pundit_user:, recommended_by: nil, page: 1)
paginated_public_items(request:, pundit_user:, recommended_by:, page:)
end
def library_props(product_count:, is_wishlist_creator: true)
{
id: wishlist.external_id,
name: wishlist.name,
url: wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol),
product_count:,
creator: is_wishlist_creator ? nil : {
name: wishlist.user.name_or_username,
profile_url: wishlist.user.profile_url,
avatar_url: wishlist.user.avatar_url
},
discover_opted_out: (wishlist.discover_opted_out? if is_wishlist_creator),
}
end
def listing_props(product: nil)
{
id: wishlist.external_id,
name: wishlist.name
}.merge(product ? selections_in_wishlist_props(product:) : {})
end
def public_props(request:, pundit_user:, recommended_by: nil, layout: nil, taxonomies_for_nav: nil)
items_with_pagination = paginated_public_items(request:, pundit_user:, recommended_by:, page: 1)
props = {
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: wishlist.user != pundit_user&.seller ? {
name: wishlist.user.name_or_username,
profile_url: wishlist.user.profile_url,
avatar_url: wishlist.user.avatar_url,
} : nil,
following: pundit_user&.seller ? wishlist.followed_by?(pundit_user.seller) : false,
can_follow: Feature.active?(:follow_wishlists, pundit_user&.seller) && pundit_user&.seller != wishlist.user,
can_edit: pundit_user&.user ? Pundit.policy!(pundit_user, wishlist).update? : false,
discover_opted_out: pundit_user&.user && Pundit.policy!(pundit_user, wishlist).update? ? wishlist.discover_opted_out? : nil,
checkout_enabled: wishlist.alive_wishlist_products.available_to_buy.any?,
}.merge(items_with_pagination)
props[:layout] = layout if layout.present?
if layout == Product::Layout::PROFILE
props[:creator_profile] = ProfilePresenter.new(pundit_user:, seller: wishlist.user).creator_profile
elsif layout == Product::Layout::DISCOVER && taxonomies_for_nav
props[:taxonomies_for_nav] = taxonomies_for_nav
end
props
end
ASSOCIATIONS_FOR_CARD = [
:user,
{
alive_wishlist_products: {
product: [:thumbnail_alive, :display_asset_previews]
}
}
].freeze
def card_props(pundit_user:, following:, layout: nil, recommended_by: nil)
thumbnails = wishlist.alive_wishlist_products.last(4).map { product_thumbnail(_1.product) }
thumbnails = [thumbnails.last].compact if thumbnails.size < 4
{
id: wishlist.external_id,
url: wishlist_url(wishlist.url_slug, host: wishlist.user.subdomain_with_protocol, layout:, recommended_by:),
name: wishlist.name,
description: wishlist.description,
seller: UserPresenter.new(user: wishlist.user).author_byline_props,
thumbnails:,
product_count: wishlist.alive_wishlist_products.size,
follower_count: wishlist.follower_count,
following:,
can_follow: Feature.active?(:follow_wishlists, pundit_user&.seller) && pundit_user&.seller != wishlist.user,
}
end
private
def paginated_public_items(request:, pundit_user:, recommended_by:, page:)
pagination, wishlist_products = pagy(wishlist.alive_wishlist_products, page:, limit: PER_PAGE)
paginated_products = wishlist_products
.includes(product: ProductPresenter::ASSOCIATIONS_FOR_CARD)
.map do |wishlist_product|
public_item_props(
wishlist_product:,
request:,
current_seller: pundit_user&.seller,
recommended_by:
)
end
{
items: paginated_products,
pagination: PagyPresenter.new(pagination).metadata,
}
end
def product_thumbnail(product)
{ url: product.thumbnail_or_cover_url, native_type: product.native_type }
end
def selections_in_wishlist_props(product:)
{
selections_in_wishlist: wishlist.alive_wishlist_products.filter_map do |wishlist_product|
if wishlist_product.product_id == product.id
{
variant_id: (ObfuscateIds.encrypt(wishlist_product.variant_id) if wishlist_product.variant_id),
recurrence: wishlist_product.recurrence,
rent: wishlist_product.rent,
quantity: wishlist_product.quantity
}
end
end
}
end
def public_item_props(wishlist_product:, request:, current_seller:, recommended_by:)
{
id: wishlist_product.external_id,
product: ProductPresenter.card_for_web(
product: wishlist_product.product,
request:,
recommended_by: recommended_by || RecommendationType::WISHLIST_RECOMMENDATION,
affiliate_id: wishlist.user.global_affiliate.external_id_numeric.to_s,
),
option: wishlist_product.variant&.to_option,
recurrence: wishlist_product.recurrence,
quantity: wishlist_product.quantity,
rent: wishlist_product.rent,
created_at: wishlist_product.created_at,
purchasable: wishlist_product.product.alive? && wishlist_product.product.published?,
giftable: wishlist_product.product.can_gift? && wishlist.user != current_seller,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/paginated_utm_links_presenter.rb | app/presenters/paginated_utm_links_presenter.rb | # frozen_string_literal: true
class PaginatedUtmLinksPresenter
include Pagy::Backend
PER_PAGE = 100
SORT_KEY_TO_COLUMN_MAP = {
"link" => "title",
"date" => "created_at",
"source" => "utm_source",
"medium" => "utm_medium",
"campaign" => "utm_campaign",
"clicks" => "unique_clicks",
"sales_count" => "sales_count",
"revenue_cents" => "revenue_cents",
"conversion_rate" => "conversion_rate",
}.freeze
private_constant :PER_PAGE, :SORT_KEY_TO_COLUMN_MAP
def initialize(seller:, query: nil, page: nil, sort: nil)
@seller = seller
@query = query&.strip.presence
@page = [page.to_i, 1].max
sort = sort.presence || {}
@sort_key = SORT_KEY_TO_COLUMN_MAP[sort[:key]] || SORT_KEY_TO_COLUMN_MAP["date"]
@sort_direction = sort[:direction].to_s.downcase == "asc" ? "asc" : "desc"
end
def props
if sort_key.in? SORT_KEY_TO_COLUMN_MAP.values_at("sales_count", "revenue_cents", "conversion_rate")
base_scope = seller.utm_links.alive
.select(%(
utm_links.*,
COUNT(purchases.id) AS sales_count,
COALESCE(SUM(purchases.price_cents), 0) AS revenue_cents,
CASE
WHEN utm_links.unique_clicks > 0
THEN LEAST(CAST(COUNT(purchases.id) AS FLOAT) / utm_links.unique_clicks, 1)
ELSE 0
END AS conversion_rate
).squish)
.left_outer_joins(:successful_purchases)
.references(:purchases)
.group(:id)
scope = UtmLink.from("(#{base_scope.to_sql}) AS utm_links")
else
scope = seller.utm_links.alive
end
scope = scope.includes(:seller, target_resource: [:seller, :user])
if query
scope = scope.where(%(
title LIKE :query
OR utm_source LIKE :query
OR utm_medium LIKE :query
OR utm_campaign LIKE :query
OR utm_term LIKE :query
OR utm_content LIKE :query
).squish, query: "%#{query}%")
end
scope = scope.order(Arel.sql("#{sort_key} #{sort_direction}"))
pagination, links = pagy(scope, page:, limit: PER_PAGE, overflow: :last_page)
{
utm_links: links.map { UtmLinkPresenter.new(seller:, utm_link: _1).utm_link_props },
pagination: PagyPresenter.new(pagination).props
}
end
private
attr_reader :seller, :query, :page, :sort_key, :sort_direction
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/customers_presenter.rb | app/presenters/customers_presenter.rb | # frozen_string_literal: true
class CustomersPresenter
attr_reader :pundit_user, :customers, :pagination, :product, :count
def initialize(pundit_user:, customers: [], pagination: nil, product: nil, count: 0)
@pundit_user = pundit_user
@customers = customers
@pagination = pagination
@product = product
@count = count
end
def customers_props
{
pagination:,
product_id: product&.external_id,
customers: customers.map { CustomerPresenter.new(purchase: _1).customer(pundit_user:) },
count:,
products: UserPresenter.new(user: pundit_user.seller).products_for_filter_box.map do |product|
{
id: product.external_id,
name: product.name,
variants: (product.is_physical? ? product.skus_alive_not_default : product.variant_categories_alive.first&.alive_variants || []).map do |variant|
{ id: variant.external_id, name: variant.name || "" }
end,
}
end,
currency_type: pundit_user.seller.currency_type.to_s,
countries: Compliance::Countries.for_select.map(&:last),
can_ping: pundit_user.seller.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME).size > 0,
show_refund_fee_notice: pundit_user.seller.show_refund_fee_notice?,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/library_presenter.rb | app/presenters/library_presenter.rb | # frozen_string_literal: true
class LibraryPresenter
include Rails.application.routes.url_helpers
attr_reader :logged_in_user
def initialize(logged_in_user)
@logged_in_user = logged_in_user
end
def library_cards
purchases = logged_in_user.purchases
.for_library
.not_rental_expired
.not_is_deleted_by_buyer
.includes(
:subscription,
:url_redirect,
:variant_attributes,
:bundle_purchase,
link: {
display_asset_previews: { file_attachment: :blob },
thumbnail_alive: { file_attachment: :blob },
user: { avatar_attachment: :blob }
}
)
.find_each(batch_size: 3000, order: :desc) # required to avoid full table scans. See https://github.com/gumroad/web/pull/25970
.to_a
creators_infos = purchases.flat_map { |purchase| purchase.link.user }.uniq.group_by(&:id).transform_values(&:first)
creator_counts = purchases.uniq(&:link_id).filter(&:not_is_bundle_purchase).group_by(&:seller_id).map do |seller_id, item|
creator = creators_infos[seller_id]
{ id: creator.external_id, name: creator.name || creator.username || creator.external_id, count: item.size }
end.sort_by { |creator| creator[:count] }.reverse
bundles = purchases.filter_map do |purchase|
{ id: purchase.link.external_id, label: purchase.link.name } if purchase.is_bundle_purchase?
end.uniq { _1[:id] }
product_seller_data = {}
purchases = purchases.map do |purchase|
next if purchase.link.is_recurring_billing && !purchase.subscription.alive?
product = purchase.link
product_seller_data[product.user.id] ||= product.user.username && {
name: product.user.name || product.user.username,
profile_url: product.user.profile_url(recommended_by: "library"),
avatar_url: product.user.avatar_url
}
{
product: {
name: product.name,
creator_id: product.user.external_id,
creator: product_seller_data[product.user.id],
thumbnail_url: product.thumbnail_or_cover_url,
native_type: product.native_type,
updated_at: product.content_updated_at || product.created_at,
permalink: product.unique_permalink,
has_third_party_analytics: product.has_third_party_analytics?("receipt"),
},
purchase: {
id: purchase.external_id,
email: purchase.email,
is_archived: purchase.is_archived,
download_url: purchase.url_redirect&.download_page_url,
variants: purchase.variant_attributes&.map(&:name)&.join(", "),
bundle_id: purchase.bundle_purchase&.link&.external_id,
is_bundle_purchase: purchase.is_bundle_purchase?,
}
}
end.compact
return purchases, creator_counts, bundles
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/community_presenter.rb | app/presenters/community_presenter.rb | # frozen_string_literal: true
class CommunityPresenter
def initialize(community:, current_user:, extras: {})
@community = community
@current_user = current_user
@extras = extras
end
def props
{
id: community.external_id,
name: community.name,
thumbnail_url: community.thumbnail_url,
seller: {
id: community.seller.external_id,
name: community.seller.display_name,
avatar_url: community.seller.avatar_url,
},
last_read_community_chat_message_created_at:,
unread_count:,
}
end
private
attr_reader :community, :current_user, :extras
def last_read_community_chat_message_created_at
if extras.key?(:last_read_community_chat_message_created_at)
extras[:last_read_community_chat_message_created_at]
else
LastReadCommunityChatMessage.includes(:community_chat_message).find_by(user_id: current_user.id, community_id: community.id)&.community_chat_message&.created_at&.iso8601
end
end
def unread_count
if extras.key?(:unread_count)
extras[:unread_count]
else
LastReadCommunityChatMessage.unread_count_for(user_id: current_user.id, community_id: community.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/analytics_presenter.rb | app/presenters/analytics_presenter.rb | # frozen_string_literal: true
class AnalyticsPresenter
def initialize(seller:)
@seller = seller
end
def page_props
{
products: seller.products_for_creator_analytics.map { product_props(_1) },
country_codes: Compliance::Countries.mapping.invert,
state_names: STATES_SUPPORTED_BY_ANALYTICS.map { |state_code| Compliance::Countries::USA.subdivisions[state_code]&.name || "Other" }
}
end
private
attr_reader :seller
def product_props(product)
{ id: product.external_id, alive: product.alive?, unique_permalink: product.unique_permalink, name: product.name }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/user_presenter.rb | app/presenters/user_presenter.rb | # frozen_string_literal: true
class UserPresenter
include Rails.application.routes.url_helpers
attr_reader :user
def initialize(user:)
@user = user
end
def audience_count = user.audience_members.count
def audience_types
result = []
result << :customers if user.audience_members.where(customer: true).exists?
result << :followers if user.audience_members.where(follower: true).exists?
result << :affiliates if user.audience_members.where(affiliate: true).exists?
result
end
def products_for_filter_box
user.links.visible.includes(:alive_variants).reject do |product|
product.archived? && !product.has_successful_sales?
end
end
def affiliate_products_for_filter_box
user.links.visible.order("created_at DESC").reject do |product|
product.archived? && !product.has_successful_sales?
end
end
def as_current_seller
time_zone = ActiveSupport::TimeZone[user.timezone]
{
id: user.external_id,
email: user.email,
name: user.display_name(prefer_email_over_default_username: true),
subdomain: user.subdomain,
avatar_url: user.avatar_url,
is_buyer: user.is_buyer?,
time_zone: { name: time_zone.tzinfo.name, offset: time_zone.tzinfo.utc_offset },
has_published_products: user.products.alive.exists?,
is_name_invalid_for_email_delivery: user.is_name_invalid_for_email_delivery?,
}
end
def author_byline_props(custom_domain_url: nil, recommended_by: nil)
return if user.username.blank?
{
id: user.external_id,
name: user.name_or_username,
avatar_url: user.avatar_url,
profile_url: user.profile_url(custom_domain_url:, recommended_by:)
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/profile_sections_presenter.rb | app/presenters/profile_sections_presenter.rb | # frozen_string_literal: true
class ProfileSectionsPresenter
include SearchProducts
CACHE_KEY_PREFIX = "profile-sections"
# seller is the owner of the section
# pundit_user.seller is the selected seller for the logged-in user (pundit_user.user) - which may be different from seller
def initialize(seller:, query:)
@seller = seller
@query = query
end
def props(request:, pundit_user:, seller_custom_domain_url:)
sections = query.to_a
props = {
currency_code: pundit_user.user&.currency_type || Currency::USD,
show_ratings_filter: seller.links.alive.any?(&:display_product_reviews?),
creator_profile: ProfilePresenter.new(seller:, pundit_user:).creator_profile,
sections: cached_sections.map do |props|
section_props(sections.find { _1.external_id == props[:id] }, cached_props: props, request:, pundit_user:, seller_custom_domain_url:)
end
}
if pundit_user.seller == seller
props[:products] = seller.products.alive.not_archived.select(:id, :name).map { { id: ObfuscateIds.encrypt(_1.id), name: _1.name } }
props[:posts] = visible_posts
props[:wishlist_options] = seller.wishlists.alive.map { { id: _1.external_id, name: _1.name } }
end
props
end
def cached_sections
products_cache_key = seller.products.cache_key_with_version
sections_cache_key = query.cache_key_with_version
cache_key = "#{CACHE_KEY_PREFIX}_#{REVISION}-#{products_cache_key}-#{sections_cache_key}"
Rails.cache.fetch(cache_key, expires_in: 10.minutes) do
query.map do |section|
data = {
id: section.external_id,
header: section.hide_header? ? nil : section.header,
type: section.type,
}
case section
when SellerProfileProductsSection
data.merge!(
{
show_filters: section.show_filters,
default_product_sort: section.default_product_sort,
search_results: section_search_results(section),
}
)
when SellerProfileFeaturedProductSection
data.merge!({ featured_product_id: ObfuscateIds.encrypt(section.featured_product_id) }) if section.featured_product_id.present?
when SellerProfileRichTextSection
data.merge!({ text: section.text })
when SellerProfileSubscribeSection
data.merge!({ button_label: section.button_label })
when SellerProfileWishlistsSection
data.merge!({ shown_wishlists: section.shown_wishlists.map { ObfuscateIds.encrypt(_1) } })
end
data
end
end
end
private
attr_reader :seller, :query
def section_props(section, cached_props:, request:, pundit_user:, seller_custom_domain_url:)
is_owner = pundit_user.seller == seller
params = request.query_parameters
if is_owner
cached_props.merge!(
{
hide_header: section.hide_header?,
header: section.header || "",
}
)
end
case cached_props[:type]
when "SellerProfileProductsSection"
if is_owner
cached_props.merge!(
{
shown_products: section.shown_products.map { ObfuscateIds.encrypt(_1) },
add_new_products: section.add_new_products,
}
)
end
cached_props[:search_results] = section_search_results(section, params:) if params.present?
cached_props[:search_results][:products] = Link.includes(ProductPresenter::ASSOCIATIONS_FOR_CARD).find(cached_props[:search_results][:products]).map do |product|
ProductPresenter.card_for_web(product:, request:, recommended_by: params[:recommended_by], target: Product::Layout::PROFILE, show_seller: false, compute_description: false)
end
when "SellerProfilePostsSection"
if is_owner
cached_props.merge!({ shown_posts: visible_posts(section:).pluck(:id) })
else
cached_props[:posts] = visible_posts(section:)
end
when "SellerProfileFeaturedProductSection"
unless is_owner
cached_props.merge!(
{
props: cached_props[:featured_product_id].present? ?
ProductPresenter.new(product: seller.products.find_by_external_id(cached_props.delete(:featured_product_id)), pundit_user:, request:).product_props(seller_custom_domain_url:) :
nil,
}
)
end
when "SellerProfileWishlistsSection"
cached_props[:wishlists] = WishlistPresenter
.cards_props(wishlists: Wishlist.alive.where(id: section.shown_wishlists), pundit_user:, layout: Product::Layout::PROFILE)
.sort_by { |wishlist| cached_props[:shown_wishlists].index(wishlist[:id]) }
end
cached_props
end
def section_search_results(section, params: {})
search_results = search_products(
params.merge(
{
sort: params[:sort] || section.default_product_sort,
section:,
is_alive_on_profile: true,
user_id: seller.id,
}
)
)
search_results[:products] = search_results[:products].ids
search_results
end
def visible_posts(section: nil)
query = seller.installments.visible_on_profile
.order(published_at: :desc)
.page_with_kaminari(0)
.per(999)
query = query.where(id: section.shown_posts) if section
query.map do |post|
{
id: post.external_id,
name: post.name,
slug: post.slug,
published_at: post.published_at,
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/dispute_evidence_page_presenter.rb | app/presenters/dispute_evidence_page_presenter.rb | # frozen_string_literal: true
class DisputeEvidencePagePresenter
def initialize(dispute_evidence)
@dispute_evidence = dispute_evidence
@purchase = @dispute_evidence.disputable.purchase_for_dispute_evidence
@purchase_product_presenter = PurchaseProductPresenter.new(@purchase)
end
def react_props
{
dispute_evidence: dispute_evidence_props,
disputable: disputable_props,
products: products_props,
}
end
private
attr_reader :dispute_evidence, :purchase, :purchase_product_presenter
def dispute_evidence_props
{
dispute_reason: dispute_evidence.dispute.reason,
customer_email: dispute_evidence.customer_email,
purchased_at: dispute_evidence.purchased_at,
duration_left_to_submit_evidence_formatted:,
customer_communication_file_max_size: dispute_evidence.customer_communication_file_max_size,
blobs: blobs_props
}
end
def disputable_props
{
purchase_for_dispute_evidence_id: purchase.external_id,
formatted_display_price: dispute_evidence.disputable.formatted_disputed_amount,
is_subscription: purchase.subscription.present?
}
end
def products_props
dispute_evidence.disputable.disputed_purchases.map do |disputed_purchase|
{
name: disputed_purchase.link.name,
url: disputed_purchase.link.long_url,
}
end
end
def duration_left_to_submit_evidence_formatted
"#{dispute_evidence.hours_left_to_submit_evidence} hours"
end
def blobs_props
{
receipt_image: blob_props(dispute_evidence.receipt_image, "receipt_image"),
policy_image: blob_props(dispute_evidence.policy_image, "policy_image"),
customer_communication_file: blob_props(dispute_evidence.customer_communication_file, "customer_communication_file"),
}
end
def blob_props(blob, type)
return nil unless blob.attached?
{
byte_size: blob.byte_size,
filename: blob.filename.to_s,
key: blob.key,
signed_id: nil,
title: case type
when "receipt_image" then "Receipt"
when "policy_image" then "Refund policy"
when "customer_communication_file" then "Customer communication"
else type.humanize
end,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/purchase_product_presenter.rb | app/presenters/purchase_product_presenter.rb | # frozen_string_literal: true
# Used to generate the product page for a purchase (e.g. /purchases/:id/product)
# for fighting chargebacks
# Similar with app/presenters/product_presenter.rb
# Attempts to retrieve the product description, refund policy, and pricing, at the
# time of purchase, via versioning
#
class PurchaseProductPresenter
include Rails.application.routes.url_helpers
attr_reader :product, :purchase, :request
def initialize(purchase)
@purchase = purchase
@product = purchase.link.paper_trail.version_at(purchase.created_at) || purchase.link
end
def product_props
purchase_refund_policy = purchase.purchase_refund_policy
{
product: {
name: product.name,
seller: UserPresenter.new(user: product.user).author_byline_props,
covers: display_asset_previews.as_json,
main_cover_id: display_asset_previews.first&.guid,
thumbnail_url: product.thumbnail&.alive&.url,
quantity_remaining: product.remaining_for_sale_count,
currency_code: product.price_currency_type.downcase,
long_url: product.long_url,
is_sales_limited: product.max_purchase_count?,
price_cents: product.price_cents,
rental_price_cents: product.rental_price_cents,
pwyw: product.customizable_price ? { suggested_price_cents: product.suggested_price_cents } : nil,
ratings: product.display_product_reviews? ? product.rating_stats : nil,
is_legacy_subscription: product.is_legacy_subscription?,
is_tiered_membership: product.is_tiered_membership,
is_physical: product.is_physical,
custom_view_content_button_text: product.custom_view_content_button_text.presence,
custom_button_text_option: product.custom_button_text_option,
is_multiseat_license: product.is_tiered_membership && product.is_multiseat_license,
permalink: product.unique_permalink,
preorder: product.is_in_preorder_state ? { release_date: product.preorder_link.release_at } : nil,
description_html: product.html_safe_description,
is_compliance_blocked: false,
is_published: !product.draft && product.alive?,
duration_in_months: product.duration_in_months,
rental: product.rental,
is_stream_only: product.has_stream_only_files?,
is_quantity_enabled: product.quantity_enabled,
sales_count:,
free_trial: product.free_trial_enabled ? {
duration: {
unit: product.free_trial_duration_unit,
amount: product.free_trial_duration_amount
}
} : nil,
summary: product.custom_summary.presence,
attributes: product.custom_attributes.filter_map do |attr|
{ name: attr["name"], value: attr["value"] } if attr["name"].present? || attr["value"].present?
end + product.file_info_for_product_page.map { |k, v| { name: k.to_s, value: v } },
recurrences: product.recurrences,
options:,
analytics: product.analytics_data,
has_third_party_analytics: false,
ppp_details: nil,
can_edit: false,
refund_policy: purchase_refund_policy.present? ? {
title: purchase_refund_policy.title,
fine_print: purchase_refund_policy.fine_print.present? ? ActionController::Base.helpers.simple_format(purchase_refund_policy.fine_print) : nil,
updated_at: purchase_refund_policy.updated_at,
} : nil
},
discount_code: nil,
purchase: nil,
}
end
def display_asset_previews
product.display_asset_previews
.unscoped
.where(link_id: product.id)
.where("created_at < ?", purchase.created_at)
.where("deleted_at IS NULL OR deleted_at > ?", purchase.created_at)
.order(:position)
end
# Similar to Link#options, only that it builds the options that were available at the time of purchase
def options
product.skus_enabled ? sku_options : variant_category_options
end
def sales_count
return unless product.should_show_sales_count?
product.successful_sales_count
end
def sku_options
product.skus
.not_is_default_sku
.where("created_at < ?", purchase.created_at)
.where("deleted_at IS NULL OR deleted_at > ?", purchase.created_at)
.map(&:to_option_for_product)
end
def variant_category_options
first_variant_category = product.variant_categories.where("variant_categories.deleted_at IS NULL OR deleted_at > ?", purchase.created_at).first
return [] unless first_variant_category
first_variant_category.variants
.where("created_at < ?", purchase.created_at)
.where("deleted_at IS NULL OR deleted_at > ?", purchase.created_at)
.in_order
.map(&:to_option)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/workflows_presenter.rb | app/presenters/workflows_presenter.rb | # frozen_string_literal: true
class WorkflowsPresenter
def initialize(seller:)
@seller = seller
end
def workflows_props
{
workflows: seller.workflows.alive.order("created_at DESC").map do |workflow|
WorkflowPresenter.new(seller:, workflow:).workflow_props
end
}
end
private
attr_reader :seller
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/url_redirect_presenter.rb | app/presenters/url_redirect_presenter.rb | # frozen_string_literal: true
class UrlRedirectPresenter
include Rails.application.routes.url_helpers
include ProductsHelper
include ActionView::Helpers::TextHelper
CONTENT_UNAVAILABILITY_REASON_CODES = {
inactive_membership: "inactive_membership",
rental_expired: "rental_expired",
access_expired: "access_expired",
email_confirmation_required: "email_confirmation_required",
}.freeze
attr_reader :url_redirect, :logged_in_user, :product, :purchase, :installment
def initialize(url_redirect:, logged_in_user: nil)
@url_redirect = url_redirect
@logged_in_user = logged_in_user
@product = url_redirect.referenced_link
@purchase = url_redirect.purchase
@installment = url_redirect.installment
end
def download_attributes
files = url_redirect.alive_product_files.includes(:alive_subtitle_files).with_attached_thumbnail.in_order
folder_ids_with_files = files.map(&:folder_id).compact
product_folders = url_redirect.referenced_link&.product_folders&.where(id: folder_ids_with_files)&.in_order || []
commission = purchase&.commission
folders = product_folders.map do |folder|
{
type: "folder",
id: folder.external_id,
name: folder.name,
children: files.filter_map { |file| map_file(file) if file.folder_id === folder.id }
}
end
{
content_items: (folders || []) + files.filter_map { |file| map_file(file) if !file.external_folder_id } + (commission&.is_completed? ? commission.files.map { |file| map_commission_file(file) } : [])
}
end
def download_page_with_content_props(extra_props = {})
{
content: content_props,
product_has_third_party_analytics: purchase&.link&.has_third_party_analytics?("receipt"),
}.merge(download_page_layout_props).merge(extra_props)
end
def download_page_without_content_props(extra_props = {})
download_page_layout_props(email_confirmation_required: extra_props[:content_unavailability_reason_code] == CONTENT_UNAVAILABILITY_REASON_CODES[:email_confirmation_required]).merge(extra_props)
end
private
def download_page_layout_props(email_confirmation_required: false)
review = purchase&.original_product_review
call = purchase&.call
{
terms_page_url: HomePageLinkService.terms,
token: url_redirect.token,
redirect_id: url_redirect.external_id,
creator:,
installment: url_redirect.with_product_files.is_a?(Installment) ? {
name: installment.name,
} : nil,
purchase: purchase.present? ? {
id: purchase.external_id,
bundle_purchase_id: purchase.is_bundle_product_purchase? ? purchase.bundle_purchase.external_id : nil,
email: email_confirmation_required ? nil : purchase.email,
email_digest: purchase.email_digest,
created_at: purchase.created_at,
is_archived: purchase.is_archived,
product_permalink: purchase.link&.unique_permalink,
product_id: purchase.link&.external_id,
product_name: purchase.link&.name,
variant_id: url_redirect.with_product_files&.is_a?(BaseVariant) ? url_redirect.with_product_files.external_id : nil,
variant_name: purchase.variant_names&.join(", "),
product_long_url: purchase.link&.long_url,
allows_review: purchase.allows_review?,
disable_reviews_after_year: purchase.seller.disable_reviews_after_year?,
review: review.present? ? ProductReviewPresenter.new(review).review_form_props : nil,
membership: purchase.subscription.present? ? {
has_active_subscription: purchase.has_active_subscription?,
subscription_id: purchase.subscription.external_id,
is_subscription_ended: purchase.subscription.ended?,
is_installment_plan_completed: purchase.subscription.is_installment_plan? && purchase.subscription.charges_completed?,
is_subscription_cancelled_or_failed: purchase.subscription.cancelled_or_failed?,
is_alive_or_restartable: purchase.subscription.alive_or_restartable?,
in_free_trial: purchase.subscription.in_free_trial?,
is_installment_plan: purchase.subscription.is_installment_plan,
} : nil,
purchase_custom_fields: purchase.purchase_custom_fields.is_post_purchase.with_attached_files.where.not(custom_field_id: nil).map do |purchase_custom_field|
field_data = {
custom_field_id: ObfuscateIds.encrypt(purchase_custom_field.custom_field_id),
type: CustomField::FIELD_TYPE_TO_NODE_TYPE_MAPPING[purchase_custom_field.field_type],
}
if purchase_custom_field.field_type == CustomField::TYPE_FILE
field_data[:files] = purchase_custom_field.files.map do |file|
{
name: File.basename(file.filename.to_s, ".*"),
size: file.byte_size,
extension: File.extname(file.filename.to_s).delete(".").upcase,
}
end
else
field_data[:value] = purchase_custom_field.value
end
field_data
end,
call: call.present? ? {
start_time: call.start_time,
end_time: call.end_time,
url: call.call_url.presence,
} : nil,
} : nil,
}
end
def content_props
product_files = url_redirect.alive_product_files.in_order
rich_content_pages = url_redirect.rich_content_json.presence
{
license:,
content_items: download_attributes[:content_items],
rich_content_pages:,
posts: posts(rich_content_pages),
video_transcoding_info:,
custom_receipt: nil,
discord: purchase.present? && DiscordIntegration.is_enabled_for(purchase) ? {
connected: DiscordIntegration.discord_user_id_for(purchase).present?
} : nil,
community_chat_url:,
ios_app_url: IOS_APP_STORE_URL,
android_app_url: ANDROID_APP_STORE_URL,
download_all_button: product_files.any? && url_redirect.with_product_files&.is_a?(Installment) && url_redirect.with_product_files&.is_downloadable? && url_redirect.entity_archive ? {
files: JSON.parse(url_redirect.product_files_hash),
} : nil,
}
end
def posts(rich_content_pages)
return [] if rich_content_pages.present? && !url_redirect.has_embedded_posts?
purchase_ids = if purchase && product
# If the user has bought this product before/after this specific purchase, show those posts too.
product.sales.for_displaying_installments(email: purchase.email).ids
elsif purchase
[purchase.id]
end
purchases = Purchase.where(id: purchase_ids)
Purchase.product_installments(purchase_ids:).map do |post|
post_purchase = purchases.find { |record| record.link_id == post.link_id } || purchase
return unless post_purchase.present?
seller_domain = if post.user.custom_domain&.active?
post.user.custom_domain.domain
else
post.user.subdomain
end
view_url_payload = {
username: post.user.username.presence || post.user.external_id,
slug: post.slug,
purchase_id: post_purchase.external_id,
host: seller_domain,
protocol: PROTOCOL
}
view_url = if seller_domain
custom_domain_view_post_url(view_url_payload)
else
view_url_payload[:host] = UrlService.domain_with_protocol
view_post_url(view_url_payload)
end
{
id: post.external_id,
name: post.displayed_name,
action_at: post.action_at_for_purchases(purchase_ids),
view_url:
}
end.compact
end
def license
license_key = purchase&.license_key || url_redirect.imported_customer&.license_key
return unless license_key
{
license_key:,
is_multiseat_license: purchase&.is_multiseat_license,
seats: purchase&.quantity
}
end
def map_file(file)
{
type: "file",
file_name: file.name_displayable,
description: file.description,
extension: file.display_extension,
file_size: file.size,
pagelength: (file.epub? ? nil : file.pagelength),
duration: file.duration,
id: file.external_id,
download_url: url_redirect.is_file_downloadable?(file) ? url_redirect_download_product_files_path(url_redirect.token, { product_file_ids: [file.external_id] }) : nil,
stream_url: file.streamable? ? url_redirect_stream_page_for_product_file_path(url_redirect.token, file.external_id) : nil,
kindle_data: file.can_send_to_kindle? ?
{ email: logged_in_user&.kindle_email, icon_url: ActionController::Base.helpers.asset_path("white-15.png") } :
nil,
latest_media_location: media_locations_by_file[file.id].as_json,
content_length: file.content_length,
isbn: file.isbn,
read_url: file.readable? ? (
file.is_a?(Link) ? url_redirect_read_url(url_redirect.token) : file.is_a?(ProductFile) ? url_redirect_read_for_product_file_path(url_redirect.token, file.external_id) : nil
) : nil,
external_link_url: file.external_link? ? file.url : nil,
subtitle_files: file.alive_subtitle_files.map do |subtitle_file|
{
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_filename, is_video: true)
}
end,
pdf_stamp_enabled: file.pdf_stamp_enabled?,
processing: file.pdf_stamp_enabled? && url_redirect.alive_stamped_pdfs.find_by(product_file_id: file.id).blank?,
thumbnail_url: file.thumbnail_url
}
end
def video_transcoding_info
return unless url_redirect.rich_content_json.present?
return unless url_redirect.alive_product_files.any?(&:streamable?)
return unless logged_in_user == url_redirect.seller && !url_redirect.with_product_files.has_been_transcoded?
{ transcode_on_first_sale: product&.transcode_videos_on_purchase.present? }
end
def creator
user = product&.user || installment&.seller
user&.name || user&.username ? {
name: user.name.presence || user.username,
profile_url: user.profile_url(recommended_by: "library"),
avatar_url: user.avatar_url
} : nil
end
def media_locations_by_file
@_media_locations_by_file ||= purchase.present? ? MediaLocation.max_consumed_at_by_file(purchase_id: purchase.id).index_by(&:product_file_id) : {}
end
def map_commission_file(file)
{
type: "file",
file_name: File.basename(file.filename.to_s, ".*"),
description: nil,
extension: File.extname(file.filename.to_s).delete(".").upcase,
file_size: file.byte_size,
pagelength: nil,
duration: nil,
id: file.signed_id,
download_url: file.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
def community_chat_url
return unless purchase.present? && Feature.active?(:communities, purchase.seller) && product.community_chat_enabled? && product.active_community.present?
path = community_path(purchase.seller.external_id, product.active_community.external_id)
return signup_path(email: purchase.email, next: path) if purchase.purchaser_id.blank?
logged_in_user.present? ? path : login_path(email: purchase.email, next: path)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/receipt_presenter.rb | app/presenters/receipt_presenter.rb | # frozen_string_literal: true
class ReceiptPresenter
attr_reader :for_email
# chargeable is either a Purchase or a Charge
def initialize(chargeable, for_email:)
@for_email = for_email
@chargeable = chargeable
end
def charge_info
@_charge_info ||= ReceiptPresenter::ChargeInfo.new(
chargeable,
for_email:,
order_items_count: chargeable.unbundled_purchases.count
)
end
def payment_info
@_payment_info ||= ReceiptPresenter::PaymentInfo.new(chargeable)
end
def shipping_info
@_shipping_info ||= ReceiptPresenter::ShippingInfo.new(chargeable)
end
def items_infos
chargeable.unbundled_purchases.map do |purchase_item|
ReceiptPresenter::ItemInfo.new(purchase_item)
end
end
def recommended_products_info
@_recommended_products_info ||= ReceiptPresenter::RecommendedProductsInfo.new(chargeable)
end
def mail_subject
@_mail_subject ||= ReceiptPresenter::MailSubject.build(chargeable)
end
def footer_info
@_footer_info ||= ReceiptPresenter::FooterInfo.new(chargeable)
end
def giftee_manage_subscription
@_giftee_manage_subscription ||= ReceiptPresenter::GifteeManageSubscription.new(chargeable)
end
private
attr_reader :chargeable
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/comment_presenter.rb | app/presenters/comment_presenter.rb | # frozen_string_literal: true
class CommentPresenter
include UsersHelper
include ActionView::Helpers::DateHelper
attr_reader :comment, :pundit_user, :purchase
delegate :author, to: :comment, allow_nil: true
def initialize(pundit_user:, comment:, purchase:)
@pundit_user = pundit_user
@comment = comment
@purchase = purchase
end
def comment_component_props
{
id: comment.external_id,
parent_id: comment.parent_id.presence && ObfuscateIds.encrypt(comment.parent_id),
author_id: author&.external_id,
author_name: author&.display_name || comment.author_name.presence,
author_avatar_url: author&.avatar_url || ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"),
purchase_id: comment.purchase&.external_id,
content: {
original: comment.content,
formatted: Rinku.auto_link(CGI.escapeHTML(comment.content), :all, %(target="_blank" rel="noopener noreferrer nofollow")),
},
depth: comment.depth,
created_at: comment.created_at.iso8601,
created_at_humanized: "#{time_ago_in_words(comment.created_at)} ago",
is_editable: Pundit.policy!(pundit_user, comment_context).update?,
is_deletable: Pundit.policy!(pundit_user, comment_context).destroy?
}
end
private
def comment_context
@_comment_context ||= CommentContext.new(
comment: @comment,
commentable: nil,
purchase: @purchase
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/affiliated_products_presenter.rb | app/presenters/affiliated_products_presenter.rb | # frozen_string_literal: true
require "pagy/extras/standalone"
require "pagy/extras/arel"
class AffiliatedProductsPresenter
include Pagy::Backend
PER_PAGE = 20
def initialize(user, query: nil, page: nil, sort: nil)
@user = user
@query = query.presence
@page = page
@sort = sort
end
def affiliated_products_page_props
{
**affiliated_products_data,
stats:,
global_affiliates_data:,
discover_url: UrlService.discover_domain_with_protocol,
archived_tab_visible: @user.archived_products_count > 0,
affiliates_disabled_reason: @user.has_brazilian_stripe_connect_account? ? "Affiliates with Brazilian Stripe accounts are not supported." : nil,
}
end
private
attr_reader :user, :query, :page, :sort
def affiliated_products_data
pagination, records = pagy_arel(affiliated_products, page:, limit: PER_PAGE)
records = records.map do |product|
revenue = product.revenue || 0
{
product_name: product.name,
url: product.affiliate_type.constantize.new(id: product.affiliate_id).referral_url_for_product(product),
fee_percentage: product.basis_points / 100,
revenue:,
humanized_revenue: MoneyFormatter.format(revenue, :usd, no_cents_if_whole: true, symbol: true),
sales_count: product.sales_count,
affiliate_type: product.affiliate_type.underscore
}
end
{ pagination: PagyPresenter.new(pagination).props, affiliated_products: records }
end
def stats
{
total_revenue: user.affiliate_credits_sum_total,
total_sales: user.affiliate_credits.count,
total_products: affiliated_products.map(&:link_id).uniq.size,
total_affiliated_creators: user.affiliated_creators.count,
}
end
def global_affiliates_data
{
global_affiliate_id: user.global_affiliate.external_id_numeric,
global_affiliate_sales: user.global_affiliate.total_cents_earned_formatted,
cookie_expiry_days: GlobalAffiliate::AFFILIATE_COOKIE_LIFETIME_DAYS,
affiliate_query_param: Affiliate::SHORT_QUERY_PARAM,
}
end
def affiliated_products
return @_affiliated_products if defined?(@_affiliated_products)
select_columns = %{
affiliates_links.link_id AS link_id,
affiliates_links.affiliate_id AS affiliate_id,
links.unique_permalink AS unique_permalink,
links.name AS name,
affiliates.type AS affiliate_type,
COALESCE(affiliates_links.affiliate_basis_points, affiliates.affiliate_basis_points) AS basis_points,
SUM(affiliate_credits.amount_cents) AS revenue,
COUNT(DISTINCT affiliate_credits.id) AS sales_count
}
group_by = %{
affiliates_links.link_id,
affiliates_links.affiliate_id,
links.unique_permalink,
links.name,
affiliates.type,
affiliates_links.affiliate_basis_points || affiliates.affiliate_basis_points
}
affiliate_credits_join = %{
LEFT OUTER JOIN affiliate_credits ON
affiliates_links.link_id = affiliate_credits.link_id AND
affiliate_credits.affiliate_id = affiliates_links.affiliate_id AND
affiliate_credits.affiliate_credit_chargeback_balance_id IS NULL AND
affiliate_credits.affiliate_credit_refund_balance_id IS NULL
}
sort_direction = sort&.dig(:direction)&.upcase == "DESC" ? "DESC" : "ASC"
order_by = case sort&.dig(:key)
when "product_name" then "links.name #{sort_direction}"
when "revenue" then "revenue #{sort_direction}"
when "sales_count" then "sales_count #{sort_direction}"
when "commission" then "basis_points #{sort_direction}"
else "affiliates.created_at ASC"
end
order_by += ", affiliates_links.id ASC"
@_affiliated_products = ProductAffiliate.
joins(affiliate_credits_join).
joins(:product).
joins(:affiliate).
where(affiliate_id: Affiliate.direct_or_global_affiliates.alive.where(affiliate_user_id: user.id).pluck(:id)).
where(links: { deleted_at: nil, banned_at: nil }).
select(select_columns).
group(group_by).
order(order_by)
@_affiliated_products = @_affiliated_products.where("links.name LIKE :query", query: "%#{query.strip}%") if query
@_affiliated_products
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/reviews_presenter.rb | app/presenters/reviews_presenter.rb | # frozen_string_literal: true
class ReviewsPresenter
attr_reader :user
def initialize(user)
@user = user
end
def reviews_props
{
reviews: user.product_reviews.includes(:editable_video).map do |review|
product = review.link
ProductReviewPresenter.new(review).review_form_props.merge(
id: review.external_id,
purchase_id: ObfuscateIds.encrypt(review.purchase_id),
purchase_email_digest: review.purchase.email_digest,
product: product_props(product),
)
end,
purchases: user.purchases.allowing_reviews_to_be_counted.where.missing(:product_review).order(created_at: :desc).filter_map do |purchase|
if !purchase.seller.disable_reviews_after_year? || purchase.created_at > 1.year.ago
product = purchase.link
{
id: purchase.external_id,
email_digest: purchase.email_digest,
product: product_props(product),
}
end
end
}
end
private
def product_props(product)
seller = product.user
{
name: product.name,
url: product.long_url(recommended_by: "library"),
permalink: product.unique_permalink,
thumbnail_url: product.thumbnail_alive&.url,
native_type: product.native_type,
seller: {
name: seller.display_name,
url: seller.profile_url,
},
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/mobile_tracking_presenter.rb | app/presenters/mobile_tracking_presenter.rb | # frozen_string_literal: true
class MobileTrackingPresenter
include UsersHelper
attr_reader :seller
def initialize(seller:)
@seller = seller
end
def product_props(product:)
{
enabled: is_third_party_analytics_enabled?(seller:, logged_in_seller: nil),
seller_id: seller.external_id,
analytics: product.analytics_data,
has_product_third_party_analytics: product.has_third_party_analytics?("product"),
has_receipt_third_party_analytics: product.has_third_party_analytics?("receipt"),
third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN,
permalink: product.unique_permalink,
name: product.name
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/collaborators_presenter.rb | app/presenters/collaborators_presenter.rb | # frozen_string_literal: true
class CollaboratorsPresenter
def initialize(seller:)
@seller = seller
end
def index_props
{
collaborators: seller.collaborators.alive.map do
CollaboratorPresenter.new(seller:, collaborator: _1).collaborator_props
end,
collaborators_disabled_reason:,
has_incoming_collaborators: seller.incoming_collaborators.alive.exists?,
}
end
private
attr_reader :seller
def collaborators_disabled_reason
seller.has_brazilian_stripe_connect_account? ? "Collaborators with Brazilian Stripe accounts are not supported." : nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/community_notification_setting_presenter.rb | app/presenters/community_notification_setting_presenter.rb | # frozen_string_literal: true
class CommunityNotificationSettingPresenter
def initialize(settings:)
@settings = settings
end
def props
{ recap_frequency: settings.recap_frequency }
end
private
attr_reader :settings
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/bundle_presenter.rb | app/presenters/bundle_presenter.rb | # frozen_string_literal: true
class BundlePresenter
include Rails.application.routes.url_helpers
attr_reader :bundle
def initialize(bundle:)
@bundle = bundle
end
def bundle_props
refund_policy = bundle.find_or_initialize_product_refund_policy
profile_sections = bundle.user.seller_profile_products_sections
collaborator = bundle.collaborator_for_display
{
bundle: {
name: bundle.name,
description: bundle.description || "",
custom_permalink: bundle.custom_permalink,
price_cents: bundle.price_cents,
customizable_price: !!bundle.customizable_price,
suggested_price_cents: bundle.suggested_price_cents,
**ProductPresenter::InstallmentPlanProps.new(product: bundle).props,
custom_button_text_option: bundle.custom_button_text_option,
custom_summary: bundle.custom_summary,
custom_attributes: bundle.custom_attributes,
max_purchase_count: bundle.max_purchase_count,
quantity_enabled: bundle.quantity_enabled,
should_show_sales_count: bundle.should_show_sales_count,
is_epublication: bundle.is_epublication?,
product_refund_policy_enabled: bundle.product_refund_policy_enabled?,
refund_policy: {
allowed_refund_periods_in_days: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.keys.map do
{
key: _1,
value: RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS[_1]
}
end,
max_refund_period_in_days: refund_policy.max_refund_period_in_days,
fine_print: refund_policy.fine_print,
fine_print_enabled: refund_policy.fine_print.present?,
title: refund_policy.title,
},
covers: bundle.display_asset_previews.as_json,
taxonomy_id: bundle.taxonomy_id&.to_s,
tags: bundle.tags.pluck(:name),
display_product_reviews: bundle.display_product_reviews,
is_adult: bundle.is_adult,
discover_fee_per_thousand: bundle.discover_fee_per_thousand,
section_ids: profile_sections.filter_map { |section| section.external_id if section.shown_products.include?(bundle.id) },
is_published: !bundle.draft && bundle.alive?,
products: bundle.bundle_products.alive.in_order.includes(:variant, product: ProductPresenter::ASSOCIATIONS_FOR_CARD).map { self.class.bundle_product(product: _1.product, quantity: _1.quantity, selected_variant_id: _1.variant&.external_id) },
collaborating_user: collaborator.present? ? UserPresenter.new(user: collaborator).author_byline_props : nil,
public_files: bundle.alive_public_files.attached.map { PublicFilePresenter.new(public_file: _1).props },
audio_previews_enabled: Feature.active?(:audio_previews, bundle.user),
},
id: bundle.external_id,
unique_permalink: bundle.unique_permalink,
currency_type: bundle.price_currency_type,
thumbnail: bundle.thumbnail&.alive&.as_json,
sales_count_for_inventory: bundle.sales_count_for_inventory,
ratings: bundle.rating_stats,
taxonomies: Discover::TaxonomyPresenter.new.taxonomies_for_nav,
profile_sections: profile_sections.map do |section|
{
id: section.external_id,
header: section.header || "",
product_names: section.product_names,
default: section.add_new_products,
}
end,
refund_policies: bundle.user
.product_refund_policies
.for_visible_and_not_archived_products
.where.not(product_id: bundle.id)
.order(updated_at: :desc)
.select("refund_policies.*", "links.name")
.as_json,
products_count: bundle.user.products.alive.not_archived.not_is_recurring_billing.not_is_bundle.not_call.count,
is_bundle: bundle.is_bundle?,
has_outdated_purchases: bundle.has_outdated_purchases,
seller_refund_policy_enabled: bundle.user.account_level_refund_policy_enabled?,
seller_refund_policy: {
title: bundle.user.refund_policy.title,
fine_print: bundle.user.refund_policy.fine_print,
},
}
end
def self.bundle_product(product:, quantity: 1, selected_variant_id: nil)
variants = product.variants_or_skus
ProductPresenter.card_for_web(product:).merge(
{
is_quantity_enabled: product.quantity_enabled,
quantity:,
price_cents: product.price_cents,
variants: variants.present? ? {
selected_id: selected_variant_id || variants.first.external_id,
list: variants.map do |variant|
{
id: variant.external_id,
name: variant.name,
description: variant.description || "",
price_difference: variant.price_difference_cents || 0,
}
end
} : nil,
}
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/collaborator_presenter.rb | app/presenters/collaborator_presenter.rb | # frozen_string_literal: true
class CollaboratorPresenter
def initialize(seller:, collaborator: nil)
@seller = seller
@collaborator = collaborator
end
def new_collaborator_props
{
products: all_products,
collaborators_disabled_reason: seller.has_brazilian_stripe_connect_account? ? "Collaborators with Brazilian Stripe accounts are not supported." : nil,
}
end
def collaborator_props
collaborator.as_json.merge(products:)
end
def edit_collaborator_props
collaborator&.as_json&.merge({
products: all_products,
collaborators_disabled_reason: seller.has_brazilian_stripe_connect_account? ? "Collaborators with Brazilian Stripe accounts are not supported." : nil,
})
end
private
attr_reader :seller, :collaborator
def products
collaborator&.product_affiliates&.includes(:product)&.map do |pa|
{
id: pa.product.external_id,
name: pa.product.name,
percent_commission: pa.affiliate_percentage,
}
end
end
def all_products
seller.products.includes(product_affiliates: :affiliate).visible_and_not_archived.map do |product|
product_affiliate = product.product_affiliates.find_by(affiliate: collaborator)
{
id: product.external_id,
name: product.name,
has_another_collaborator: product.has_another_collaborator?(collaborator:),
has_affiliates: product.direct_affiliates.alive.exists?,
published: product.published?,
enabled: product_affiliate.present?,
percent_commission: product_affiliate&.affiliate_percentage,
dont_show_as_co_creator: product_affiliate&.dont_show_as_co_creator || false,
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/invoice_presenter.rb | app/presenters/invoice_presenter.rb | # frozen_string_literal: true
class InvoicePresenter
def initialize(chargeable, address_fields: {}, additional_notes: nil, business_vat_id: nil)
@chargeable = chargeable
@address_fields = address_fields
@additional_notes = additional_notes
@business_vat_id = business_vat_id
end
def invoice_generation_props
form_info = InvoicePresenter::FormInfo.new(chargeable)
{
form_info: {
heading: form_info.heading,
display_vat_id: form_info.display_vat_id?,
vat_id_label: form_info.vat_id_label,
data: form_info.data
},
supplier_info: {
heading: supplier_info.heading,
attributes: supplier_info.attributes
},
seller_info: {
heading: seller_info.heading,
attributes: seller_info.attributes
},
order_info: {
heading: order_info.heading,
pdf_attributes: order_info.pdf_attributes,
form_attributes: order_info.form_attributes,
invoice_date_attribute: order_info.invoice_date_attribute
},
id: chargeable.external_id_for_invoice,
email: chargeable.orderable.email,
countries: Compliance::Countries.for_select.to_h,
}
end
def order_info
@_order_info ||= InvoicePresenter::OrderInfo.new(chargeable, address_fields:, additional_notes:, business_vat_id:)
end
def supplier_info
@_supplier_info ||= InvoicePresenter::SupplierInfo.new(chargeable)
end
def seller_info
@_seller_info ||= InvoicePresenter::SellerInfo.new(chargeable)
end
private
attr_reader :business_vat_id, :chargeable, :address_fields, :additional_notes
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/user_memberships_presenter.rb | app/presenters/user_memberships_presenter.rb | # frozen_string_literal: true
class UserMembershipsPresenter
class OwnerTeamMembershipRecordMissingError < StandardError; end
attr_reader :pundit_user
def initialize(pundit_user:)
@pundit_user = pundit_user
end
def props
user_memberships = pundit_user.user.user_memberships_not_deleted_and_ordered
validate_user_memberships!(user_memberships)
build_user_memberships_props(user_memberships, pundit_user.seller)
rescue OwnerTeamMembershipRecordMissingError
# All users that have access to another seller's account must have a TeamMembership record
# to their own occount of role `owner`
# Owner membership is missing and there is at least one non-owner team membership record present
# Allowing the user to switch to the other seller account will prevent switching back their own
# account
# It _should_ not happen. Notify rather than allowing that scenario
Bugsnag.notify("Missing owner team membership for user #{pundit_user.user.id}")
[]
end
private
def validate_user_memberships!(user_memberships)
raise OwnerTeamMembershipRecordMissingError if user_memberships.present? && user_memberships.none?(&:role_owner?)
end
def build_user_memberships_props(user_memberships, seller)
user_memberships.map { |team_membership| user_membership_props(team_membership, seller) }
end
def user_membership_props(team_membership, seller)
team_membership_seller = team_membership.seller
{
id: team_membership.external_id,
seller_name: team_membership_seller.display_name(prefer_email_over_default_username: true),
seller_avatar_url: team_membership_seller.avatar_url,
has_some_read_only_access: team_membership.role_not_owner? && team_membership.role_not_admin?,
is_selected: team_membership_seller == seller,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/post_presenter.rb | app/presenters/post_presenter.rb | # frozen_string_literal: true
class PostPresenter
include UsersHelper
RECENT_UPDATES_LIMIT = 5
delegate :link, :seller, :id, :message, to: :post, allow_nil: true
attr_reader :post, :purchase, :pundit_user, :purchase_id_param, :visible_posts
def initialize(pundit_user:, post:, purchase_id_param:)
@pundit_user = pundit_user
@post = post
@purchase_id_param = purchase_id_param
@visible_posts = seller.visible_posts_for(pundit_user:, shown_on_profile: false)
set_purchase
end
def post_component_props
{
creator_profile: ProfilePresenter.new(pundit_user:, seller:).creator_profile,
subject: post.subject,
slug: post.slug,
external_id: post.external_id,
purchase_id: purchase&.external_id,
published_at: post.published_at,
message: Rinku.auto_link(post.message, :all, 'target="_blank" rel="noopener noreferrer nofollow"'),
call_to_action: post.call_to_action_url.present? && post.call_to_action_text.present? ? { url: post.call_to_action_url, text: post.call_to_action_text } : nil,
download_url: post.download_url(purchase&.subscription, purchase),
has_posts_on_profile: seller.seller_profile_posts_sections.on_profile.any?,
recent_posts:,
paginated_comments:,
comments_max_allowed_depth: Comment::MAX_ALLOWED_DEPTH,
}
end
def snippet
TextScrubber.format(message).squish.first(150)
end
def social_image
@_social_image ||= Post::SocialImage.for(message)
end
def e404?
return false if seller == pundit_user.seller && post.workflow.present?
if purchase.present?
!post.eligible_purchase?(purchase)
else
visible_posts.exclude?(post)
end
end
private
def recent_posts
@recent_posts ||= visible_posts
.filter_by_product_id_if_present(link.try(:id))
.where.not(id:)
.order(published_at: :desc)
.page_with_kaminari(1)
.per(RECENT_UPDATES_LIMIT)
.filter_map do |post|
recent_post_data(post) if purchase.nil? || post.purchase_passes_filters(purchase)
end
end
def recent_post_data(recent_post)
{
name: recent_post.name,
slug: recent_post.slug,
published_at: recent_post.published_at,
truncated_description: recent_post.truncated_description,
purchase_id: recent_post.eligible_purchase_for_user(pundit_user.user)&.external_id
}
end
# for posts targeted to customers of specific products, we need to make sure access is authorized
# by seeking a purchase record with a purchase_id param or via the logged-in user's access to the purchase
def set_purchase
if purchase_id_param
@purchase = seller.sales
.all_success_states
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.find_by_external_id(purchase_id_param)
elsif pundit_user.user
@purchase = Purchase.where(purchaser_id: pundit_user.user.id, link_id: link.try(:id))
.successful
.not_chargedback_or_chargedback_reversed
.not_fully_refunded
.first
end
end
def paginated_comments
return unless post.allow_comments?
PaginatedCommentsPresenter.new(pundit_user:, commentable: post, purchase:).result
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/utm_links_stats_presenter.rb | app/presenters/utm_links_stats_presenter.rb | # frozen_string_literal: true
class UtmLinksStatsPresenter
def initialize(seller:, utm_link_ids:)
@seller = seller
@utm_link_ids = utm_link_ids
end
def props
utm_links = seller.utm_links.select(%(
utm_links.id,
COUNT(purchases.id) AS sales_count,
COALESCE(SUM(purchases.price_cents), 0) AS revenue_cents,
CASE
WHEN utm_links.unique_clicks > 0
THEN LEAST(CAST(COUNT(purchases.id) AS FLOAT) / utm_links.unique_clicks, 1)
ELSE 0
END AS conversion_rate
).squish)
.where(id: utm_link_ids)
.left_outer_joins(:successful_purchases)
.references(:purchases)
.group(:id)
utm_links.each_with_object({}) do |utm_link, acc|
acc[utm_link.external_id] = {
sales_count: utm_link.sales_count,
revenue_cents: utm_link.revenue_cents,
conversion_rate: utm_link.conversion_rate.round(4),
}
end
end
private
attr_reader :seller, :utm_link_ids
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings/team_presenter.rb | app/presenters/settings/team_presenter.rb | # frozen_string_literal: true
class Settings::TeamPresenter
attr_reader :pundit_user
TYPES = %w(owner membership invitation)
TYPES.each do |type|
self.const_set("TYPE_#{type.upcase}", type)
end
def initialize(pundit_user:)
@pundit_user = pundit_user
end
def member_infos
infos = [MemberInfo.build_owner_info(pundit_user.seller)]
infos += seller_memberships.map do |team_membership|
MemberInfo.build_membership_info(pundit_user:, team_membership:)
end
infos += invitations.map do |team_invitation|
MemberInfo.build_invitation_info(pundit_user:, team_invitation:)
end
infos
end
private
# Reject owner membership as not all sellers have this record (see User#create_owner_membership_if_needed!)
# Furthermore, owner membership cannot be altered, so it's safe to ignore it and build the info record
# manually for the owner (see MemberInfo.build_owner_info)
#
def seller_memberships
@seller_memberships ||= pundit_user.seller
.seller_memberships
.not_deleted
.order(created_at: :desc)
.to_a
.reject(&:role_owner?)
end
def invitations
@_invitations ||= pundit_user.seller
.team_invitations
.not_deleted
.order(created_at: :desc)
.to_a
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings/team_presenter/member_info.rb | app/presenters/settings/team_presenter/member_info.rb | # frozen_string_literal: true
class Settings::TeamPresenter::MemberInfo
TYPES = %w(owner membership invitation)
TYPES.each do |type|
self.const_set("TYPE_#{type.upcase}", type)
end
class << self
def build_membership_info(pundit_user:, team_membership:)
MembershipInfo.new(pundit_user:, team_membership:)
end
def build_owner_info(user)
OwnerInfo.new(user)
end
def build_invitation_info(pundit_user:, team_invitation:)
InvitationInfo.new(pundit_user:, team_invitation:)
end
end
private
# Record can be either a TeamMembership or a TeamInvitation
def build_remove_from_team_option(pundit_user, record)
record_user = record.is_a?(TeamInvitation) ? nil : record.user
return if record_user == pundit_user.user # Used by a TeamMembership record, we show the leave team option instead
return if !Pundit.policy!(pundit_user, [:settings, :team, record]).destroy?
{
id: "remove_from_team",
label: "Remove from team"
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings/team_presenter/member_info/invitation_info.rb | app/presenters/settings/team_presenter/member_info/invitation_info.rb | # frozen_string_literal: true
class Settings::TeamPresenter::MemberInfo::InvitationInfo < Settings::TeamPresenter::MemberInfo
attr_reader :pundit_user, :team_invitation
def initialize(pundit_user:, team_invitation:)
@pundit_user = pundit_user
@team_invitation = team_invitation
end
def to_hash
current_role = team_invitation.role
{
type: Settings::TeamPresenter::MemberInfo::TYPE_INVITATION,
id: team_invitation.external_id,
role: current_role,
name: "",
email: team_invitation.email,
avatar_url: ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png"),
is_expired: team_invitation.expired?,
options: build_options(current_role),
leave_team_option: nil
}
end
private
def build_options(current_role)
options = build_role_options(current_role)
options << build_resend_invitation(pundit_user, team_invitation)
options << build_remove_from_team_option(pundit_user, team_invitation)
options.compact
end
def build_role_options(current_role)
TeamInvitation::ROLES
.reject { |role| reject_role_option?(current_role, role) }
.map { |role| { id: role, label: role.capitalize } }
end
def reject_role_option?(current_role, role)
return false if current_role == role
!Pundit.policy!(pundit_user, [:settings, :team, team_invitation]).update?
end
def build_resend_invitation(pundit_user, team_invitation)
return unless Pundit.policy!(pundit_user, [:settings, :team, team_invitation]).resend_invitation?
{
id: "resend_invitation",
label: "Resend invitation"
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings/team_presenter/member_info/owner_info.rb | app/presenters/settings/team_presenter/member_info/owner_info.rb | # frozen_string_literal: true
class Settings::TeamPresenter::MemberInfo::OwnerInfo < Settings::TeamPresenter::MemberInfo
attr_reader :user
def initialize(user)
@user = user
end
def to_hash
role = TeamMembership::ROLE_OWNER
{
type: Settings::TeamPresenter::MemberInfo::TYPE_OWNER,
id: user.external_id,
role:,
name: user.display_name,
email: user.form_email,
avatar_url: user.avatar_url,
is_expired: false,
options: build_options(role),
leave_team_option: nil
}
end
private
def build_options(role)
[{ id: role, label: role.capitalize }]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/presenters/settings/team_presenter/member_info/membership_info.rb | app/presenters/settings/team_presenter/member_info/membership_info.rb | # frozen_string_literal: true
class Settings::TeamPresenter::MemberInfo::MembershipInfo < Settings::TeamPresenter::MemberInfo
attr_reader :pundit_user, :team_membership
def initialize(pundit_user:, team_membership:)
@pundit_user = pundit_user
@team_membership = team_membership
end
def to_hash
user = team_membership.user
role = team_membership.role
{
type: Settings::TeamPresenter::MemberInfo::TYPE_MEMBERSHIP,
id: team_membership.external_id,
role:,
name: user.display_name,
email: user.form_email,
avatar_url: user.avatar_url,
is_expired: false,
options: build_options(role),
leave_team_option: build_leave_team_option(pundit_user, team_membership)
}
end
private
def build_options(current_role)
options = build_role_options(current_role)
options << build_remove_from_team_option(pundit_user, team_membership)
options.compact
end
def build_role_options(current_role)
TeamMembership::ROLES
.excluding(TeamMembership::ROLE_OWNER)
.reject { |role| reject_role_option?(current_role, role) }
.map { |role| { id: role, label: role.capitalize } }
end
def reject_role_option?(current_role, role)
return false if current_role == role
!Pundit.policy!(pundit_user, [:settings, :team, team_membership]).update?
end
def build_leave_team_option(pundit_user, team_membership)
return unless (team_membership.user == pundit_user.user) && Pundit.policy!(pundit_user, [:settings, :team, team_membership]).destroy?
{
id: "leave_team",
label: "Leave team"
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.