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/modules/immutable.rb | app/modules/immutable.rb | # frozen_string_literal: true
# An immutable ActiveRecord.
# Any model this module is included into will be immutable, except for
# any fields specified using `attr_mutable`.
#
# If you need to change an Immutable you should call `dup_and_save` or `dup_and_save!`.
module Immutable
extend ActiveSupport::Concern
included do
include Deletable
extend ClassMethods
attr_mutable :deleted_at
attr_mutable :updated_at
before_update do
changed_attributes_not_excluded = changed - self.class.attr_mutable_attributes
raise RecordImmutable, changed_attributes_not_excluded if changed_attributes_not_excluded.present?
end
end
class_methods do
def attr_mutable_attributes
@attr_mutable_attributes ||= []
end
def attr_mutable(attribute)
attr_mutable_attributes << attribute.to_s
end
def perform_dup_and_save(record, block, raise_errors:)
new_record = record.dup
result = nil
ActiveRecord::Base.transaction do
block.call(new_record)
result = record.mark_deleted(validate: false)
raise ActiveRecord::Rollback unless result
result = raise_errors ? new_record.save! : new_record.save
raise ActiveRecord::Rollback unless result
end
[result, new_record]
end
end
def dup_and_save(&block)
self.class.perform_dup_and_save(self, block, raise_errors: false)
end
def dup_and_save!(&block)
self.class.perform_dup_and_save(self, block, raise_errors: true)
end
class RecordImmutable < RuntimeError
def initialize(attributes)
super("The record is immutable but the attributes #{attributes} were attempted to be changed, but are not excluded from this models immutability.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/s3_retrievable.rb | app/modules/s3_retrievable.rb | # frozen_string_literal: true
module S3Retrievable
extend ActiveSupport::Concern
GUID_LENGTH = 32
# Use the guid if it can be found, otherwise use self.url
# Assumes guid is a 32-character alphanumeric sequence preceding "/original/" in the url
def unique_url_identifier
identifier = s3_url.split("/original/").first
if identifier && identifier != s3_url
potential_guid = identifier.last(GUID_LENGTH)
identifier = potential_guid unless /[^A-Za-z0-9]/.match?(potential_guid)
end
identifier
end
def download_original(encoding: "ascii-8bit")
raise ArgumentError, "`##{__method__}` requires a block" unless block_given?
extname = File.extname(s3_url)
basename = Digest::MD5.hexdigest(File.basename(s3_url, extname))
tempfile = Tempfile.new([basename, extname], encoding:)
self.s3_object.download_file(tempfile.path)
tempfile.rewind
yield tempfile
rescue Aws::S3::Errors::NotFound => e
raise e.exception("Key = #{s3_key} -- #{self.class.name}.id = #{id}")
ensure
tempfile&.close!
end
class_methods do
def has_s3_fields(column)
scope :s3, -> { where("#{column} LIKE ?", "#{S3_BASE_URL}%") }
scope :with_s3_key, ->(key) { where("#{column} = ?", "#{S3_BASE_URL}#{key}") }
# Public: Returns the s3 key for the object by which the file can be retrieved from s3.
define_method(:s3_key) do
return unless s3?
s3_url.split("/")[4..-1].join("/")
end
define_method(:s3?) do
return false if s3_url.blank?
s3_url.starts_with?(S3_BASE_URL)
end
define_method(:s3_object) do
return unless s3?
Aws::S3::Resource.new.bucket(S3_BUCKET).object(s3_key)
end
define_method(:s3_filename) do
return unless s3?
splitted = send(column).split("/")
user_external_id = user.try(:external_id)
starting_index = 7
max_split_count = 8
if user_external_id && send(column) =~ %r{\A#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/\w+/#{user_external_id}/}
starting_index = 8
max_split_count = 9
end
splitted.count > max_split_count ? splitted[starting_index..-1].join("/") : splitted.last # to handle file names that have / in them.
end
define_method(:s3_url) do
send(column)
end
# sample.pdf -> .pdf
define_method(:s3_extension) do
return unless s3?
File.extname(s3_url)
end
# sample.pdf -> PDF
define_method(:s3_display_extension) do
return unless s3?
extension = s3_extension
extension.present? ? extension[1..-1].upcase : ""
end
# sample.pdf -> sample
define_method(:s3_display_name) do
return unless s3?
if s3_extension.length > 0
s3_filename[0...-s3_extension.length]
else
s3_filename
end
end
define_method(:s3_directory_uri) do
return unless s3?
s3_url.split("/")[4, 3].join("/") # i.e: "attachments/aefc7b6c0f6e14c27edc7a0313e4ee77/original"
end
define_method(:restore_deleted_s3_object!) do
return unless s3?
return if s3_object.exists?
bucket = Aws::S3::Resource.new(
region: AWS_DEFAULT_REGION,
credentials: Aws::Credentials.new(GlobalConfig.get("S3_DELETER_ACCESS_KEY_ID"), GlobalConfig.get("S3_DELETER_SECRET_ACCESS_KEY"))
).bucket(S3_BUCKET)
restored = false
bucket.object_versions(prefix: s3_key).each do |object_version|
next unless object_version.key == s3_key
next unless object_version.data.is_a?(Aws::S3::Types::DeleteMarkerEntry)
object_version.delete
restored = true
break
end
restored
end
# Some S3 keys have a different Unicode normalization form in the database than in S3 itself.
# The only way to know for sure is to try to load the object from S3.
# If it's missing for that key, we'll try finding it in the S3 directory,
# as it should be the only file here at that time.
define_method(:confirm_s3_key!) do
s3_object.load
rescue Aws::S3::Errors::NotFound
files = Aws::S3::Client.new.list_objects(bucket: S3_BUCKET, prefix: s3_directory_uri).first.contents
return if files.size != 1
new_url = S3_BASE_URL + files[0].key
update!(url: new_url)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/base_price/recurrence.rb | app/modules/base_price/recurrence.rb | # frozen_string_literal: true
module BasePrice::Recurrence
MONTHLY = "monthly"
QUARTERLY = "quarterly"
BIANNUALLY = "biannually"
YEARLY = "yearly"
EVERY_TWO_YEARS = "every_two_years"
DEFAULT_TIERED_MEMBERSHIP_RECURRENCE = MONTHLY
ALLOWED_RECURRENCES = [
MONTHLY,
QUARTERLY,
BIANNUALLY,
YEARLY,
EVERY_TWO_YEARS
].freeze
ALLOWED_INSTALLMENT_PLAN_RECURRENCES = [
MONTHLY,
].freeze
RECURRENCE_TO_NUMBER_OF_MONTHS = {
MONTHLY => 1,
QUARTERLY => 3,
BIANNUALLY => 6,
YEARLY => 12,
EVERY_TWO_YEARS => 24
}.freeze
RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS = {
MONTHLY => 1.day,
QUARTERLY => 7.days,
BIANNUALLY => 7.days,
YEARLY => 7.days,
EVERY_TWO_YEARS => 7.days
}.freeze
PERMITTED_PARAMS = ALLOWED_RECURRENCES.inject({}) do |c, recurrence|
# TODO: :product_edit_react cleanup
c.merge!(recurrence.to_sym => [:enabled, :price, :price_cents, :suggested_price, :suggested_price_cents])
end.freeze
def self.all
ALLOWED_RECURRENCES
end
def self.number_of_months_in_recurrence(recurrence)
RECURRENCE_TO_NUMBER_OF_MONTHS[recurrence]
end
def self.renewal_reminder_email_days(recurrence)
RECURRENCE_TO_RENEWAL_REMINDER_EMAIL_DAYS[recurrence]
end
def self.seconds_in_recurrence(recurrence)
number_of_months = BasePrice::Recurrence.number_of_months_in_recurrence(recurrence)
number_of_months.months
end
def recurrence_long_indicator(recurrence)
case recurrence
when BasePrice::Recurrence::MONTHLY
"a month"
when BasePrice::Recurrence::QUARTERLY
"every 3 months"
when BasePrice::Recurrence::BIANNUALLY
"every 6 months"
when BasePrice::Recurrence::YEARLY
"a year"
when BasePrice::Recurrence::EVERY_TWO_YEARS
"every 2 years"
end
end
def recurrence_short_indicator(recurrence)
case recurrence
when MONTHLY then "/ month"
when QUARTERLY then "/ 3 months"
when BIANNUALLY then "/ 6 months"
when YEARLY then "/ year"
when EVERY_TWO_YEARS then "/ 2 years"
end
end
def single_period_indicator(recurrence)
case recurrence
when "monthly" then "1-month"
when "yearly" then "1-year"
when "quarterly" then "3-month"
when "biannually" then "6-month"
when "every_two_years" then "2-year"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/base_price/shared.rb | app/modules/base_price/shared.rb | # frozen_string_literal: true
module BasePrice::Shared
def clean_price(price_string)
clean = price_string.to_s
unless single_unit_currency?
clean = clean.gsub(/[^-0-9.,]/, "") # allow commas for now
if clean.rindex(/,/) == clean.length - 3 # euro style!
clean = clean.delete(".") # remove euro 1000^x delimiters
clean = clean.tr(",", ".") # replace euro comma with decimal
end
end
clean = clean.gsub(/[^-0-9.]/, "") # remove commas
string_to_price_cents(price_currency_type.to_sym, clean)
end
def save_recurring_prices!(recurrence_price_values)
enabled_recurrences = recurrence_price_values.select { |_, attributes| attributes[:enabled].to_s == "true" }
enabled_recurrences.each do |recurrence, attributes|
price = attributes[:price]
# TODO: :product_edit_react cleanup
if price.blank? && attributes[:price_cents].blank?
errors.add(:base, "Please provide a price for all selected payment options.")
raise Link::LinkInvalid
end
# TODO: :product_edit_react cleanup
price_cents = attributes[:price_cents] || clean_price(price)
suggested_price = attributes[:suggested_price]
# TODO: :product_edit_react cleanup
suggested_price_cents = attributes[:suggested_price_cents] || (suggested_price.present? ? clean_price(suggested_price) : nil)
create_or_update_new_price!(
price_cents:,
suggested_price_cents:,
recurrence:,
is_rental: false
)
end
recurrences_to_delete = (BasePrice::Recurrence.all - enabled_recurrences.keys.map(&:to_s)).push(nil)
prices_to_delete = prices.alive.where(recurrence: recurrences_to_delete)
prices_to_delete.map(&:mark_deleted!)
enqueue_index_update_for(["price_cents", "available_price_cents"]) if prices_to_delete.any?
save!
end
def price_must_be_within_range
min_price = CURRENCY_CHOICES[price_currency_type]["min_price"]
prices_to_validate.compact.each do |price_cents_to_validate|
next if price_cents_to_validate == 0
if price_cents_to_validate < min_price
errors.add(:base, "Sorry, a product must be at least #{MoneyFormatter.format(min_price, price_currency_type.to_sym, no_cents_if_whole: true, symbol: true)}.")
elsif user.max_product_price && get_usd_cents(price_currency_type, price_cents_to_validate) > user.max_product_price
errors.add(:base, "Sorry, we don't support pricing products above $5,000.")
end
end
end
private
# Private: This method checks to see if a price with the passed in recurrence, currency, and rental/buy status exists.
# If so, it updates it with the additional properties. If not, it creates a new price.
#
# price_cents - The amount of the Price to be created
# recurrence - The recurrence of the price to be created. It could be nil for non-recurring-billing products.
# is_rental - Indicating if the newly created Price is for rentals.
# suggested_price_cents - The suggested amount to pay if pay-what-you-want is enabled. Can be nil if PWYW is not enabled.
#
def create_or_update_new_price!(price_cents:, recurrence:, is_rental:, suggested_price_cents: nil)
if is_rental && price_cents.nil?
errors.add(:base, "Please enter the rental price.")
raise ActiveRecord::RecordInvalid.new(self)
end
ActiveRecord::Base.transaction do
scoped_prices = is_rental ? prices.alive.is_rental : prices.alive.is_buy
scoped_prices = scoped_prices.where(currency: price_currency_type, recurrence:)
price = scoped_prices.last || scoped_prices.new
price.price_cents = price_cents
price.suggested_price_cents = suggested_price_cents
price.is_rental = is_rental
changed = price.changed?
begin
price.save!
rescue => e
errors.add(:base, price.errors.full_messages.to_sentence)
raise e
end
if changed
alive_prices.reset
enqueue_index_update_for(["price_cents", "available_price_cents"])
end
end
end
def prices_to_validate
prices.alive.where(currency: price_currency_type).pluck(:price_cents)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/colombia_bank_account/account_type.rb | app/modules/colombia_bank_account/account_type.rb | # frozen_string_literal: true
module ColombiaBankAccount::AccountType
CHECKING = "checking"
SAVINGS = "savings"
def self.all
[
CHECKING,
SAVINGS
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/review_stat.rb | app/modules/product/review_stat.rb | # frozen_string_literal: true
module Product::ReviewStat
delegate :average_rating, :rating_counts, :reviews_count, :rating_percentages, to: :review_stat_proxy
def rating_stats
{
count: reviews_count,
average: average_rating,
percentages: rating_percentages.values,
}
end
def update_review_stat_via_rating_change(old_rating, new_rating)
create_product_review_stat if product_review_stat.nil?
if old_rating.nil?
product_review_stat.update_with_added_rating(new_rating)
elsif new_rating.nil?
product_review_stat.update_with_removed_rating(old_rating)
else
product_review_stat.update_with_changed_rating(old_rating, new_rating)
end
enqueue_index_update_for_reviews
end
def update_review_stat_via_purchase_changes(purchase_changes, product_review:)
return if product_review.nil? || purchase_changes.blank?
purchase = product_review.purchase
purchase_is_valid = purchase.allows_review_to_be_counted?
old_purchase = Purchase.new(
purchase.attributes
.except(*Purchase.unused_attributes)
.merge(purchase_changes.stringify_keys.transform_values(&:first))
)
old_purchase_is_valid = old_purchase.allows_review_to_be_counted?
if old_purchase_is_valid && !purchase_is_valid
product_review_stat.update_with_removed_rating(product_review.rating)
product_review.mark_deleted! unless product_review.deleted?
enqueue_index_update_for_reviews
elsif !old_purchase_is_valid && purchase_is_valid && product_review_stat.present?
product_review_stat.update_with_added_rating(product_review.rating)
product_review.mark_undeleted! unless product_review.alive?
enqueue_index_update_for_reviews
end
end
# Admin methods. VERY slow for large sellers, so only use if necessary.
# For example, avoid: `Link.find_each(&:sync_review_stat)`
def sync_review_stat
data = generate_review_stat_attributes
if product_review_stat.nil? && data[:reviews_count] > 0
create_product_review_stat(data)
elsif !product_review_stat.nil?
product_review_stat.update!(data)
end
end
def generate_review_stat_attributes
data = { link_id: id }
valid_purchases = sales.allowing_reviews_to_be_counted
valid_reviews = product_reviews.joins(:purchase).merge(valid_purchases)
rating_counts = valid_reviews.group(:rating).count
reviews_count = rating_counts.values.sum
data[:reviews_count] = reviews_count
if reviews_count > 0
average_rating = (rating_counts.map { |rating, rating_count| rating * rating_count }.sum.to_f / reviews_count).round(1)
else
average_rating = 0
end
data[:average_rating] = average_rating
ProductReviewStat::RATING_COLUMN_MAP.each do |rating, column_name|
data[column_name] = rating_counts[rating] || 0
end
data
end
# /Admin methods.
private
def review_stat_proxy
product_review_stat || ProductReviewStat::TEMPLATE
end
def enqueue_index_update_for_reviews
enqueue_index_update_for(%w(average_rating reviews_count is_recommendable))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/prices.rb | app/modules/product/prices.rb | # frozen_string_literal: true
module Product::Prices
include BasePrice::Shared
# Public: Alias for default_price_cents in order to hide the price_cents column, which isn't used anymore in favor of the Price model.
def price_cents
default_price_cents
end
# Public: Returns a single price for the product that can be used in generic situations where rent vs. buy is not indicated.
def default_price_cents
rent_only? ? rental_price_cents : buy_price_cents
end
def buy_price_cents
# Do not query for the associated Price objects if the product isn't persisted yet since those will always return empty results.
# All products are created with a price_cents and this attribute should be read until the product is persisted, after which the
# associated Price(s) determine the product's price(s).
return read_attribute(:price_cents) unless persisted?
return default_price.price_cents if buyable? && default_price
nil
end
def rental_price_cents
return read_attribute(:rental_price_cents) unless persisted?
rentable? ? alive_prices.where(currency: price_currency_type).select(&:is_rental?).last&.price_cents : nil
end
def default_price
return alive_prices.where(currency: price_currency_type).select(&:is_rental?).last if rent_only?
relevant_prices = alive_prices.where(currency: price_currency_type).select(&:is_buy?)
relevant_prices = relevant_prices.select(&:is_default_recurrence?) if is_recurring_billing && subscription_duration.present?
relevant_prices.last
end
# Public: Sets the buy price of the product to price_cents. If the product is already persisted then it changes the Price(s) associated with the
# product to achieve that. If the product hasn't been persisted yet it simply sets the price_cents attribute and relies on associate_price to
# create and associated the proper Price(s) object. If the product is a tiered membership product, it does not create or update a new price since
# these prices are set on the variant.
def price_cents=(price_cents)
return super(price_cents) if !persisted? || is_tiered_membership
create_or_update_new_price!(price_cents:, recurrence: subscription_duration.try(:to_s), is_rental: false)
end
def rental_price_cents=(rental_price_cents)
return super(rental_price_cents) unless persisted?
create_or_update_new_price!(price_cents: rental_price_cents, recurrence: subscription_duration.try(:to_s), is_rental: true)
end
def set_customizable_price
return if is_tiered_membership
return unless default_price_cents == 0
return if variant_categories_alive.joins(:variants).merge(BaseVariant.alive).sum("base_variants.price_difference_cents") > 0
update_column(:customizable_price, true)
end
def price_range=(price)
return unless price
price_string = price.to_s
self.price_cents = clean_price(price_string)
write_customizable_price(price_string)
end
def rental_price_range=(rental_price_string)
self.rental_price_cents = rental_price_string.present? ? clean_price(rental_price_string) : nil
write_customizable_price(rental_price_string) if rent_only?
end
def suggested_price=(price)
self.suggested_price_cents = price.present? ? clean_price(price.to_s) : nil
end
def format_price(price)
price == "$0.99" ? "99¢" : price
end
def price_formatted
format_price(display_price)
end
def rental_price_formatted
format_price(rental_display_price)
end
def price_formatted_verbose
"#{price_formatted}#{show_customizable_price_indicator? ? '+' : ''}#{is_recurring_billing ? " #{recurrence_long_indicator(display_recurrence)}" : ''}"
end
def price_formatted_including_rental_verbose
return price_formatted_verbose unless buy_and_rent?
"#{rental_price_formatted}#{show_customizable_price_indicator? ? '+' : ''} / #{price_formatted}#{show_customizable_price_indicator? ? '+' : ''}"
end
def suggested_price_formatted
attrs = { no_cents_if_whole: true, symbol: false }
MoneyFormatter.format(suggested_price_cents, price_currency_type.to_sym, attrs)
end
def base_price_formatted_without_dollar_sign
display_price_for_price_cents(display_base_price_cents, symbol: false)
end
def price_formatted_without_dollar_sign
display_price(symbol: false)
end
def rental_price_formatted_without_dollar_sign
MoneyFormatter.format(rental_price_cents, price_currency_type.to_sym, no_cents_if_whole: true, symbol: false)
end
def currency_symbol
symbol_for(price_currency_type)
end
def currency
CURRENCY_CHOICES[price_currency_type]
end
def min_price_formatted
MoneyFormatter.format(currency["min_price"], price_currency_type.to_sym, no_cents_if_whole: true, symbol: true)
end
# used by links_controller and api/links_controller to validate the price of the product against all its offer codes
# if more routes open up to change product price, make sure to wrap in transaction and use this method
def validate_product_price_against_all_offer_codes?
all_alive_offer_codes = product_and_universal_offer_codes
all_alive_offer_codes.each do |offer_code|
price_after_code = default_price_cents - offer_code.amount_off(default_price_cents)
next if price_after_code <= 0 || price_after_code >= currency["min_price"]
errors.add(:base, "An existing discount code puts the price of this product below the #{min_price_formatted} minimum after discount.")
return false
end
true
end
def suggested_price_greater_than_price
return if suggested_price_cents.blank? || !customizable_price || suggested_price_cents >= default_price_cents
errors.add(:base, "The suggested price you entered was too low.")
end
def write_customizable_price(price_string)
return if is_tiered_membership
price_customizable = price_string[-1, 1] == "+" || price_cents == 0
self.customizable_price = price_customizable
end
def display_base_price_cents
is_tiered_membership ? (lowest_tier_price.price_cents || 0) : default_price_cents
end
def display_price_cents(for_default_duration: false)
if is_tiered_membership?
lowest_tier_price(for_default_duration:).price_cents || 0
else
default_price_cents + (lowest_variant_price_difference_cents || 0)
end
end
def display_price(additional_attrs = {})
display_price_for_price_cents(display_price_cents, additional_attrs)
end
def rental_display_price(additional_attrs = {})
display_price_for_price_cents(rental_price_cents, additional_attrs)
end
def display_price_for_price_cents(price_cents, additional_attrs = {})
attrs = { no_cents_if_whole: true, symbol: true }.merge(additional_attrs)
MoneyFormatter.format(price_cents, price_currency_type.to_sym, attrs)
end
def price_for_recurrence(recurrence)
prices.alive.is_buy.where(recurrence:).last
end
def price_cents_for_recurrence(recurrence)
price_for_recurrence(recurrence).try(:price_cents)
end
def price_formatted_without_dollar_sign_for_recurrence(recurrence)
price_cents = price_cents_for_recurrence(recurrence)
return "" if price_cents.blank?
display_price_for_price_cents(price_cents, symbol: false)
end
def has_price_for_recurrence?(recurrence)
price_for_recurrence(recurrence).present?
end
def suggested_price_formatted_without_dollar_sign_for_recurrence(recurrence)
suggested_price_cents = suggested_price_cents_for_recurrence(recurrence)
return nil if suggested_price_cents.blank?
display_price_for_price_cents(suggested_price_cents, symbol: false)
end
def save_subscription_prices_and_duration!(recurrence_price_values:, subscription_duration:)
ActiveRecord::Base.transaction do
self.subscription_duration = subscription_duration
enabled_recurrences = recurrence_price_values.select { |_, attributes| attributes[:enabled].to_s == "true" }
unless subscription_duration.to_s.in?(enabled_recurrences)
errors.add(:base, "Please provide a price for the default payment option.")
raise Link::LinkInvalid
end
save_recurring_prices!(recurrence_price_values)
end
end
def has_multiple_recurrences?
return false unless is_recurring_billing
prices.alive.is_buy.select(:recurrence).distinct.count > 1
end
def available_price_cents
available_prices =
if is_tiered_membership?
VariantPrice.where(variant_id: tiers.pluck(:id)).alive.is_buy.pluck(:price_cents)
elsif current_base_variants.present?
base_price = default_price_cents
current_base_variants.pluck(:price_difference_cents).map { |difference| base_price + difference.to_i }
else
prices.alive.is_buy.pluck(:price_cents)
end
available_prices.uniq
end
private
# Private: Called only on create to instantiate Price object(s) and associate it to the newly created product.
def associate_price
# for tiered memberships, price is set at the tier level
return if is_tiered_membership
price_cents = read_attribute(:price_cents)
if price_cents.blank?
errors.add(:base, "New products should be created with a price_cents")
raise Link::LinkInvalid
end
price = Price.new
price.price_cents = price_cents
price.recurrence = subscription_duration.try(:to_s)
price.currency = price_currency_type
prices << price
return unless rentable?
rental_price_cents = read_attribute(:rental_price_cents)
rental_price = Price.new
rental_price.price_cents = rental_price_cents
rental_price.currency = price_currency_type
rental_price.is_rental = true
prices << rental_price
end
def delete_unused_prices
if buy_only?
prices.alive.is_rental.each(&:mark_deleted!)
elsif rent_only?
prices.alive.is_buy.each(&:mark_deleted!)
end
end
def suggested_price_cents_for_recurrence(recurrence)
suggested_price_cents = price_cents_for_recurrence(recurrence)
return suggested_price_cents if suggested_price_cents.present?
default_price = self.default_price
return nil if default_price.blank?
number_of_months_in_default_price_recurrence = BasePrice::Recurrence.number_of_months_in_recurrence(default_price.recurrence)
default_price_cents = default_price.price_cents
number_of_months_in_recurrence = BasePrice::Recurrence.number_of_months_in_recurrence(recurrence)
suggested_price_cents = (default_price_cents / number_of_months_in_default_price_recurrence.to_f) * number_of_months_in_recurrence
suggested_price_cents
end
def show_customizable_price_indicator?
return customizable_price unless is_tiered_membership
# for tiered products, show `+` in formatted price if:
# 1. there are multiple tiers, or
# 2. any tiers have PWYW enabled, or
# 3. there's only 1 tier but it has multiple prices
tiers.size > 1 || tiers.where(customizable_price: true).exists? || default_tier.prices.alive.is_buy.size > 1
end
def lowest_tier_price(for_default_duration: false)
return unless is_tiered_membership
prices = VariantPrice.where(variant_id: tiers.map(&:id)).alive.is_buy
prices = prices.where(recurrence: subscription_duration) if for_default_duration
prices.order("price_cents asc").take ||
default_tier.prices.is_buy.build(price_cents: 0, recurrence: subscription_duration)
end
def lowest_variant_price_difference_cents
return if is_tiered_membership?
lowest_variant = current_base_variants.order(price_difference_cents: :asc).first
lowest_variant&.price_difference_cents
end
def display_recurrence
is_tiered_membership && lowest_tier_price ? lowest_tier_price.recurrence : subscription_duration
end
def prices_to_validate
if persisted?
prices.alive.where(currency: price_currency_type).pluck(:price_cents)
else
price_cents_to_validate = []
price_cents_to_validate << buy_price_cents if buyable?
price_cents_to_validate << rental_price_cents if rentable?
price_cents_to_validate
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/creation_limit.rb | app/modules/product/creation_limit.rb | # frozen_string_literal: true
module Product::CreationLimit
extend ActiveSupport::Concern
included do
validate :validate_daily_product_creation_limit, on: :create
end
class_methods do
def bypass_product_creation_limit
previous = product_creation_limit_bypassed?
self.product_creation_limit_bypassed = true
yield
ensure
self.product_creation_limit_bypassed = previous
end
def product_creation_limit_bypassed?
ActiveSupport::IsolatedExecutionState[ISOLATED_EXECUTION_STATE_KEY]
end
private
def product_creation_limit_bypassed=(value)
ActiveSupport::IsolatedExecutionState[ISOLATED_EXECUTION_STATE_KEY] = value
end
end
private
ISOLATED_EXECUTION_STATE_KEY = :gumroad_bypass_product_creation_limit
def validate_daily_product_creation_limit
return if skip_daily_product_creation_limit?
last_24h_links_count = user.links.where(created_at: 1.day.ago..).count
return if last_24h_links_count < daily_creation_limit
errors.add(:base, "Sorry, you can only create #{daily_creation_limit} products per day.")
end
def skip_daily_product_creation_limit?
return true if Rails.env.development?
return true if self.class.product_creation_limit_bypassed?
return true if user.blank?
return true if user.is_team_member?
false
end
def daily_creation_limit
user&.compliant? ? 100 : 10
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/shipping.rb | app/modules/product/shipping.rb | # frozen_string_literal: true
module Product::Shipping
# constant referring to all other countries
ELSEWHERE = "ELSEWHERE"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/searchable.rb | app/modules/product/searchable.rb | # frozen_string_literal: true
module Product::Searchable
extend ActiveSupport::Concern
# we want to show 9 tags, but this is used as an array indexing which starts at 0
MAX_NUMBER_OF_TAGS = 8
RECOMMENDED_PRODUCTS_PER_PAGE = 9
MAX_NUMBER_OF_FILETYPES = 8
MAX_OFFER_CODES_IN_INDEX = 300
ATTRIBUTE_TO_SEARCH_FIELDS_MAP = {
"name" => ["name", "rated_as_adult"],
"description" => ["description", "rated_as_adult"],
"price_cents" => ["price_cents", "available_price_cents"],
"purchase_disabled_at" => ["is_recommendable", "is_alive_on_profile", "is_alive"],
"deleted_at" => ["is_recommendable", "is_alive_on_profile", "is_alive"],
"banned_at" => ["is_recommendable", "is_alive_on_profile", "is_alive"],
"max_purchase_count" => ["is_recommendable"],
"taxonomy_id" => ["taxonomy_id", "is_recommendable"],
"content_updated_at" => "content_updated_at",
"archived" => ["is_recommendable", "is_alive_on_profile"],
"is_in_preorder_state" => "is_preorder",
"display_product_reviews" => ["display_product_reviews", "is_recommendable"],
"is_adult" => "rated_as_adult",
"native_type" => "is_call",
}.freeze
private_constant :ATTRIBUTE_TO_SEARCH_FIELDS_MAP
SEARCH_FIELDS = Set.new(%w[
user_id
is_physical
tags
creator_name
sales_volume
created_at
average_rating
reviews_count
is_subscription
is_bundle
filetypes
price_cents
available_price_cents
updated_at
creator_external_id
content_updated_at
total_fee_cents
past_year_fee_cents
staff_picked_at
offer_codes
] + ATTRIBUTE_TO_SEARCH_FIELDS_MAP.values.flatten)
MAX_PARTIAL_SEARCH_RESULTS = 5
MAX_RESULT_WINDOW = 10_000
DEFAULT_SALES_VOLUME_RECENTNESS = 3.months
HOT_AND_NEW_PRODUCT_RECENTNESS = 90.days
TOP_CREATORS_SIZE = 6
included do
include Elasticsearch::Model
include AfterCommitEverywhere
index_name "products"
settings number_of_shards: 1, number_of_replicas: 0, analysis: {
filter: {
edge_ngram_filter: {
type: "edge_ngram",
min_gram: "2",
max_gram: "20",
}
},
analyzer: {
edge_ngram_analyzer: {
type: "custom",
tokenizer: "standard",
filter: ["lowercase", "edge_ngram_filter"]
}
}
} do
mapping dynamic: :strict do
# https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html
indexes :name,
type: :text,
fields: {
ngrams: { type: :text,
analyzer: "edge_ngram_analyzer",
search_analyzer: "standard" }
}
indexes :description, type: :text
# https://www.elastic.co/guide/en/elasticsearch/reference/master/dynamic-field-mapping.html
# The subfields are defined by default as a dynamic incurred field
# We are being explicit about its definition here
indexes :tags, type: :text do
indexes :keyword, type: :keyword
end
indexes :filetypes, type: :text do
indexes :keyword, type: :keyword
end
indexes :user_id, type: :long
indexes :taxonomy_id, type: :long
indexes :sales_volume, type: :long
indexes :created_at, type: :date
indexes :alive_on_profile, type: :text do # unused
indexes :keyword, type: :keyword, ignore_above: 256
end
indexes :average_rating, type: :float
indexes :categories, type: :text do # unused
indexes :keyword, type: :keyword, ignore_above: 256
end
indexes :content_updated_at, type: :date
indexes :creator_external_id, type: :text do
indexes :keyword, type: :keyword, ignore_above: 256
end
indexes :creator_name, type: :text do
indexes :keyword, type: :keyword, ignore_above: 256
end
indexes :display_product_reviews, type: :boolean
indexes :is_adult, type: :boolean
indexes :is_physical, type: :boolean
indexes :is_preorder, type: :boolean
indexes :is_subscription, type: :boolean
indexes :is_bundle, type: :boolean
indexes :is_recommendable, type: :boolean
indexes :is_alive_on_profile, type: :boolean
indexes :is_call, type: :boolean
indexes :is_alive, type: :boolean
indexes :price_cents, type: :long
indexes :available_price_cents, type: :long
indexes :recommendable, type: :text do # unused
indexes :keyword, type: :keyword, ignore_above: 256
end
indexes :rated_as_adult, type: :boolean
indexes :reviews_count, type: :long
indexes :sales_count, type: :long
indexes :updated_at, type: :date
indexes :total_fee_cents, type: :long
indexes :past_year_fee_cents, type: :long
indexes :staff_picked_at, type: :date
indexes :offer_codes, type: :text do
indexes :code, type: :keyword, ignore_above: 256
end
end
after_create :enqueue_search_index!
before_update :update_search_index_for_changed_fields
end
end
class_methods do
def search_options(params)
search_options = Elasticsearch::DSL::Search.search do
size params.fetch(:size, RECOMMENDED_PRODUCTS_PER_PAGE)
from (params[:from].to_i - 1).clamp(0, MAX_RESULT_WINDOW - size)
_source false
if params[:track_total_hits]
track_total_hits params[:track_total_hits]
end
query do
bool do
if params[:query].present?
must do
simple_query_string do
query params[:query]
fields %i[name creator_name description tags]
default_operator :and
end
end
end
if params[:user_id]
must do
terms user_id: Array.wrap(params[:user_id]).map(&:to_i)
end
else
must do
term is_recommendable: true
end
unless params[:include_rated_as_adult]
must do
term rated_as_adult: false
end
end
end
if !params[:is_alive_on_profile].nil?
must do
term is_alive_on_profile: params[:is_alive_on_profile]
end
end
if params[:ids].present?
must do
terms "_id" => params[:ids]
end
elsif params[:section].is_a? SellerProfileSection
must do
terms "_id" => params[:section].shown_products
end
end
if params[:exclude_ids].present?
must_not do
terms "_id" => params[:exclude_ids]
end
end
if params[:taxonomy_id]
taxonomy_ids = if params[:include_taxonomy_descendants]
Taxonomy.find(params[:taxonomy_id]).self_and_descendants.pluck(:id)
else
[params[:taxonomy_id]]
end
must do
terms taxonomy_id: taxonomy_ids
end
end
if params[:tags]
must do
terms "tags.keyword" => Array.wrap(params[:tags])
end
end
if params[:filetypes]
must do
terms "filetypes.keyword" => Array.wrap(params[:filetypes])
end
end
if params[:min_price].present? || params[:max_price].present?
filter do
range :available_price_cents do
gte params[:min_price].to_f * 100 if params[:min_price].present?
lte params[:max_price].to_f * 100 if params[:max_price].present?
end
end
end
if params[:rating]
filter do
range :average_rating do
gte params[:rating].to_i if params[:rating].to_i > 0
end
end
must do
term display_product_reviews: "true"
end
end
if params[:min_reviews_count]
filter do
range :reviews_count do
gte params[:min_reviews_count].to_i
end
end
end
if params[:sort] == ProductSortKey::HOT_AND_NEW
filter do
range :created_at do
gte HOT_AND_NEW_PRODUCT_RECENTNESS.ago
end
end
end
if params[:staff_picked]
filter do
exists field: "staff_picked_at"
end
end
if !params[:is_subscription].nil?
must do
term is_subscription: params[:is_subscription]
end
end
if !params[:is_bundle].nil?
must do
term is_bundle: params[:is_bundle]
end
end
if params.key?(:is_call)
must do
term is_call: params[:is_call]
end
end
if params.key?(:is_alive)
must do
term is_alive: params[:is_alive]
end
end
if params[:offer_code].present?
must do
term "offer_codes.code" => params[:offer_code]
end
end
end
end
sort do
case params[:sort]
when ProductSortKey::FEATURED, nil
by :total_fee_cents, order: "desc"
by :sales_volume, order: "desc"
when ProductSortKey::BEST_SELLERS
by :past_year_fee_cents, order: "desc"
when ProductSortKey::CURATED
by :_score, order: "desc"
by :past_year_fee_cents, order: "desc"
when ProductSortKey::HOT_AND_NEW
by :sales_volume, order: "desc"
when ProductSortKey::NEWEST then by :created_at, order: "desc"
when ProductSortKey::AVAILABLE_PRICE_DESCENDING, ProductSortKey::PRICE_DESCENDING then by :available_price_cents, order: "desc", mode: "min"
when ProductSortKey::AVAILABLE_PRICE_ASCENDING, ProductSortKey::PRICE_ASCENDING then by :available_price_cents, order: "asc", mode: "min"
when ProductSortKey::IS_RECOMMENDABLE_DESCENDING then by :is_recommendable, order: "desc"
when ProductSortKey::IS_RECOMMENDABLE_ASCENDING then by :is_recommendable, order: "asc"
when ProductSortKey::REVENUE_ASCENDING then by :sales_volume, order: "asc"
when ProductSortKey::REVENUE_DESCENDING then by :sales_volume, order: "desc"
when ProductSortKey::MOST_REVIEWED then by :reviews_count, order: "desc"
when ProductSortKey::HIGHEST_RATED
by :average_rating, order: "desc"
by :reviews_count, order: "desc"
when ProductSortKey::RECENTLY_UPDATED
by :content_updated_at, order: "desc"
when ProductSortKey::STAFF_PICKED
by :staff_picked_at, order: "desc"
end
# In the event of a tie, sort by newest. Don't sort purchases, since they're already sorted.
by :created_at, order: "desc" unless params[:section] && params[:sort] == ProductSortKey::PAGE_LAYOUT
end
aggregation "tags.keyword" do
terms do
field "tags.keyword"
size MAX_NUMBER_OF_TAGS
end
end
if params[:include_top_creators]
aggregation "top_creators" do
terms do
field "user_id"
size TOP_CREATORS_SIZE
order sales_volume_sum: :desc
aggregation "sales_volume_sum" do
sum field: "sales_volume"
end
end
end
end
end
search_options = search_options.to_hash
search_options[:query][:bool][:must] << params[:search] if params[:search]
if (params[:ids].present? || params[:section].is_a?(SellerProfileSection)) && params[:sort] == ProductSortKey::PAGE_LAYOUT
product_ids = params[:ids] || params[:section].shown_products
search_options[:query][:bool][:should] ||= []
product_ids.each_with_index do |id, i|
search_options[:query][:bool][:should] << { term: { _id: { value: id, boost: product_ids.size - i } } }
end
end
if params[:curated_product_ids].present? && params[:sort] == ProductSortKey::CURATED
search_options[:query][:bool][:should] ||= []
params[:curated_product_ids].each_with_index do |id, i|
search_options[:query][:bool][:should] << { term: { _id: { value: id, boost: params[:curated_product_ids].size - i } } }
end
end
search_options
end
def filetype_options(params)
filetype_search_options = search_options(params.except(:filetypes))
Elasticsearch::DSL::Search.search do
query filetype_search_options[:query]
aggregation "filetypes.keyword" do
terms do
field "filetypes.keyword"
size MAX_NUMBER_OF_FILETYPES
end
end
end
end
def partial_search_options(params)
Elasticsearch::DSL::Search.search do
size MAX_PARTIAL_SEARCH_RESULTS
query do
bool do
must do
simple_query_string do
query params[:query]
fields %i[name name.ngrams]
default_operator :and
end
end
must do
term is_recommendable: true
end
unless params[:include_rated_as_adult]
must do
term rated_as_adult: false
end
end
end
end
sort do
by :sales_volume, order: "desc"
by :created_at, order: "desc"
end
end
end
end
def as_indexed_json(options = {})
options.merge(
build_search_update(SEARCH_FIELDS)
).as_json
end
def build_search_update(attribute_names)
attribute_names.each_with_object({}) do |attribute_name, attributes|
Array.wrap(attribute_name).each do |attr_name|
attributes[attr_name] = build_search_property(attr_name)
end
end
end
def enqueue_search_index!
after_commit do
ProductIndexingService.perform(
product: self.class.find(id),
action: "index",
on_failure: :async
)
end
end
def enqueue_index_update_for(changed_search_fields)
after_commit do
ProductIndexingService.perform(
product: self.class.find(id),
action: "update",
attributes_to_update: changed_search_fields,
on_failure: :async
)
end
end
private
def build_search_property(attribute_key)
case attribute_key
when "name" then name
when "description" then description
when "tags" then tags.pluck(:name)
when "creator_name" then user.name || user.username
when "sales_volume" then total_usd_cents(created_after: DEFAULT_SALES_VOLUME_RECENTNESS.ago)
when "is_recommendable" then recommendable?
when "rated_as_adult" then rated_as_adult?
when "created_at" then created_at
when "average_rating" then average_rating
when "reviews_count" then reviews_count
when "price_cents" then price_cents
when "available_price_cents" then available_price_cents
when "is_physical" then is_physical
when "is_subscription" then is_recurring_billing
when "is_bundle" then is_bundle
when "is_preorder" then is_in_preorder_state
when "filetypes" then product_files.alive.pluck(:filetype).uniq
when "user_id" then user_id
when "taxonomy_id" then taxonomy_id
when "is_alive_on_profile" then (alive? && !archived?)
when "is_alive" then alive?
when "is_call" then native_type == Link::NATIVE_TYPE_CALL
when "display_product_reviews" then display_product_reviews?
when "updated_at" then updated_at
when "creator_external_id" then user.external_id
when "content_updated_at" then content_updated_at
when "total_fee_cents" then total_fee_cents(created_after: DEFAULT_SALES_VOLUME_RECENTNESS.ago)
when "past_year_fee_cents" then total_fee_cents(created_after: 1.year.ago)
when "staff_picked_at" then staff_picked_at
when "offer_codes" then product_and_universal_offer_codes.last(MAX_OFFER_CODES_IN_INDEX).map(&:code)
else
raise "Error building search properties. #{attribute_key} is not a valid property"
end
end
def update_search_index_for_changed_fields
changed_search_fields = ATTRIBUTE_TO_SEARCH_FIELDS_MAP.flat_map do |key, fields|
send(:"#{key}_changed?") ? fields : []
end
return if changed_search_fields.empty?
enqueue_index_update_for(changed_search_fields)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/utils.rb | app/modules/product/utils.rb | # frozen_string_literal: true
module Product::Utils
extend ActiveSupport::Concern
class_methods do
# Helper for when debugging in console.
#
# Fetches a product uniquely identified by `id_or_permalink` (ID, unique or custom permalink)
# and optionally scoped by `user_id` if more than one product can be matched via custom permalink.
def f(id_or_permalink, user_id = nil)
Link.find_by_unique_permalink(id_or_permalink) || find_unique_by(user_id, custom_permalink: id_or_permalink) || Link.find(id_or_permalink)
end
private
# May be simplified/replaced with https://edgeapi.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_sole_by once we upgrade to Rails 7
def find_unique_by(user_id, **args)
found, undesired = Link.by_user(user_id && User.find(user_id)).where(args).first(2)
raise ActiveRecord::RecordNotUnique, "More than one product matched" if undesired.present?
found
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/preview.rb | app/modules/product/preview.rb | # frozen_string_literal: true
module Product::Preview
extend ActiveSupport::Concern
MAX_PREVIEW_COUNT = 8
# If the preview height is not defined or too small we will default to this value, this makes sure we display a large enough preview
# image in the users library
DEFAULT_MOBILE_PREVIEW_HEIGHT = 204
included do
scope :with_asset_preview, -> { joins(:asset_previews).where("asset_previews.deleted_at IS NULL") }
end
FILE_REGEX.each do |type, _ext|
define_method("preview_#{type}_path?") do
main_preview.present? && ((main_preview.file.attached? && main_preview.file.public_send(:"#{ type }?")) || (type == "image" && main_preview.unsplash_url.present?))
end
end
def main_preview
display_asset_previews.first
end
alias preview main_preview
def mobile_oembed_url
OEmbedFinder::MOBILE_URL_REGEXES.detect { |r| preview_oembed_url.try(:match, r) } ? preview_oembed_url : ""
end
def preview=(preview)
return main_preview&.mark_deleted! if preview.blank?
asset_preview = asset_previews.build
if preview.is_a?(String) && preview.present?
asset_preview.url = preview
asset_preview.save!
elsif preview.respond_to?(:path)
asset_preview.file.attach preview
asset_preview.save!
asset_preview.file.analyze
end
end
alias preview_url= preview=
def preview_oembed
main_preview&.oembed
end
def preview_oembed_height
main_preview&.oembed && main_preview&.height
end
def preview_oembed_thumbnail_url
main_preview&.oembed_thumbnail_url
end
def preview_oembed_width
main_preview&.oembed && main_preview&.width
end
def preview_oembed_url
main_preview&.oembed_url
end
def preview_width
main_preview&.display_width
end
def preview_height
main_preview&.display_height
end
def preview_url
main_preview&.url
end
def preview_width_for_mobile
preview_width || 0
end
def preview_height_for_mobile
mobile_preview_height = preview_height || 0
mobile_preview_height = 0 if mobile_preview_height < DEFAULT_MOBILE_PREVIEW_HEIGHT
mobile_preview_height
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/stats.rb | app/modules/product/stats.rb | # frozen_string_literal: true
module Product::Stats
extend ActiveSupport::Concern
class_methods do
# Essentially returns a sum of "active customers" (for each product)
# because we're considering each subscription as one sale,
# and excluding deactivated subscription.
def successful_sales_count(products:, extra_search_options: nil)
return 0 if products.blank?
search_options = Purchase::ACTIVE_SALES_SEARCH_OPTIONS.merge(
product: products,
size: 0,
track_total_hits: true,
)
search_options.merge!(extra_search_options) if extra_search_options.present?
PurchaseSearchService.search(search_options).results.total
end
def monthly_recurring_revenue(products:)
return 0 if products.blank?
search_options = {
product: products,
state: Purchase::NON_GIFT_SUCCESS_STATES,
exclude_non_original_subscription_purchases: true,
exclude_deactivated_subscriptions: true,
exclude_cancelled_or_pending_cancellation_subscriptions: true,
exclude_bundle_product_purchases: true,
aggs: { mrr_total: { sum: { field: "monthly_recurring_revenue" } } },
size: 0
}
search_result = PurchaseSearchService.search(search_options)
search_result.aggregations.mrr_total.value
end
end
def successful_sales_count(extra_search_options = nil)
self.class.successful_sales_count(products: self, extra_search_options:)
end
def has_successful_sales?
successful_sales_count(track_total_hits: nil) > 0
end
def sales_unit
if is_recurring_billing
"subscribers"
elsif is_in_preorder_state
"preorders"
else
"sales"
end
end
def balance_formatted(total_cents = nil)
Money.new(total_cents || total_usd_cents).format(no_cents_if_whole: true)
end
def pending_balance
subscriptions.active.find_each.inject(0) { |total, sub| total + sub.remaining_charges_count * sub.original_purchase.price_cents }
end
def revenue_pending
duration_in_months? ? pending_balance : 0
end
def monthly_recurring_revenue
self.class.monthly_recurring_revenue(products: self)
end
def total_usd_cents(extra_search_options = {})
search_options = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
product: self,
size: 0,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
amount_refunded_cents_total: { sum: { field: "amount_refunded_cents" } },
}
).merge(extra_search_options)
search_result = PurchaseSearchService.search(search_options)
search_result.aggregations.price_cents_total.value - search_result.aggregations.amount_refunded_cents_total.value
end
def total_usd_cents_earned_by_user(for_user, extra_search_options = {})
for_seller = for_user.id == user.id
search_options = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
product: self,
size: 0,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
affiliate_cents_total: { sum: { field: "affiliate_credit_amount_cents" } },
affiliate_fees_total: { sum: { field: "affiliate_credit_fee_cents" } },
amount_refunded_cents_total: { sum: { field: for_seller ? "amount_refunded_cents" : "affiliate_credit_amount_partially_refunded_cents" } },
}
).merge(extra_search_options)
if for_seller
search_options[:seller] = for_user
else
search_options[:affiliate_user] = for_user
end
search_result = PurchaseSearchService.search(search_options)
affiliate_total = search_result.aggregations.affiliate_cents_total.value + search_result.aggregations.affiliate_fees_total.value - search_result.aggregations.amount_refunded_cents_total.value
if for_seller
search_result.aggregations.price_cents_total.value - affiliate_total
else
affiliate_total
end
end
def total_fee_cents(extra_search_options = {})
search_options = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
product: self,
size: 0,
aggs: {
fee_cents_total: { sum: { field: "fee_cents" } },
fee_refunded_cents_total: { sum: { field: "fee_refunded_cents" } },
}
).merge(extra_search_options)
search_result = PurchaseSearchService.search(search_options)
search_result.aggregations.fee_cents_total.value - search_result.aggregations.fee_refunded_cents_total.value
end
def number_of_views
EsClient.count(index: ProductPageView.index_name, body: { query: { term: { product_id: id } } })["count"]
end
def active_customers_count
PurchaseSearchService.search(
product: self,
state: Purchase::ALL_SUCCESS_STATES_EXCEPT_PREORDER_AUTH,
exclude_giftees: true,
exclude_refunded_except_subscriptions: true,
exclude_deactivated_subscriptions: true,
exclude_unreversed_chargedback: true,
exclude_non_original_subscription_purchases: true,
exclude_commission_completion_purchases: true,
exclude_bundle_product_purchases: true,
size: 0,
aggs: { unique_email_count: { cardinality: { field: "email.raw" } } }
).aggregations.unique_email_count.value
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/validations.rb | app/modules/product/validations.rb | # frozen_string_literal: true
module Product::Validations
include ActionView::Helpers::TextHelper
MAX_VIEW_CONTENT_BUTTON_TEXT_LENGTH = 26
MAX_CUSTOM_RECEIPT_TEXT_LENGTH = 500
private
def max_purchase_count_is_greater_than_or_equal_to_inventory_sold
return unless max_purchase_count_changed?
return if max_purchase_count.nil?
errors.add(:base, "Sorry, you cannot limit the number of purchases to that amount.") unless max_purchase_count >= sales_count_for_inventory
end
def require_shipping_for_physical
errors.add(:base, "Shipping form is required for physical products.") if is_physical && !require_shipping
end
def duration_multiple_of_price_options
return unless is_recurring_billing
return if duration_in_months.nil?
return errors.add(:base, "Your subscription length in months must be a number greater than zero.") if duration_in_months <= 0
prices.alive.pluck(:recurrence).each do |recurrence|
unless duration_in_months % BasePrice::Recurrence.number_of_months_in_recurrence(recurrence) == 0
return errors.add(:base, "Your subscription length in months must be a multiple of #{BasePrice::Recurrence.number_of_months_in_recurrence(recurrence)} because you have selected a payment option of #{recurrence} payments.")
end
end
end
def custom_view_content_button_text_length
return if custom_view_content_button_text.blank? || custom_view_content_button_text.length <= MAX_VIEW_CONTENT_BUTTON_TEXT_LENGTH
over_limit = custom_view_content_button_text.length - MAX_VIEW_CONTENT_BUTTON_TEXT_LENGTH
errors.add(:base, "Button: #{pluralize(over_limit, 'character')} over limit (max: #{MAX_VIEW_CONTENT_BUTTON_TEXT_LENGTH})")
end
def content_has_no_adult_keywords
[description, name].each do |content|
if AdultKeywordDetector.adult?(content)
errors.add(:base, "Adult keywords are not allowed")
break
end
end
end
def bundle_is_not_in_bundle
return unless BundleProduct.alive.where(product: self).exists?
errors.add(:base, "This product cannot be converted to a bundle because it is already part of a bundle.")
end
def published_bundle_must_have_at_least_one_product
return unless published?
return if not_is_bundle?
return if bundle_products.alive.exists?
errors.add(:base, "Bundles must have at least one product.")
end
def user_is_eligible_for_service_products
return if user.eligible_for_service_products?
errors.add(:base, "Service products are disabled until your account is 30 days old.")
end
def commission_price_is_valid
double_min_price = currency["min_price"] * 2
return if price_cents == 0 || price_cents >= double_min_price
errors.add(:base, "The commission price must be at least #{formatted_amount_in_currency(double_min_price, price_currency_type, no_cents_if_whole: true)}.")
end
def one_coffee_per_user
return unless user.links.visible_and_not_archived.where(native_type: Link::NATIVE_TYPE_COFFEE).where.not(id:).exists?
errors.add(:base, "You can only have one coffee product.")
end
def calls_must_have_at_least_one_duration
return unless native_type == Link::NATIVE_TYPE_CALL
return if deleted_at.present?
return if variant_categories.alive.first&.alive_variants&.exists?
errors.add(:base, "Calls must have at least one duration")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/recommendations.rb | app/modules/product/recommendations.rb | # frozen_string_literal: true
module Product::Recommendations
def recommendable?
recommendable_reasons.values.all?
end
alias_method :recommendable, :recommendable?
# All of the factors(values/records/etc.) which influence the return value of this method should be watched.
# Whenever any of those factors change, a `SendToElasticsearchWorker` job must be enqueued to update the `is_recommendable`
# field in the Elasticsearch index.
def recommendable_reasons
reasons = {
alive: alive?,
not_archived: !archived?,
reviews_displayed: display_product_reviews?,
not_sold_out: max_purchase_count.present? ? sales_count_for_inventory < max_purchase_count : true,
taxonomy_filled: taxonomy.present?,
sale_made: sales.counts_towards_volume.exists?,
}
user.recommendable_reasons.each do |reason, value|
reasons[:"user_#{reason}"] = value
end
reasons
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/product/caching.rb | app/modules/product/caching.rb | # frozen_string_literal: true
module Product::Caching
def scoped_cache_key(locale, fragmented = false, displayed_switch_ids = [], prefetched_cache_key_prefix = nil, request_host = nil)
displayed_switch_ids = displayed_switch_ids.sort
displayed_switch_ids = displayed_switch_ids.join("_")
prefix = prefetched_cache_key_prefix || cache_key_prefix
request_host_key = "_#{request_host}" if request_host.present?
fragmented_key = "_fragmented" if fragmented
"#{prefix}#{request_host_key}_#{locale}#{fragmented_key}_displayed_switch_ids_#{displayed_switch_ids}"
end
def invalidate_cache
Rails.cache.delete("link_cache_key_prefix_#{id}")
product_cached_values.fresh.each(&:expire!)
end
def cache_key_prefix
Rails.cache.fetch(key_for_cache_key_prefix) do
generate_cache_key_prefix
end
end
def generate_cache_key_prefix
"#{id}_#{SecureRandom.uuid}"
end
def key_for_cache_key_prefix
"link_cache_key_prefix_#{id}"
end
def self.scoped_cache_keys(products, displayed_switch_ids_for_products, locale, fragmented = false)
scoped_keys = []
cache_key_prefixes(products).each_with_index do |(key, prefix), i|
scoped_keys.push products[i].scoped_cache_key(locale, fragmented, displayed_switch_ids_for_products[i], prefix)
end
scoped_keys
end
def self.cache_key_prefixes(products)
indexed_products = products.index_by(&:key_for_cache_key_prefix)
Rails.cache.fetch_multi(*indexed_products.keys) do |key|
"#{indexed_products[key].id}_#{SecureRandom.uuid}"
end
end
def self.dashboard_collection_data(collection, cache: false)
product_ids = collection.pluck(:id)
cached_values = ProductCachedValue.fresh.where(product_id: product_ids)
uncached_product_ids = (product_ids - cached_values.pluck(:product_id)).zip
CacheProductDataWorker.perform_bulk(uncached_product_ids) if cache && !uncached_product_ids.empty?
collection.map do |product|
cache_or_product = cached_values.find { |cached_value| cached_value.product_id == product.id } || product
if block_given?
yield(product).merge(
{
"successful_sales_count" => cache_or_product.successful_sales_count,
"remaining_for_sale_count" => cache_or_product.remaining_for_sale_count,
"monthly_recurring_revenue" => cache_or_product.monthly_recurring_revenue.to_f,
"revenue_pending" => cache_or_product.revenue_pending.to_f,
"total_usd_cents" => cache_or_product.total_usd_cents.to_f,
}
)
else
cache_or_product
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/australian_backtaxes.rb | app/modules/user/australian_backtaxes.rb | # frozen_string_literal: true
##
# A collection of methods to help with backtax calculations
##
class User
module AustralianBacktaxes
def opted_in_to_australia_backtaxes?
australia_backtax_agreement.present?
end
def au_backtax_agreement_date
australia_backtax_agreement&.created_at
end
def paid_for_austalia_backtaxes?
australia_backtax_agreement&.credit.present?
end
def date_paid_australia_backtaxes
australia_backtax_agreement&.credit&.created_at&.strftime("%B %-d, %Y")
end
def credit_creation_date
[(Time.now.utc.to_date + 1.month).beginning_of_month, Date.new(2023, 7, 1)].max.strftime("%B %-d, %Y")
end
def australia_backtax_agreement
backtax_agreements.where(jurisdiction: BacktaxAgreement::Jurisdictions::AUSTRALIA).first
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/posts.rb | app/modules/user/posts.rb | # frozen_string_literal: true
module User::Posts
def visible_posts_for(pundit_user:, shown_on_profile: true)
# The condition below doesn't take into consideration logged-in user's role for logged-in seller
# This is a non-issue at this moment as all roles have "read" access to posts.
# To have a more granular access based on role, the logic below needs to be refactored to use a
# policy scope via Pundit (https://github.com/varvet/pundit#scopes)
#
if pundit_user.seller == self
visible_posts = installments.not_workflow_installment.alive
return shown_on_profile ? visible_posts.shown_on_profile : visible_posts
end
follower_post_ids = seller_post_ids = product_post_ids = affiliate_post_ids = nil
audience_posts = installments.where("installment_type = ?", Installment::AUDIENCE_TYPE)
audience_post_ids = audience_posts.map(&:id)
display_audience_posts = false
public_post_ids = audience_posts.shown_on_profile.map(&:id)
if pundit_user.user
follower = follower_by_email(pundit_user.user.email)
if follower.present?
follower_post_ids = installments.where("installment_type = ?", Installment::FOLLOWER_TYPE)
.filter_map { |post| post.id if post.follower_passes_filters(follower) }
display_audience_posts = true
end
purchases = sales.for_visible_posts(purchaser_id: pundit_user.user.id)
if purchases.exists?
product_post_ids = Set.new
filters = purchases.joins(:link)
.select(:email,
:country,
:ip_country,
"min(purchases.created_at) as min_created_at",
"max(purchases.created_at) as max_created_at",
"min(purchases.price_cents) as min_price_cents",
"max(purchases.price_cents) as max_price_cents",
"group_concat(distinct(links.unique_permalink)) as product_permalinks")
.first
.attributes
filters[:variant_external_ids] = []
purchases.each do |purchase|
filters[:variant_external_ids] + purchase.variant_attributes.map(&:external_id)
subscription = purchase.subscription
terminated_at = subscription.present? && !subscription.alive? ? subscription.deactivated_at : nil
posts = installments.where(link_id: purchase.link_id)
.product_or_variant_type
.where("published_at >= ?", purchase.created_at)
posts = posts.where("published_at < ?", terminated_at) if terminated_at.present?
posts = posts.filter { |post| subscription.alive_at?(post.published_at) } if subscription.present?
product_post_ids += posts.filter_map { |post| post.id if post.purchase_passes_filters(purchase) }
end
filters = filters.symbolize_keys.except(:id)
filters[:product_permalinks] = filters[:product_permalinks].split(",").compact if filters[:product_permalinks].present?
seller_post_ids = installments.where("installment_type = ?", Installment::SELLER_TYPE)
.filter_map { |post| post.id if post.seller_post_passes_filters(**filters) }
display_audience_posts = true
end
affiliate = direct_affiliates.alive.find_by(affiliate_user_id: pundit_user.user.id)
if affiliate.present?
affiliate_post_ids = installments.where("installment_type = ?", Installment::AFFILIATE_TYPE)
.filter_map { |post| post.id if post.affiliate_passes_filters(affiliate) }
display_audience_posts = true
end
end
all_visible_post_ids = [public_post_ids]
all_visible_post_ids += follower_post_ids if follower_post_ids
all_visible_post_ids += seller_post_ids if seller_post_ids
all_visible_post_ids += affiliate_post_ids if affiliate_post_ids
all_visible_post_ids += audience_post_ids if display_audience_posts
all_visible_post_ids += product_post_ids.to_a if product_post_ids
visible_posts = Installment.where(id: all_visible_post_ids)
.not_workflow_installment
.alive
.published
shown_on_profile ? visible_posts.shown_on_profile : visible_posts
end
def last_5_created_posts
self.installments.order(created_at: :desc).limit(5)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/social_twitter.rb | app/modules/user/social_twitter.rb | # frozen_string_literal: true
module User::SocialTwitter
TWITTER_PROPERTIES = %w[twitter_user_id twitter_handle twitter_oauth_token twitter_oauth_secret].freeze
def self.included(base)
base.extend(TwitterClassMethods)
end
def twitter_picture_url
twitter_user = $twitter.user(twitter_user_id.to_i)
pic_url = twitter_user.profile_image_url.to_s.gsub("_normal.", "_400x400.")
pic_url = URI(URI::DEFAULT_PARSER.escape(pic_url))
URI.open(pic_url) do |remote_file|
tempfile = Tempfile.new(binmode: true)
tempfile.write(remote_file.read)
tempfile.rewind
self.avatar.attach(io: tempfile,
filename: File.basename(pic_url.to_s),
content_type: remote_file.content_type)
self.avatar.blob.save!
end
self.avatar.analyze unless self.avatar.attached?
self.avatar_url
rescue StandardError
nil
end
module TwitterClassMethods
# Find user by Twitter ID, Email or create one.
def find_or_create_for_twitter_oauth!(data)
info = data["extra"]["raw_info"]
user = User.where(twitter_user_id: info["id"]).first
unless user
user = User.new
user.provider = :twitter
user.twitter_user_id = info["id"]
user.password = Devise.friendly_token[0, 20]
user.skip_confirmation!
user.save!
end
if info["errors"].present?
info["errors"].each do |error|
logger.error "Error getting extra info from Twitter OAuth: #{error.message}"
end
else
query_twitter(user, info)
end
user.save!
user
end
# Save Twitter data in DB
def query_twitter(user, data)
return unless user
# Dont overwrite fields of existing users.
logger.info(data.inspect)
user.twitter_user_id = data["id"]
user.twitter_handle = data["screen_name"]
# don't set these properties if they already have values
user.name ||= data["name"]
data["entities"]["description"]["urls"].each do |url|
data["description"].gsub!(url["url"], url["display_url"])
end
user.bio ||= data["description"]
user.username = user.twitter_handle unless user.read_attribute(:username).present?
user.username = nil unless user.valid?
user.save
user.twitter_picture_url unless user.avatar.attached?
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/social_facebook.rb | app/modules/user/social_facebook.rb | # frozen_string_literal: true
module User::SocialFacebook
def self.included(base)
base.extend(FacebookClassMethods)
end
def renew_facebook_access_token
oauth = Koala::Facebook::OAuth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
new_token = oauth.exchange_access_token(facebook_access_token)
self.facebook_access_token = new_token
rescue Koala::Facebook::APIError, *INTERNET_EXCEPTIONS => e
logger.info "Error renewing Facebook access token: #{e.message}"
end
module FacebookClassMethods
def find_for_facebook_oauth(data)
return nil if data["uid"].blank?
facebook_access_token = data["credentials"]["token"]
user = User.where(facebook_uid: data["uid"]).first
if user.nil?
email = data["info"]["email"] || data["extra"]["raw_info"]["email"]
user = User.where(email:).first if EmailFormatValidator.valid?(email)
if user.nil?
user = User.new
user.provider = :facebook
user.facebook_access_token = facebook_access_token
user.password = Devise.friendly_token[0, 20]
query_fb_graph(user, data, new_user: true)
user.save!
if user.email.present?
Purchase.where(email: user.email, purchaser_id: nil).each do |past_purchase|
past_purchase.attach_to_user_and_card(user, nil, nil)
end
end
end
else
query_fb_graph(user, data)
user.facebook_access_token = facebook_access_token
user.save!
end
user
end
# Save data from FB graph in DB
def query_fb_graph(user, data, new_user: false)
# Handle possibly bad JSON data from FB
return if data.blank? || data.is_a?(String)
user.facebook_uid = data["uid"]
if new_user
user.name = data["extra"]["raw_info"]["name"]
email = data["info"]["email"] || data["extra"]["raw_info"]["email"]
user.email = email
user.skip_confirmation!
end
user.facebook_access_token = data["credentials"]["token"]
end
def fb_object(obj, token: nil)
Koala::Facebook::API.new(token).get_object(obj)
end
def fb_app_access_token
Koala::Facebook::OAuth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET).get_app_access_token
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/stats.rb | app/modules/user/stats.rb | # frozen_string_literal: true
# Mixin contains stats helpers for use on Users.
#
# See the User::PaymentStats module for internal stats that are not displayed to the Seller.
module User::Stats
include CurrencyHelper
extend ActiveSupport::Concern
included do
attr_accessor :sales_total
scope :by_sales_revenue, lambda { |days_ago: nil, limit:|
joins("LEFT JOIN links on links.user_id = users.id \
LEFT JOIN purchases on purchases.link_id = links.id")
.select("users.*, SUM(purchases.price_cents) AS sales_total")
.where("purchases.price_cents > 0 AND purchases.purchase_state = 'successful' AND \
(purchases.stripe_refunded IS NULL OR purchases.stripe_refunded = 0) \
#{days_ago.present? ? ' AND purchases.created_at > ?' : ''}", days_ago.to_i.days.ago)
.group("users.id")
.order("sales_total DESC, users.created_at DESC")
.limit(limit)
}
end
def active_subscribers?(charge_processor_id:, merchant_account: nil)
active_subscriptions = Subscription.distinct
.joins(link: :user)
.merge(Link.alive.is_recurring_billing)
.where(users: { id: })
.active_without_pending_cancel
.joins(:purchases)
.where.not(purchases: { total_transaction_cents: 0 })
active_subscriptions = active_subscriptions.where("purchases.merchant_account_id = ?", merchant_account.id) if merchant_account.present?
subscriptions_using_charge_processor = false
subscriptions_using_charge_processor ||= active_subscriptions.where(user_id: nil)
.joins(:credit_card)
.where(credit_cards: { charge_processor_id: })
.exists?
subscriptions_using_charge_processor ||= active_subscriptions.where.not(user_id: nil)
.joins(user: :credit_card)
.where(credit_cards: { charge_processor_id: })
.exists?
subscriptions_using_charge_processor
end
def active_preorders?(charge_processor_id:, merchant_account: nil)
preorders = Preorder.distinct.joins(preorder_link: { link: :user })
.merge(Link.alive.is_in_preorder_state)
.merge(PreorderLink.without_state(:released))
.authorization_successful
.where(users: { id: })
.joins(:purchases)
.where.not(purchases: { total_transaction_cents: 0 })
preorders = preorders.where("purchases.merchant_account_id = ?", merchant_account.id) if merchant_account.present?
preorders_using_charge_processor = false
preorders_using_charge_processor ||= preorders.where(purchaser_id: nil)
.joins(:credit_card)
.where(credit_cards: { charge_processor_id: })
.exists?
preorders_using_charge_processor ||= preorders.where.not(purchaser_id: nil)
.joins(purchaser: :credit_card)
.where(credit_cards: { charge_processor_id: })
.exists?
preorders_using_charge_processor
end
def balance_formatted(via: :sql)
formatted_dollar_amount(unpaid_balance_cents(via:), with_currency: should_be_shown_currencies_always?)
end
def affiliate_credits_sum_for_credits_created_between(start_time, end_time)
paid_scope = affiliate_credits.paid.where("affiliate_credits.created_at > ? AND affiliate_credits.created_at <= ? ", start_time, end_time)
all_scope = affiliate_credits.where("affiliate_credits.created_at > ? AND affiliate_credits.created_at <= ? ", start_time, end_time)
affiliate_credit_sum_from_scope(paid_scope, all_scope)
end
def affiliate_credits_sum_total
paid_scope = affiliate_credits.paid
all_scope = affiliate_credits
affiliate_credit_sum_from_scope(paid_scope, all_scope)
end
def affiliate_credit_sum_from_scope(paid_scope, all_scope)
aff_credit_cents = paid_scope.sum("amount_cents").to_i
aff_credit_cents += all_scope
.joins(:purchase).where("purchases.stripe_partially_refunded": true)
.sum("amount_cents")
aff_credit_cents -= all_scope
.joins(:purchase).where("purchases.stripe_partially_refunded": true)
.joins(:affiliate_partial_refunds)
.sum("affiliate_partial_refunds.amount_cents")
aff_credit_cents
end
def last_weeks_followers
end_of_period = Date.today.beginning_of_week(:sunday).to_datetime
start_of_period = end_of_period - 7.days
followers.active.where("created_at > ? and created_at <= ?", start_of_period, end_of_period).count
end
def last_weeks_sales
end_of_period = Date.today.beginning_of_week(:sunday).to_datetime
start_of_period = end_of_period - 7.days
paid_sales = sales.paid.not_chargedback_or_chargedback_reversed
.where("purchases.created_at > ? and purchases.created_at <= ?", start_of_period, end_of_period)
total_from(paid_sales, affiliate_credits_sum_for_credits_created_between(start_of_period, end_of_period))
end
def total_from(paid_sales, affiliate_credits)
price = paid_sales.sum(:price_cents)
price += affiliate_credits
fee = paid_sales.sum(:fee_cents)
fee += paid_sales.sum(:affiliate_credit_cents)
price -= paid_sales.joins(:refunds).sum("refunds.amount_cents")
fee -= paid_sales.joins(:refunds).sum("refunds.fee_cents")
fee -= paid_sales.joins(:affiliate_partial_refunds).sum("affiliate_partial_refunds.amount_cents")
price - fee
end
def credits_total
credits.sum(:amount_cents)
end
def sales_cents_total(after: nil)
revenue_as_seller(after:) + revenue_as_affiliate(after:)
end
def gross_sales_cents_total_as_seller(recommended: nil)
search_params = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
seller: self,
recommended:,
size: 0,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
amount_refunded_cents_total: { sum: { field: "amount_refunded_cents" } },
},
)
result = PurchaseSearchService.search(search_params)
result.aggregations.price_cents_total.value - result.aggregations.amount_refunded_cents_total.value
end
def sales_cents_total_formatted
formatted_dollar_amount(sales_cents_total, with_currency: should_be_shown_currencies_always?)
end
def time_until_pay_day_formatted
end_time = DateTime.current.end_of_month
stamp = end_time.strftime("#{end_time.day.ordinalize} of %B")
if end_time > 1.day.from_now
days = (end_time - DateTime.current).to_i
"in #{days} days, on the #{stamp}"
else
"on the #{stamp}"
end
end
# Admin use only
def lost_chargebacks # returns `{ volume: String, count: String }`
search_params = {
seller: self,
state: "successful",
exclude_refunded: true,
exclude_bundle_product_purchases: true,
track_total_hits: true,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
unreversed_chargebacks: {
filter: {
bool: {
must: [{ exists: { field: "chargeback_date" } }],
must_not: [{ term: { "selected_flags" => "chargeback_reversed" } }]
}
},
aggs: {
price_cents_total: { sum: { field: "price_cents" } }
}
}
}
}
search_result = PurchaseSearchService.search(search_params)
count_denominator = search_result.response.hits.total.value.to_f
volume_denominator = search_result.aggregations["price_cents_total"]["value"]
count_numerator = search_result.aggregations["unreversed_chargebacks"]["doc_count"].to_f
volume_numerator = search_result.aggregations["unreversed_chargebacks"]["price_cents_total"]["value"]
volume = volume_denominator > 0 ? format("%.1f%%", volume_numerator / volume_denominator * 100) : "NA"
count = count_denominator > 0 ? format("%.1f%%", count_numerator / count_denominator * 100) : "NA"
{ volume:, count: }
end
def sales_cents_for_balances(balance_ids)
sales
.where(purchase_success_balance_id: balance_ids)
.sum("price_cents")
end
def refunds_cents_for_balances(balance_ids)
sales.where(purchase_refund_balance_id: balance_ids)
.joins(:refunds).sum("refunds.amount_cents")
end
def chargebacks_cents_for_balances(balance_ids)
chargebacked_sales = sales.where(purchase_chargeback_balance_id: balance_ids)
chargebacked_sales.sum("price_cents") - chargebacked_sales.joins(:refunds).sum("refunds.amount_cents")
end
def credits_cents_for_balances(balance_ids)
credits
.where(financing_paydown_purchase_id: nil)
.where("json_data->>'$.stripe_loan_paydown_id' IS NULL")
.where(fee_retention_refund_id: nil)
.where(balance_id: balance_ids)
.sum("amount_cents")
end
def loan_repayment_cents_for_balances(balance_ids)
credits
.where("financing_paydown_purchase_id IS NOT NULL OR json_data->>'$.stripe_loan_paydown_id' IS NOT NULL")
.where(balance_id: balance_ids)
.sum("amount_cents")
end
def fees_cents_for_balances(balance_ids)
revenue_fees_cents = sales.where(purchase_success_balance_id: balance_ids).sum("fee_cents")
revenue_fees_cents - returned_fees_due_to_refunds_and_chargebacks(balance_ids)
end
def returned_fees_due_to_refunds_and_chargebacks(balance_ids)
refunded_sales = sales.is_refund_chargeback_fee_waived.where("purchase_refund_balance_id IN (?)", balance_ids)
refunded_fee = refunded_sales.joins(:refunds).sum("refunds.fee_cents")
refunded_sales_fee_not_waived = sales.not_is_refund_chargeback_fee_waived.where("purchase_refund_balance_id IN (?)", balance_ids)
refunded_fee += refunded_sales_fee_not_waived.joins(:refunds).sum("refunds.fee_cents - COALESCE(refunds.json_data->'$.retained_fee_cents', 0)")
disputed_sales = sales.where("purchase_chargeback_balance_id IN (?)", balance_ids)
disputed_fee = disputed_sales.sum(:fee_cents) - disputed_sales.joins(:refunds).sum("refunds.fee_cents")
refunded_fee + disputed_fee
end
def taxes_cents_for_balances(balance_ids)
sales
.successful
.not_fully_refunded.not_chargedback_or_chargedback_reversed
.where(purchase_success_balance_id: balance_ids)
.sum("tax_cents")
end
def affiliate_credit_cents_for_balances(balance_ids)
paid_scope = affiliate_credits.not_refunded_or_chargebacked.where(affiliate_credit_success_balance_id: balance_ids)
refunded_cents = affiliate_credits
.where("affiliate_credit_refund_balance_id IN (?) OR affiliate_credit_chargeback_balance_id IN (?)",
balance_ids, balance_ids)
.where.not(affiliate_credit_success_balance_id: balance_ids).sum(:amount_cents)
all_scope = affiliate_credits.where(affiliate_credit_success_balance_id: balance_ids)
affiliate_credit_sum_from_scope(paid_scope, all_scope) - refunded_cents
end
def affiliate_fee_cents_for_balances(balance_ids)
sales_scope = sales.where(purchase_success_balance_id: balance_ids)
aff_fee_cents = sales_scope
.where("purchase_refund_balance_id IS NULL AND purchase_chargeback_balance_id IS NULL")
.sum("affiliate_credit_cents")
aff_fee_cents += sales_scope
.where(stripe_partially_refunded: true)
.sum("affiliate_credit_cents")
aff_fee_cents + returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(balance_ids)
end
def returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(balance_ids)
sales_from_other_balances = sales.where.not(purchase_success_balance_id: balance_ids)
refunded_sales = sales_from_other_balances.where(purchase_refund_balance_id: balance_ids)
refunded_affiliate_fee_cents = BalanceTransaction.where(refund_id: Refund.where(purchase_id: refunded_sales.pluck(:id)))
.where.not(user_id: id)
.sum(:holding_amount_net_cents)
disputed_sales = sales_from_other_balances.where(purchase_chargeback_balance_id: balance_ids)
disputed_affiliate_fee_cents = BalanceTransaction.where(dispute_id: Dispute.where(purchase_id: disputed_sales.pluck(:id)))
.where.not(user_id: id)
.sum(:holding_amount_net_cents)
refunded_affiliate_fee_cents + disputed_affiliate_fee_cents
end
def sales_data_for_balance_ids(balance_ids)
{
sales_cents: sales_cents_for_balances(balance_ids),
refunds_cents: refunds_cents_for_balances(balance_ids),
chargebacks_cents: chargebacks_cents_for_balances(balance_ids),
credits_cents: credits_cents_for_balances(balance_ids),
loan_repayment_cents: loan_repayment_cents_for_balances(balance_ids),
fees_cents: fees_cents_for_balances(balance_ids),
discover_fees_cents: discover_fees_cents_for_balances(balance_ids),
direct_fees_cents: direct_fees_cents_for_balances(balance_ids),
discover_sales_count: discover_sales_count_for_balances(balance_ids),
direct_sales_count: direct_sales_count_for_balances(balance_ids),
taxes_cents: taxes_cents_for_balances(balance_ids),
affiliate_credits_cents: affiliate_credit_cents_for_balances(balance_ids),
affiliate_fees_cents: affiliate_fee_cents_for_balances(balance_ids),
paypal_payout_cents: 0
}
end
def paypal_sales_in_duration(start_date:, end_date:)
paypal_sales = sales.paypal.successful
paypal_sales = paypal_sales.where("succeeded_at >= ?", start_date.beginning_of_day) if start_date
paypal_sales = paypal_sales.where("succeeded_at <= ?", end_date.end_of_day) if end_date
paypal_sales
end
def paypal_refunds_in_duration(start_date:, end_date:)
paypal_refunds = Refund.joins(:purchase).where(
seller_id: id,
purchases: { charge_processor_id: PaypalChargeProcessor.charge_processor_id }
)
paypal_refunds = paypal_refunds.where("refunds.created_at >= ?", start_date.beginning_of_day) if start_date
paypal_refunds = paypal_refunds.where("refunds.created_at <= ?", end_date.end_of_day) if end_date
paypal_refunds
end
def paypal_sales_chargebacked_in_duration(start_date:, end_date:)
disputed_paypal_sales = sales.paypal.chargedback.not_chargeback_reversed
disputed_paypal_sales = disputed_paypal_sales.where("chargeback_date >= ?", start_date.beginning_of_day) if start_date
disputed_paypal_sales = disputed_paypal_sales.where("chargeback_date <= ?", end_date.end_of_day) if end_date
disputed_paypal_sales
end
def paypal_sales_cents_for_duration(start_date:, end_date:)
paypal_sales_in_duration(start_date:, end_date:).sum(:price_cents)
end
def paypal_refunds_cents_for_duration(start_date:, end_date:)
paypal_refunds_in_duration(start_date:, end_date:).sum(:amount_cents)
end
def paypal_chargebacked_cents_for_duration(start_date:, end_date:)
paypal_sales_chargebacked_in_duration(start_date:, end_date:).sum(:price_cents)
end
def paypal_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = paypal_sales_in_duration(start_date:, end_date:).sum(:fee_cents)
revenue_fee_cents - paypal_returned_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def paypal_returned_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = paypal_refunds_in_duration(start_date:, end_date:).sum(:fee_cents)
disputed_fee = paypal_sales_chargebacked_in_duration(start_date:, end_date:).sum(:fee_cents)
refunded_fee + disputed_fee
end
def paypal_discover_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = paypal_sales_in_duration(start_date:, end_date:).was_discover_fee_charged.sum(:fee_cents)
revenue_fee_cents - paypal_returned_discover_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def paypal_returned_discover_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = paypal_refunds_in_duration(start_date:, end_date:)
.where("purchases.flags & ? > 0", Purchase.flag_mapping["flags"][:was_discover_fee_charged])
.sum(:fee_cents)
disputed_fee = paypal_sales_chargebacked_in_duration(start_date:, end_date:).was_discover_fee_charged.sum(:fee_cents)
refunded_fee + disputed_fee
end
def paypal_discover_sales_count_for_duration(start_date:, end_date:)
paypal_sales_in_duration(start_date:, end_date:).was_discover_fee_charged.count
end
def paypal_direct_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = paypal_sales_in_duration(start_date:, end_date:).not_was_discover_fee_charged.sum(:fee_cents)
revenue_fee_cents - paypal_returned_direct_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def paypal_returned_direct_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = paypal_refunds_in_duration(start_date:, end_date:)
.where("purchases.flags & ? = 0", Purchase.flag_mapping["flags"][:was_discover_fee_charged])
.sum(:fee_cents)
disputed_fee = paypal_sales_chargebacked_in_duration(start_date:, end_date:).not_was_discover_fee_charged.sum(:fee_cents)
refunded_fee + disputed_fee
end
def paypal_direct_sales_count_for_duration(start_date:, end_date:)
paypal_sales_in_duration(start_date:, end_date:).not_was_discover_fee_charged.count
end
def paypal_taxes_cents_for_duration(start_date:, end_date:)
tax_cents = paypal_sales_in_duration(start_date:, end_date:).sum(:tax_cents)
tax_cents - paypal_returned_taxes_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def paypal_returned_taxes_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_tax = paypal_refunds_in_duration(start_date:, end_date:).sum(:tax_cents)
disputed_tax = paypal_sales_chargebacked_in_duration(start_date:, end_date:).sum(:tax_cents)
refunded_tax + disputed_tax
end
def paypal_affiliate_fee_cents_for_duration(start_date:, end_date:)
aff_fee_cents = paypal_sales_in_duration(start_date:, end_date:).sum("affiliate_credit_cents")
aff_fee_cents - paypal_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def paypal_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_affiliate_fee_cents = paypal_refunds_in_duration(start_date:, end_date:)
.sum("purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents)").round
disputed_affiliate_fee_cents = paypal_sales_chargebacked_in_duration(start_date:, end_date:).sum(:affiliate_credit_cents)
refunded_affiliate_fee_cents + disputed_affiliate_fee_cents
end
def paypal_sales_data_for_duration(start_date:, end_date:)
{
sales_cents: paypal_sales_cents_for_duration(start_date:, end_date:),
refunds_cents: paypal_refunds_cents_for_duration(start_date:, end_date:),
chargebacks_cents: paypal_chargebacked_cents_for_duration(start_date:, end_date:),
credits_cents: 0,
fees_cents: paypal_fees_cents_for_duration(start_date:, end_date:),
discover_fees_cents: paypal_discover_fees_cents_for_duration(start_date:, end_date:),
direct_fees_cents: paypal_direct_fees_cents_for_duration(start_date:, end_date:),
discover_sales_count: paypal_discover_sales_count_for_duration(start_date:, end_date:),
direct_sales_count: paypal_direct_sales_count_for_duration(start_date:, end_date:),
taxes_cents: paypal_taxes_cents_for_duration(start_date:, end_date:),
affiliate_credits_cents: 0,
affiliate_fees_cents: paypal_affiliate_fee_cents_for_duration(start_date:, end_date:),
}
end
def paypal_payout_net_cents(paypal_sales_data)
paypal_sales_data[:sales_cents] -
paypal_sales_data[:refunds_cents] -
paypal_sales_data[:chargebacks_cents] -
paypal_sales_data[:fees_cents] -
paypal_sales_data[:affiliate_fees_cents]
end
# Similar to Payment::Stats#revenue_by_link
def paypal_revenue_by_product_for_duration(start_date:, end_date:)
revenue_by_product = paypal_sales_in_duration(start_date:, end_date:)
.group("link_id")
.sum("price_cents - fee_cents - affiliate_credit_cents")
revenue_by_product.default = 0
chargedback_amounts = paypal_sales_chargebacked_in_duration(start_date:, end_date:)
.group(:link_id)
.sum("price_cents - fee_cents - affiliate_credit_cents")
chargedback_amounts.each { |product, chargeback_amount| revenue_by_product[product] -= chargeback_amount }
refunded_amounts = paypal_refunds_in_duration(start_date:, end_date:)
.group(:link_id)
.sum("refunds.amount_cents - refunds.fee_cents - TRUNCATE(purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents), 0)")
refunded_amounts.each { |product, refund_amount| revenue_by_product[product] -= refund_amount }
revenue_by_product
end
def stripe_connect_sales_in_duration(start_date:, end_date:)
stripe_connect_sales = sales.stripe.successful.
where(merchant_account_id: merchant_accounts.filter_map { |ma| ma.id if ma.is_a_stripe_connect_account? })
stripe_connect_sales = stripe_connect_sales.where("succeeded_at >= ?", start_date.beginning_of_day) if start_date
stripe_connect_sales = stripe_connect_sales.where("succeeded_at <= ?", end_date.end_of_day) if end_date
stripe_connect_sales
end
def stripe_connect_refunds_in_duration(start_date:, end_date:)
stripe_connect_refunds = Refund.joins(:purchase).where(
seller_id: id,
purchases: {
charge_processor_id: StripeChargeProcessor.charge_processor_id,
merchant_account_id: merchant_accounts.filter_map { |ma| ma.id if ma.is_a_stripe_connect_account? }
}
)
stripe_connect_refunds = stripe_connect_refunds.where("refunds.created_at >= ?", start_date.beginning_of_day) if start_date
stripe_connect_refunds = stripe_connect_refunds.where("refunds.created_at <= ?", end_date.end_of_day) if end_date
stripe_connect_refunds
end
def stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:)
disputed_stripe_connect_sales =
sales.stripe
.where(merchant_account_id: merchant_accounts.filter_map { |ma| ma.id if ma.is_a_stripe_connect_account? })
.chargedback.not_chargeback_reversed
disputed_stripe_connect_sales = disputed_stripe_connect_sales.where("chargeback_date >= ?", start_date.beginning_of_day) if start_date
disputed_stripe_connect_sales = disputed_stripe_connect_sales.where("chargeback_date <= ?", end_date.end_of_day) if end_date
disputed_stripe_connect_sales
end
def stripe_connect_sales_cents_for_duration(start_date:, end_date:)
stripe_connect_sales_in_duration(start_date:, end_date:).sum(:price_cents)
end
def stripe_connect_refunds_cents_for_duration(start_date:, end_date:)
stripe_connect_refunds_in_duration(start_date:, end_date:).sum(:amount_cents)
end
def stripe_connect_chargebacked_cents_for_duration(start_date:, end_date:)
stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).sum(:price_cents)
end
def stripe_connect_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = stripe_connect_sales_in_duration(start_date:, end_date:).sum(:fee_cents)
revenue_fee_cents - stripe_connect_returned_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def stripe_connect_returned_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = stripe_connect_refunds_in_duration(start_date:, end_date:).sum(:fee_cents)
disputed_fee = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).sum(:fee_cents)
refunded_fee + disputed_fee
end
def stripe_connect_discover_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = stripe_connect_sales_in_duration(start_date:, end_date:).was_discover_fee_charged.sum(:fee_cents)
revenue_fee_cents - stripe_connect_returned_discover_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def stripe_connect_returned_discover_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = stripe_connect_refunds_in_duration(start_date:, end_date:)
.where("purchases.flags & ? > 0", Purchase.flag_mapping["flags"][:was_discover_fee_charged])
.sum(:fee_cents)
disputed_fee = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).was_discover_fee_charged.sum(:fee_cents)
refunded_fee + disputed_fee
end
def stripe_connect_discover_sales_count_for_duration(start_date:, end_date:)
stripe_connect_sales_in_duration(start_date:, end_date:).was_discover_fee_charged.count
end
def stripe_connect_direct_fees_cents_for_duration(start_date:, end_date:)
revenue_fee_cents = stripe_connect_sales_in_duration(start_date:, end_date:).not_was_discover_fee_charged.sum(:fee_cents)
revenue_fee_cents - stripe_connect_returned_direct_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def stripe_connect_returned_direct_fees_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_fee = stripe_connect_refunds_in_duration(start_date:, end_date:)
.where("purchases.flags & ? = 0", Purchase.flag_mapping["flags"][:was_discover_fee_charged])
.sum(:fee_cents)
disputed_fee = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).not_was_discover_fee_charged.sum(:fee_cents)
refunded_fee + disputed_fee
end
def stripe_connect_direct_sales_count_for_duration(start_date:, end_date:)
stripe_connect_sales_in_duration(start_date:, end_date:).not_was_discover_fee_charged.count
end
def stripe_connect_taxes_cents_for_duration(start_date:, end_date:)
tax_cents = stripe_connect_sales_in_duration(start_date:, end_date:).sum(:tax_cents)
tax_cents - stripe_connect_returned_taxes_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def stripe_connect_returned_taxes_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_tax = stripe_connect_refunds_in_duration(start_date:, end_date:).sum(:tax_cents)
disputed_tax = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).sum(:tax_cents)
refunded_tax + disputed_tax
end
def stripe_connect_affiliate_fee_cents_for_duration(start_date:, end_date:)
aff_fee_cents = stripe_connect_sales_in_duration(start_date:, end_date:).sum("affiliate_credit_cents")
aff_fee_cents - stripe_connect_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(start_date:, end_date:)
end
def stripe_connect_returned_affiliate_fee_cents_due_to_refunds_and_chargebacks(start_date:, end_date:)
refunded_affiliate_fee_cents = stripe_connect_refunds_in_duration(start_date:, end_date:)
.sum("purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents)").round
disputed_affiliate_fee_cents = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:).sum(:affiliate_credit_cents)
refunded_affiliate_fee_cents + disputed_affiliate_fee_cents
end
def stripe_connect_sales_data_for_duration(start_date:, end_date:)
{
sales_cents: stripe_connect_sales_cents_for_duration(start_date:, end_date:),
refunds_cents: stripe_connect_refunds_cents_for_duration(start_date:, end_date:),
chargebacks_cents: stripe_connect_chargebacked_cents_for_duration(start_date:, end_date:),
credits_cents: 0,
fees_cents: stripe_connect_fees_cents_for_duration(start_date:, end_date:),
discover_fees_cents: stripe_connect_discover_fees_cents_for_duration(start_date:, end_date:),
direct_fees_cents: stripe_connect_direct_fees_cents_for_duration(start_date:, end_date:),
discover_sales_count: stripe_connect_discover_sales_count_for_duration(start_date:, end_date:),
direct_sales_count: stripe_connect_direct_sales_count_for_duration(start_date:, end_date:),
taxes_cents: stripe_connect_taxes_cents_for_duration(start_date:, end_date:),
affiliate_credits_cents: 0,
affiliate_fees_cents: stripe_connect_affiliate_fee_cents_for_duration(start_date:, end_date:),
}
end
def stripe_connect_payout_net_cents(stripe_connect_sales_data)
stripe_connect_sales_data[:sales_cents] -
stripe_connect_sales_data[:refunds_cents] -
stripe_connect_sales_data[:chargebacks_cents] -
stripe_connect_sales_data[:fees_cents] -
stripe_connect_sales_data[:affiliate_fees_cents]
end
# Similar to Payment::Stats#revenue_by_link
def stripe_connect_revenue_by_product_for_duration(start_date:, end_date:)
revenue_by_product = stripe_connect_sales_in_duration(start_date:, end_date:)
.group("link_id")
.sum("price_cents - fee_cents - affiliate_credit_cents")
revenue_by_product.default = 0
chargedback_amounts = stripe_connect_sales_chargebacked_in_duration(start_date:, end_date:)
.group(:link_id)
.sum("price_cents - fee_cents - affiliate_credit_cents")
chargedback_amounts.each { |product, chargeback_amount| revenue_by_product[product] -= chargeback_amount }
refunded_amounts = stripe_connect_refunds_in_duration(start_date:, end_date:)
.group(:link_id)
.sum("refunds.amount_cents - refunds.fee_cents - TRUNCATE(purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents), 0)")
refunded_amounts.each { |product, refund_amount| revenue_by_product[product] -= refund_amount }
revenue_by_product
end
def active?(number_of_days)
sales_in_time_period = sales.successful.where("created_at > ?", number_of_days.days.ago).count
new_links_in_time_period = links.where("created_at > ?", number_of_days.days.ago).count
(sales_in_time_period + new_links_in_time_period) > 0
end
def product_count
links.visible.count
end
def total_amount_made_cents
balances.sum(:amount_cents)
end
# Public: Returns the list of products that should be considered for creator analytics purposes.
# We omit products only if they've been deleted or archived *and* they don't have any sales.
def products_for_creator_analytics
successful_purchase_exists_sql = Purchase.successful_or_preorder_authorization_successful.where("purchases.link_id = links.id").to_sql
links.where("EXISTS (#{successful_purchase_exists_sql}) OR (links.deleted_at IS NULL AND #{Link.not_archived_condition})")
.order(id: :desc)
end
def first_sale_created_at_for_analytics
union_sql = [:successful, :preorder_authorization_successful, :preorder_concluded_successfully].map do |state|
"(" + sales.order(:created_at).select(:created_at).limit(1).where(purchase_state: state).to_sql + ")"
end.join(" UNION ")
sql = "SELECT created_at FROM (#{union_sql}) subquery ORDER BY created_at ASC LIMIT 1"
ApplicationRecord.connection.execute(sql).to_a.flatten.first
end
def archived_products_count
links.visible.archived.count
end
def all_sales_count
total = PurchaseSearchService.search(
seller: self,
state: Purchase::NON_GIFT_SUCCESS_STATES,
exclude_giftees: true,
exclude_refunded_except_subscriptions: true,
exclude_unreversed_chargedback: true,
exclude_non_original_subscription_purchases: true,
exclude_commission_completion_purchases: true,
exclude_bundle_product_purchases: true,
size: 0,
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/risk.rb | app/modules/user/risk.rb | # frozen_string_literal: true
module User::Risk
extend ActiveSupport::Concern
IFFY_ENDPOINT = "http://internal-production-iffy-live-internal-1668548970.us-east-1.elb.amazonaws.com"
PAYMENT_REMINDER_RISK_STATES = %w[flagged_for_tos_violation not_reviewed compliant].freeze
INCREMENTAL_ENQUEUE_BALANCE = 100_00
COUNTRIES_THAT_DO_NOT_HAVE_ZIPCODES = [
# Country Codes: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
"ie" # Ireland
].freeze
PROBATION_WITH_REMINDER_DAYS = 30
PROBATION_REVIEW_DAYS = 2
MAX_REFUND_QUEUE_SIZE = 100000
MAX_CHARGEBACK_RATE_ALLOWED_FOR_PAYOUTS = 3.0
def self.contact_iffy_risk_analysis(iffy_request_parameters)
return nil unless Rails.env.production?
return nil if iffy_request_parameters.blank?
return nil if iffy_request_parameters[:is_multi_buy]
return nil if iffy_request_parameters[:card_country] && COUNTRIES_THAT_DO_NOT_HAVE_ZIPCODES.include?(iffy_request_parameters[:card_country].downcase)
begin
iffy_call_timeout = determine_iffy_call_timeout
iffy_response = HTTParty.post("#{IFFY_ENDPOINT}/people/buyer_info", body: iffy_request_parameters, timeout: iffy_call_timeout)
rescue StandardError
Rails.logger.info("iffy_fraud_check_timed_out")
return nil
end
if iffy_response.code == 200
Rails.logger.info("iffy_fraud_check_succeeded, require_zip=#{iffy_response['require_zip']}")
iffy_response
else
Rails.logger.info("iffy_fraud_check_failed, response_code=#{iffy_response.code}")
nil
end
end
DEFAULT_IFFY_CALL_TIMEOUT = 0.4.seconds
def self.determine_iffy_call_timeout
if $redis.present?
redis_iffy_timeout_value = $redis.get("iffy_zipcode_request_timeout")
iffy_call_timeout = if redis_iffy_timeout_value.present?
redis_iffy_timeout_value.to_f
else
DEFAULT_IFFY_CALL_TIMEOUT
end
else
iffy_call_timeout = DEFAULT_IFFY_CALL_TIMEOUT
end
iffy_call_timeout
end
def enable_refunds!
self.refunds_disabled = false
save!
end
def disable_refunds!
self.refunds_disabled = true
save!
end
def flagged_for_explicit_nsfw?
flagged_for_tos_violation? && tos_violation_reason == Compliance::EXPLICIT_NSFW_TOS_VIOLATION_REASON
end
def flag_for_explicit_nsfw_tos_violation!(options)
transaction do
update!(tos_violation_reason: Compliance::EXPLICIT_NSFW_TOS_VIOLATION_REASON)
comment_content = "All products were unpublished because this user was selling prohibited content."
flag_for_tos_violation!(options.merge(bulk: true, content: comment_content))
ContactingCreatorMailer.flagged_for_explicit_nsfw_tos_violation(id).deliver_later(queue: "default")
links.alive.find_each do |product|
product.unpublish!(is_unpublished_by_admin: true)
end
end
end
def suspend_due_to_stripe_risk
transaction do
update!(tos_violation_reason: "Stripe reported high risk")
flag_for_tos_violation!(author_name: "stripe_risk", bulk: true) unless flagged_for_tos_violation? || on_probation? || suspended?
suspend_for_tos_violation!(author_name: "stripe_risk", bulk: true) unless suspended?
links.alive.find_each do |product|
product.unpublish!(is_unpublished_by_admin: true)
end
comments.create!(
author_name: "stripe_risk",
comment_type: Comment::COMMENT_TYPE_SUSPENSION_NOTE,
content: "Suspended because of high risk reported by Stripe"
)
ContactingCreatorMailer.suspended_due_to_stripe_risk(id).deliver_later
end
end
def not_verified?
!verified
end
def log_suspension_time_to_mongo
Mongoer.async_write(MongoCollections::USER_SUSPENSION_TIME, "user_id" => id, "suspended_at" => Time.current.to_s)
end
def disable_links_and_tell_chat
links.each do |link|
link.update(banned_at: Time.current)
end
end
def enable_links_and_tell_chat
links.each do |link|
link.update(banned_at: nil)
end
end
def suspend_sellers_other_accounts
SuspendAccountsWithPaymentAddressWorker.perform_in(5.seconds, id)
end
def block_seller_ip!
BlockSuspendedAccountIpWorker.perform_in(5.seconds, id)
end
def enable_sellers_other_accounts
return if payment_address.blank?
User.where(payment_address:).where.not(id:).each do |user|
user.mark_compliant!(author_name: "enable_sellers_other_accounts", content: "Marked compliant automatically on #{Time.current.to_fs(:formatted_date_full_month)} as payment address #{payment_address} is now unblocked")
end
end
def unblock_seller_ip!
BlockedObject.unblock!(last_sign_in_ip) if last_sign_in_ip.present?
end
def delete_custom_domain!
return if custom_domain.nil?
return if custom_domain.deleted?
custom_domain.mark_deleted!
end
def suspended?
suspended_for_tos_violation? || suspended_for_fraud?
end
alias_method :suspended, :suspended?
def flagged?
flagged_for_tos_violation? || flagged_for_fraud?
end
def suspended_by_admin?
return false unless suspended?
last_suspension_comment = comments
.where(comment_type: Comment::COMMENT_TYPE_SUSPENDED)
.order(:created_at)
.last
last_suspension_comment&.author_id.present?
end
def add_user_comment(transition)
params = transition.args.first
raise ArgumentError, "first transition argument must include an author_id or author_name" if !params || (!params[:author_id] && !params[:author_name])
author_name = params[:author_name] || User.find(params[:author_id])&.name_or_username
date = Time.current.to_fs(:formatted_date_full_month)
content = case transition.to_name
when :compliant
"Marked compliant by #{author_name} on #{date}"
when :on_probation
"Probated (payouts suspended) by #{author_name} on #{date}"
when :flagged_for_tos_violation
params[:product_id].present? ?
"Flagged for a policy violation by #{author_name} on #{date} for product named '#{Link.find(params[:product_id]).name}'" :
"Flagged for a policy violation by #{author_name} on #{date}"
when :suspended_for_tos_violation
"Suspended for a policy violation by #{author_name} on #{date}"
when :flagged_for_fraud
"Flagged for fraud by #{author_name} on #{date}"
when :suspended_for_fraud
"Suspended for fraud by #{author_name} on #{date}"
else
transition.to_name.to_s.humanize
end
comment_type = case transition.to_name
when :compliant
Comment::COMMENT_TYPE_COMPLIANT
when :on_probation
Comment::COMMENT_TYPE_ON_PROBATION
when :flagged_for_fraud, :flagged_for_tos_violation
Comment::COMMENT_TYPE_FLAGGED
when :suspended_for_fraud, :suspended_for_tos_violation
Comment::COMMENT_TYPE_SUSPENDED
else
transition.to_name.slice(/[^_]*/)
end
comments.create!(
content: params[:content] || content,
author_id: params[:author_id],
author_name: params[:author_name],
comment_type:
)
end
def add_product_comment(transition)
params = transition.args.first
return if params && params[:bulk]
raise ArgumentError, "first transition argument must include a product_id" if !params || !params[:product_id]
action_taken = transition.to_name.to_s.humanize
action_reason = tos_violation_reason
product = Link.find_by(id: params[:product_id])
product.comments.create!(
content: params[:content] || "#{action_taken} as #{action_reason}",
author_id: params[:author_id],
author_name: params[:author_name],
comment_type: transition.to_name.slice(/[^_]*/)
)
end
PAYOUTS_STATUSES = %w[paused payable].freeze
PAYOUTS_STATUSES.each do |status|
self.const_set("PAYOUTS_STATUS_#{status.upcase}", status)
end
def payouts_status
@_account_with_paused_payouts_state ||= \
if payouts_paused?
PAYOUTS_STATUS_PAUSED
else
PAYOUTS_STATUS_PAYABLE
end
end
PAYOUT_PAUSE_SOURCES = %w[stripe admin system user].freeze
PAYOUT_PAUSE_SOURCES.each do |source|
self.const_set("PAYOUT_PAUSE_SOURCE_#{source.upcase}", source)
end
class_methods do
def refund_queue(from_date = 30.days.ago)
user_ids = MONGO_DATABASE[MongoCollections::USER_SUSPENSION_TIME]
.find(suspended_at: { "$gte": from_date.utc.to_s })
.limit(MAX_REFUND_QUEUE_SIZE)
.map { |record| record["user_id"] }
User.where(id: user_ids, user_risk_state: "suspended_for_fraud")
.joins(:balances)
.merge(Balance.unpaid)
.group(:user_id)
.having("SUM(amount_cents) > 0")
.order(updated_at: :desc, id: :desc)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/validations.rb | app/modules/user/validations.rb | # frozen_string_literal: true
module User::Validations
ALLOWED_AVATAR_EXTENSIONS = ["png", "jpg", "jpeg"]
MINIMUM_AVATAR_DIMENSION = 200
MAXIMUM_AVATAR_FILE_SIZE = 10.megabytes
GA_REGEX = %r{G-[a-zA-Z0-9]+} # Regex for Google Analytics 4 Measurement ID.
private
def google_analytics_id_valid
return if google_analytics_id.blank? || google_analytics_id.match(GA_REGEX)
errors.add(:base, "Please enter a valid Google Analytics ID")
end
def email_almost_unique
return if !email_changed? || email.blank? || User.by_email(email).empty?
errors.add(:base, "An account already exists with this email.")
end
def account_created_email_domain_is_not_blocked
return if self.errors[:email].present?
return unless blocked_by_email_domain?
errors.add(:base, "Something went wrong.")
end
def account_created_ip_is_not_blocked
return unless blocked_by_account_created_ip?
errors.add(:base, "Something went wrong.")
end
def avatar_is_valid
return if !avatar.attached? || !avatar.new_record?
if avatar.byte_size > MAXIMUM_AVATAR_FILE_SIZE
errors.add(:base,
"Please upload a profile picture with a size smaller than #{ApplicationController.helpers.number_to_human_size(MAXIMUM_AVATAR_FILE_SIZE)}")
return
end
begin
avatar.analyze if avatar.metadata["height"].blank? || avatar.metadata["width"].blank?
errors.add(:base, "Please upload a profile picture that is at least 200x200px") if avatar.metadata["height"].to_i < MINIMUM_AVATAR_DIMENSION || avatar.metadata["width"].to_i < MINIMUM_AVATAR_DIMENSION
rescue ActiveStorage::FileNotFoundError
# In Rails 6, newly uploaded files are not stored until after validation passes on save (see https://github.com/rails/rails/pull/33303). As a result, we cannot perform this validation unless direct upload is used.
end
supported_extensions = ALLOWED_AVATAR_EXTENSIONS.join(", ")
errors.add(:base, "Please upload a profile picture with one of the following extensions: #{supported_extensions}.") if ALLOWED_AVATAR_EXTENSIONS.none? { |ext| avatar.content_type.to_s.match?(ext) }
end
def facebook_meta_tag_is_valid
return if facebook_meta_tag.blank? || facebook_meta_tag.match?(/\A<meta\s+name=(["'])facebook-domain-verification(?:\1)\s+content=(["'])\w+(?:\2)\s*\/>\z/)
errors.add(:base, "Please enter a valid meta tag")
end
def payout_frequency_is_valid
return if [User::PayoutSchedule::DAILY, User::PayoutSchedule::WEEKLY, User::PayoutSchedule::MONTHLY, User::PayoutSchedule::QUARTERLY].include?(payout_frequency)
errors.add(:payout_frequency, "must be daily, weekly, monthly, or quarterly")
end
protected
def json_data_must_be_hash
raise "json_data must be a hash" unless json_data.is_a?(Hash)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/payment_stats.rb | app/modules/user/payment_stats.rb | # frozen_string_literal: true
# Mixin contains stats helpers for use on Users, relevant to the internal payments team at Gumroad.
# The numbers in this stats module should unlikely be displayed to the Creator. For example, most
# stats within relate to transaction total values and not the values received or earned by Creators.
#
# See the User::Stats module for analytics and other stats that might be displayed to the Creator.
module User::PaymentStats
# Public: Calculates the average sale price the user has had over the last year.
# If there have been no sales, zero is returned.
def average_transaction_amount_cents
sales_in_last_year = sales.non_free.where(created_at: 1.year.ago..Time.current)
average = sales_in_last_year.average(:price_cents)
(average || 0).to_i
end
# Public: The transaction volume processed for the user in the last year.
def transaction_volume_in_the_last_year
transaction_volume_since(1.year.ago)
end
# Public: The transaction volume processed for the user since the time given.
def transaction_volume_since(since)
sales.paid.where("purchases.created_at > ?", since).sum(:price_cents)
end
# Public: Calculates the projected annual transaction volume.
# This will be the same as volume made over the last year, unless the Creator has not been
# active for the last year, then it will be guestimated for the period starting at their
# first transaction.
def projected_annual_transaction_volume
first_sale = sales.successful.non_free.first
return 0 if first_sale.nil?
period_selling_seconds = Time.current - first_sale.created_at
volume_period_seconds = [period_selling_seconds, 1.year].min
(transaction_volume_in_the_last_year * 1.year / volume_period_seconds).to_i
end
def max_payment_amount_cents
payments.order(amount_cents: :desc).first.try(:amount_cents) || 0
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/recommendations.rb | app/modules/user/recommendations.rb | # frozen_string_literal: true
module User::Recommendations
def recommendable?
recommendable_reasons.values.all?
end
# All of the factors(values/records/etc.) which influence the return value of this method should be watched.
# Whenever any of those factors change, a `SendToElasticsearchWorker` job must be enqueued to update the `is_recommendable`
# field in the Elasticsearch index.
def recommendable_reasons
{
name_filled: name_or_username.present?,
not_deleted: !deleted?,
payout_filled: !(payment_address.blank? && active_bank_account.blank? && stripe_connect_account.blank? && !has_paypal_account_connected?),
compliant: compliant?,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/compliance.rb | app/modules/user/compliance.rb | # frozen_string_literal: true
module User::Compliance
# https://stripe.com/global lists all countries supported by Stripe.
# https://stripe.com/connect/pricing lists default currencies for the supported countries.
# This list contains supported countries which have euros listed as default currency.
EUROPEAN_COUNTRIES = [
Compliance::Countries::AUT,
Compliance::Countries::BEL,
Compliance::Countries::HRV,
Compliance::Countries::CYP,
Compliance::Countries::EST,
Compliance::Countries::FIN,
Compliance::Countries::FRA,
Compliance::Countries::DEU,
Compliance::Countries::GRC,
Compliance::Countries::IRL,
Compliance::Countries::ITA,
Compliance::Countries::LVA,
Compliance::Countries::LTU,
Compliance::Countries::LUX,
Compliance::Countries::MLT,
Compliance::Countries::MCO,
Compliance::Countries::NLD,
Compliance::Countries::PRT,
Compliance::Countries::SVK,
Compliance::Countries::SVN,
Compliance::Countries::ESP,
]
SUPPORTED_COUNTRIES = [
Compliance::Countries::USA,
Compliance::Countries::CAN,
Compliance::Countries::AUS,
Compliance::Countries::GBR,
Compliance::Countries::HKG,
Compliance::Countries::NZL,
Compliance::Countries::SGP,
Compliance::Countries::CHE,
Compliance::Countries::POL,
Compliance::Countries::CZE,
Compliance::Countries::THA,
Compliance::Countries::BGR,
Compliance::Countries::DNK,
Compliance::Countries::HUN,
Compliance::Countries::KOR,
Compliance::Countries::ARE,
Compliance::Countries::ISR,
Compliance::Countries::TTO,
Compliance::Countries::PHL,
Compliance::Countries::TZA,
Compliance::Countries::NAM,
Compliance::Countries::ATG,
Compliance::Countries::ROU,
Compliance::Countries::SWE,
Compliance::Countries::MEX,
Compliance::Countries::ARG,
Compliance::Countries::PER,
Compliance::Countries::NOR,
Compliance::Countries::ALB,
Compliance::Countries::BHR,
Compliance::Countries::JOR,
Compliance::Countries::NGA,
Compliance::Countries::AZE,
Compliance::Countries::IND,
Compliance::Countries::AGO,
Compliance::Countries::NER,
Compliance::Countries::SMR,
Compliance::Countries::VNM,
Compliance::Countries::ETH,
Compliance::Countries::BRN,
Compliance::Countries::GUY,
Compliance::Countries::GTM,
Compliance::Countries::TWN,
Compliance::Countries::IDN,
Compliance::Countries::CRI,
Compliance::Countries::BWA,
Compliance::Countries::CHL,
Compliance::Countries::PAK,
Compliance::Countries::TUR,
Compliance::Countries::BIH,
Compliance::Countries::MAR,
Compliance::Countries::SRB,
Compliance::Countries::ZAF,
Compliance::Countries::KEN,
Compliance::Countries::EGY,
Compliance::Countries::COL,
Compliance::Countries::RWA,
Compliance::Countries::SAU,
Compliance::Countries::JPN,
Compliance::Countries::BGD,
Compliance::Countries::BTN,
Compliance::Countries::LAO,
Compliance::Countries::MOZ,
Compliance::Countries::ECU,
Compliance::Countries::MYS,
Compliance::Countries::URY,
Compliance::Countries::MUS,
Compliance::Countries::JAM,
Compliance::Countries::LIE,
Compliance::Countries::DOM,
Compliance::Countries::UZB,
Compliance::Countries::BOL,
Compliance::Countries::MDA,
Compliance::Countries::MKD,
Compliance::Countries::PAN,
Compliance::Countries::SLV,
Compliance::Countries::GIB,
Compliance::Countries::OMN,
Compliance::Countries::TUN,
Compliance::Countries::MDG,
Compliance::Countries::PRY,
Compliance::Countries::GHA,
Compliance::Countries::ARM,
Compliance::Countries::LKA,
Compliance::Countries::KWT,
Compliance::Countries::ISL,
Compliance::Countries::QAT,
Compliance::Countries::BHS,
Compliance::Countries::LCA,
Compliance::Countries::SEN,
Compliance::Countries::KHM,
Compliance::Countries::MNG,
Compliance::Countries::GAB,
Compliance::Countries::DZA,
Compliance::Countries::MAC,
Compliance::Countries::BEN,
Compliance::Countries::CIV,
].concat(EUROPEAN_COUNTRIES).freeze
SUPPORTED_COUNTRIES_HAVING_STATES = [
Compliance::Countries::USA.alpha2,
Compliance::Countries::CAN.alpha2,
Compliance::Countries::AUS.alpha2,
Compliance::Countries::ARE.alpha2,
Compliance::Countries::MEX.alpha2,
Compliance::Countries::IRL.alpha2,
].freeze
private_constant :SUPPORTED_COUNTRIES, :SUPPORTED_COUNTRIES_HAVING_STATES, :EUROPEAN_COUNTRIES
def self.european_countries
EUROPEAN_COUNTRIES
end
def native_payouts_supported?(country_code: nil)
info = alive_user_compliance_info
return false if country_code.nil? && info.nil?
country_code = country_code.presence || info.legal_entity_country_code
SUPPORTED_COUNTRIES.map(&:alpha2).include?(country_code) &&
(country_code != Compliance::Countries::ARE.alpha2 || info.is_business?)
end
def fetch_or_build_user_compliance_info
alive_user_compliance_info = self.alive_user_compliance_info
return alive_user_compliance_info if alive_user_compliance_info.present?
build_user_compliance_info
end
def build_user_compliance_info
user_compliance_infos.build.tap do |new_user_compliance_info|
new_user_compliance_info.json_data = {}
end
end
def alive_user_compliance_info
user_compliance_infos.alive.last
end
SUPPORTED_COUNTRIES.each do |country|
define_method("signed_up_from_#{
country.common_name
.downcase
.tr(' ', '_')
.tr("'", '_')
.tr('ü', 'u')
.tr('ô', 'o')
}?") do
compliance_country_code == country.alpha2
end
end
def signed_up_from_europe?
EUROPEAN_COUNTRIES.map(&:alpha2).include?(compliance_country_code)
end
def country_supports_iban?
signed_up_from_europe? ||
signed_up_from_switzerland? ||
signed_up_from_poland? ||
signed_up_from_czechia? ||
signed_up_from_bulgaria? ||
signed_up_from_denmark? ||
signed_up_from_hungary? ||
signed_up_from_albania? ||
signed_up_from_jordan? ||
signed_up_from_azerbaijan? ||
signed_up_from_bahrain? ||
signed_up_from_liechtenstein? ||
signed_up_from_united_arab_emirates? ||
signed_up_from_israel? ||
signed_up_from_romania? ||
signed_up_from_sweden? ||
signed_up_from_costa_rica? ||
signed_up_from_pakistan? ||
signed_up_from_guatemala? ||
signed_up_from_angola? ||
signed_up_from_niger? ||
signed_up_from_san_marino? ||
signed_up_from_turkiye? ||
signed_up_from_egypt? ||
signed_up_from_bosnia_and_herzegovina? ||
signed_up_from_saudi_arabia? ||
signed_up_from_norway? ||
signed_up_from_saudi_arabia? ||
signed_up_from_gibraltar? ||
signed_up_from_mauritius? ||
signed_up_from_tunisia? ||
signed_up_from_el_salvador? ||
signed_up_from_kuwait? ||
signed_up_from_iceland? ||
signed_up_from_monaco? ||
signed_up_from_benin? ||
signed_up_from_cote_d_ivoire?
end
def needs_info_of_significant_company_owners?
false
end
# Public: Returns whether the user has ever been asked to provide the field given.
# If `only_needs_to_have_been_requested_partially` is provided as `true` or `false` the function
# will only return true if the field was requested in part or in full, respecively.
# If the parameter is not provided, or set to `nil`, the function will indicate if the field was requested regardless
# of whether partial entry of the field was indicated as allowed in the request.
def has_ever_been_requested_for_user_compliance_info_field?(field, only_needs_to_have_been_requested_partially: nil)
query = user_compliance_info_requests.where(field_needed: field)
query = query.only_needs_field_to_be_partially_provided(only_needs_to_have_been_requested_partially) unless only_needs_to_have_been_requested_partially.nil?
query.exists?
end
def compliance_country_code
alive_user_compliance_info.try(:legal_entity_country_code)
end
def compliance_country_has_states?
SUPPORTED_COUNTRIES_HAVING_STATES.include?(compliance_country_code)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/feature_status.rb | app/modules/user/feature_status.rb | # frozen_string_literal: true
##
# A collections of methods that determines user's status with certain features.
##
class User
module FeatureStatus
def merchant_migration_enabled?
check_merchant_account_is_linked || (Feature.active?(:merchant_migration, self) &&
StripeMerchantAccountManager::COUNTRIES_SUPPORTED_BY_STRIPE_CONNECT.include?(::Compliance::Countries.find_by_name(alive_user_compliance_info&.country)&.alpha2))
end
def paypal_connect_enabled?
alive_user_compliance_info.present? && PaypalMerchantAccountManager::COUNTRY_CODES_NOT_SUPPORTED_BY_PCP.exclude?(::Compliance::Countries.find_by_name(alive_user_compliance_info.country)&.alpha2)
end
def paypal_connect_allowed?
compliant? && sales_cents_total >= PaypalMerchantAccountManager::MIN_SALES_CENTS_REQ_FOR_PCP && has_completed_payouts?
end
def paypal_disconnect_allowed?
!active_subscribers?(charge_processor_id: PaypalChargeProcessor.charge_processor_id) &&
!active_preorders?(charge_processor_id: PaypalChargeProcessor.charge_processor_id)
end
def can_setup_bank_payouts?
active_bank_account.present? || native_payouts_supported? || signed_up_from_united_arab_emirates?
end
def can_setup_paypal_payouts?
payment_address.present? || !native_payouts_supported? || signed_up_from_united_arab_emirates? || signed_up_from_egypt?
end
def charge_paypal_payout_fee?
Feature.active?(:paypal_payout_fee, self) &&
!paypal_payout_fee_waived? &&
PaypalPayoutProcessor::PAYPAL_PAYOUT_FEE_EXEMPT_COUNTRY_CODES.exclude?(alive_user_compliance_info&.legal_entity_country_code)
end
def stripe_disconnect_allowed?
!has_stripe_account_connected? ||
(!active_subscribers?(charge_processor_id: StripeChargeProcessor.charge_processor_id, merchant_account: stripe_connect_account) &&
!active_preorders?(charge_processor_id: StripeChargeProcessor.charge_processor_id, merchant_account: stripe_connect_account))
end
def has_stripe_account_connected?
merchant_migration_enabled? && stripe_connect_account.present?
end
def has_paypal_account_connected?
paypal_connect_account.present?
end
def can_publish_products?
is_team_member? || stripe_account.present? || stripe_connect_account.present? || paypal_connect_account.present? || payment_address.present?
end
def pay_with_paypal_enabled?
# PayPal sales have been disabled for this creator by admin (mostly due to high chargeback rate)
return false if disable_paypal_sales?
# Paypal Connect is not enabled, fallback to old Paypal mode
return Feature.inactive?(:disable_braintree_sales, self) unless paypal_connect_enabled?
# If Paypal Connect is supported, check if user has connected a Merchant Account
merchant_accounts.alive.charge_processor_alive.paypal.exists?
end
def pay_with_card_enabled?
return true unless check_merchant_account_is_linked?
merchant_accounts.alive.charge_processor_alive.stripe.exists?
end
def native_paypal_payment_enabled?
merchant_account(PaypalChargeProcessor.charge_processor_id).present?
end
def has_payout_information?
active_bank_account.present? || payment_address.present? || has_stripe_account_connected? || has_paypal_account_connected?
end
def can_disable_vat?
false
end
def waive_gumroad_fee_on_new_sales?
timezone_for_gumroad_day = gumroad_day_timezone.presence || timezone
is_today_gumroad_day = Time.now.in_time_zone(timezone_for_gumroad_day).to_date == $redis.get(RedisKey.gumroad_day_date)&.to_date
is_today_gumroad_day || Feature.active?(:waive_gumroad_fee_on_new_sales, self)
end
def product_level_support_emails_enabled?
Feature.active?(:product_level_support_emails, self)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/money_balance.rb | app/modules/user/money_balance.rb | # frozen_string_literal: true
class User
module MoneyBalance
def unpaid_balance_cents(via: :sql)
if via == :elasticsearch
begin
Balance.amount_cents_sum_for(self)
rescue => e
Bugsnag.notify(e)
unpaid_balance_cents(via: :sql)
end
else
balances.unpaid.sum(:amount_cents)
end
end
def unpaid_balance_cents_up_to_date(date)
balances.unpaid.where("date <= ?", date).sum(:amount_cents)
end
def unpaid_balance_cents_up_to_date_held_by_gumroad(date)
balances.unpaid.where("date <= ?", date).where(merchant_account_id: gumroad_merchant_account_ids).sum(:amount_cents)
end
def unpaid_balance_holding_cents_up_to_date_held_by_stripe(date)
creator_stripe_account = stripe_account
return 0 unless creator_stripe_account.present?
balances.unpaid.where("date <= ?", date).where(merchant_account_id: creator_stripe_account.id).sum(:holding_amount_cents)
end
def instantly_payable_unpaid_balance_cents
instantly_payable_unpaid_balances.sum(&:holding_amount_cents)
end
def instantly_payable_unpaid_balance_cents_up_to_date(date)
instantly_payable_unpaid_balances_up_to_date(date).sum(&:holding_amount_cents)
end
def instantly_payable_unpaid_balances
instantly_payable_unpaid_balances_up_to_date(Date.today)
end
def instantly_payable_unpaid_balances_up_to_date(date)
amount_cents_available_on_stripe = StripePayoutProcessor.instantly_payable_amount_cents_on_stripe(self)
first_unpayable_balance_held_by_stripe_date = nil
unpaid_balances_up_to_date(date).select { _1.merchant_account.holder_of_funds == HolderOfFunds::STRIPE }.sort_by(&:date).map(&:date).each do |date|
balance_cents_held_by_stripe_till_date = unpaid_balances.where("date <= ?", date).select { _1.merchant_account.holder_of_funds == HolderOfFunds::STRIPE }.sum(&:holding_amount_cents)
if (balance_cents_held_by_stripe_till_date * 100.0 / (100 + StripePayoutProcessor::INSTANT_PAYOUT_FEE_PERCENT)).floor > amount_cents_available_on_stripe
first_unpayable_balance_held_by_stripe_date = date
break
end
end
payable_balances = unpaid_balances_up_to_date(date)
payable_balances = payable_balances.where("date < ?", first_unpayable_balance_held_by_stripe_date) if first_unpayable_balance_held_by_stripe_date.present?
payable_balances.select { _1.merchant_account.holder_of_funds.in?([HolderOfFunds::STRIPE, HolderOfFunds::GUMROAD]) }.sort_by(&:date)
end
def unpaid_balances_up_to_date(date)
balances.unpaid.where("date <= ?", date)
end
def unpaid_balances
balances.unpaid
end
def paid_payments_cents_for_date(date)
payments.where(payout_period_end_date: date, state: %w[processing unclaimed completed]).sum(:amount_cents)
end
def formatted_balance_to_forfeit(reason)
return if reason == :account_closure && Feature.inactive?(:delete_account_forfeit_balance, self)
forfeiter = ForfeitBalanceService.new(user: self, reason:)
forfeiter.balance_amount_formatted if forfeiter.balance_amount_cents_to_forfeit > 0
end
def forfeit_unpaid_balance!(reason)
return if reason == :account_closure && Feature.inactive?(:delete_account_forfeit_balance, self)
ForfeitBalanceService.new(user: self, reason:).process
end
def validate_account_closure_balances!
forfeiter = ForfeitBalanceService.new(user: self, reason: :account_closure)
if forfeiter.balance_amount_cents_to_forfeit != 0
raise UnpaidBalanceError.new("Balance requires forfeiting", forfeiter.balance_amount_formatted)
end
end
private
def gumroad_merchant_account_ids
@_gumroad_merchant_account_ids ||= [
MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id),
MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id)
]
end
end
class UnpaidBalanceError < StandardError
attr_reader :amount
def initialize(message, amount)
@amount = amount
super(message)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/payout_info.rb | app/modules/user/payout_info.rb | # frozen_string_literal: true
module User::PayoutInfo
include CurrencyHelper
def payout_info
@payout_info ||= {
active_bank_account: active_bank_account&.as_json(only: %i[type account_holder_full_name], methods: %i[formatted_account]),
payment_address:,
payouts_paused_by_source:,
payouts_paused_for_reason: comments.with_type_payouts_paused.last&.content,
manual_payout_info:
}
end
private
def manual_payout_info
return unless last_payout_to_user.nil? || %w(completed failed returned reversed cancelled).include?(last_payout_to_user.state)
return unless stripe_payable_from_admin? || paypal_payable_from_admin?
{
stripe: stripe_payable_info,
paypal: paypal_payable_info,
unpaid_balance_up_to_date: unpaid_balance_cents_up_to_date(manual_payout_period_end_date),
currency: stripe_account&.currency,
ask_confirmation: (stripe_payable_from_admin? || paypal_payable_from_admin?) && !stripe_payable? && !paypal_payable?,
manual_payout_period_end_date:
}
end
def stripe_payable_info
return unless stripe_payable_from_admin?
{
unpaid_balance_held_by_gumroad: formatted_dollar_amount(unpaid_balance_cents_up_to_date_held_by_gumroad(manual_payout_period_end_date)),
unpaid_balance_held_by_stripe: formatted_amount_in_currency(unpaid_balance_holding_cents_up_to_date_held_by_stripe(manual_payout_period_end_date), stripe_account&.currency)
}
end
def paypal_payable_info
return unless paypal_payable_from_admin?
{
should_payout_be_split: should_paypal_payout_be_split?,
split_payment_by_cents: PaypalPayoutProcessor.split_payment_by_cents(self)
}
end
def stripe_payable?
Payouts.is_user_payable(self, manual_payout_period_end_date, processor_type: PayoutProcessorType::STRIPE)
end
def paypal_payable?
Payouts.is_user_payable(self, manual_payout_period_end_date, processor_type: PayoutProcessorType::PAYPAL)
end
def stripe_payable_from_admin?
Payouts.is_user_payable(self, manual_payout_period_end_date, processor_type: PayoutProcessorType::STRIPE, from_admin: true)
end
def paypal_payable_from_admin?
Payouts.is_user_payable(self, manual_payout_period_end_date, processor_type: PayoutProcessorType::PAYPAL, from_admin: true)
end
def manual_payout_period_end_date
User::PayoutSchedule.manual_payout_end_date
end
def last_payout_to_user
payments.last
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/tier.rb | app/modules/user/tier.rb | # frozen_string_literal: true
module User::Tier
# Earning tiers
TIER_0 = 0
TIER_1 = 1_000
TIER_2 = 10_000
TIER_3 = 100_000
TIER_4 = 1_000_000
TIER_RANGES = {
0...1_000_00 => TIER_0,
1_000_00...10_000_00 => TIER_1,
10_000_00...100_000_00 => TIER_2,
100_000_00...1_000_000_00 => TIER_3,
1_000_000_00...Float::INFINITY => TIER_4,
}.freeze
TIER_FEES_MERCHANT_ACCOUNT = {
TIER_0 => 0.09,
TIER_1 => 0.07,
TIER_2 => 0.05,
TIER_3 => 0.03,
TIER_4 => 0.029,
}
TIER_FEES_NON_MERCHANT_ACCOUNT = {
TIER_0 => 0.07,
TIER_1 => 0.05,
TIER_2 => 0.03,
TIER_3 => 0.01,
TIER_4 => 0.009,
}
def tier(sales_cents = nil)
return unless tier_pricing_enabled?
return TIER_0 if sales_cents && sales_cents <= 0
sales_cents ? TIER_RANGES.select { |range| range === sales_cents }.values.first : tier_state
end
def tier_fee(is_merchant_account: nil)
return unless tier_pricing_enabled?
is_merchant_account ? TIER_FEES_MERCHANT_ACCOUNT[tier] : TIER_FEES_NON_MERCHANT_ACCOUNT[tier]
end
def formatted_tier_earning(sales_cents: nil)
return unless tier_pricing_enabled?
Money.new(tier(sales_cents) * 100, :usd).format(with_currency: false, no_cents_if_whole: true)
end
def formatted_tier_fee_percentage(is_merchant_account: nil)
return unless tier_pricing_enabled?
(tier_fee(is_merchant_account:) * 100).round(1)
end
def tier_pricing_enabled?
true
end
def log_tier_transition(from_tier:, to_tier:)
logger.info "User: user ID #{id} transitioned from tier #{from_tier} to tier #{to_tier}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/payout_schedule.rb | app/modules/user/payout_schedule.rb | # frozen_string_literal: true
module User::PayoutSchedule
PAYOUT_STARTING_DATE = Date.new(2012, 12, 21)
PAYOUT_RECURRENCE_DAYS = 7
PAYOUT_DELAY_DAYS = 7
WEEKLY = "weekly"
MONTHLY = "monthly"
QUARTERLY = "quarterly"
DAILY = "daily"
include CurrencyHelper
def next_payout_date
return nil if unpaid_balance_cents < minimum_payout_amount_cents
return Date.current + 1 if payout_frequency == DAILY && Payouts.is_user_payable(self, Date.current, payout_type: Payouts::PAYOUT_TYPE_INSTANT)
upcoming_payout_date = get_initial_payout_date(Date.today)
until upcoming_payout_date >= Date.today
upcoming_payout_date = advance_payout_date(upcoming_payout_date)
end
if payout_amount_for_payout_date(upcoming_payout_date) < minimum_payout_amount_cents
upcoming_payout_date = advance_payout_date(upcoming_payout_date)
end
if upcoming_payout_date == Date.today && payments.where("date(created_at) = ?", Date.today).first.present?
upcoming_payout_date = advance_payout_date(upcoming_payout_date)
end
upcoming_payout_date
end
def current_payout_processor
if (paypal_payout_email.present? && active_bank_account.blank?) || !native_payouts_supported?
PayoutProcessorType::PAYPAL
else
PayoutProcessorType::STRIPE
end
end
def upcoming_payout_amounts
upcoming_payout_date = next_payout_date
upcoming_amounts = {}
while upcoming_payout_date
payout_amount = payout_amount_for_payout_date(upcoming_payout_date) - upcoming_amounts.values.sum
break if payout_amount < minimum_payout_amount_cents
upcoming_amounts[upcoming_payout_date] = payout_amount
upcoming_payout_date = advance_payout_date(upcoming_payout_date)
end
upcoming_amounts
end
def payout_amount_for_payout_date(payout_date)
if payout_frequency == DAILY && Payouts.is_user_payable(self, payout_date - 1, payout_type: Payouts::PAYOUT_TYPE_INSTANT)
instantly_payable_unpaid_balance_cents_up_to_date(payout_date - 1)
else
unpaid_balance_cents_up_to_date(payout_date - PAYOUT_DELAY_DAYS)
end
end
def formatted_balance_for_next_payout_date
next_payout_date = self.next_payout_date
return if next_payout_date.nil?
payout_amount_cents = payout_amount_for_payout_date(next_payout_date)
formatted_dollar_amount(payout_amount_cents)
end
# Public: Returns the upcoming payout date, not taking a user into account.
def self.next_scheduled_payout_date
scheduled_payout_date = PAYOUT_STARTING_DATE
scheduled_payout_date += PAYOUT_RECURRENCE_DAYS while scheduled_payout_date < Date.today
scheduled_payout_date
end
# Public: Returns the upcoming payout's end date, not taking a user into account.
def self.next_scheduled_payout_end_date
next_scheduled_payout_date - PAYOUT_DELAY_DAYS
end
def self.manual_payout_end_date
if [2, 3, 4, 5].include?(Date.today.wday) # Tuesday to Friday
next_scheduled_payout_end_date
else
next_scheduled_payout_end_date - PAYOUT_DELAY_DAYS
end
end
private
def last_friday_of_week(date)
return date if date.friday?
date.next_occurring(:friday)
end
def last_friday_of_month(date)
month_end = date.end_of_month
month_end.friday? ? month_end : month_end.prev_occurring(:friday)
end
def last_friday_of_quarter(date)
quarter_end = date.end_of_quarter
quarter_end.friday? ? quarter_end : quarter_end.prev_occurring(:friday)
end
def get_initial_payout_date(date)
case payout_frequency
# Daily payouts are handled separately, so this date is a fallback, for any amount not able to be paid instantly
when DAILY then last_friday_of_week(date)
when WEEKLY then last_friday_of_week(date)
when MONTHLY then last_friday_of_month(date)
when QUARTERLY then last_friday_of_quarter(date)
end
end
def advance_payout_date(date)
case payout_frequency
# Daily payouts are handled separately, so this date is a fallback, for any amount not able to be paid instantly
when DAILY then last_friday_of_week(date.next_day(7))
when WEEKLY then last_friday_of_week(date.next_day(7))
when MONTHLY then last_friday_of_month(date.next_month)
when QUARTERLY then last_friday_of_quarter(date.next_month(3))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/ping_notification.rb | app/modules/user/ping_notification.rb | # frozen_string_literal: true
module User::PingNotification
def send_test_ping(url)
latest_sale = sales.last
return nil if latest_sale.blank?
URI.parse(url) # TestPingsController.create catches URI::InvalidURIError
ping_params = latest_sale.payload_for_ping_notification.merge(test: true)
ping_params = if notification_content_type == Mime[:json]
ping_params.to_json
elsif notification_content_type == Mime[:url_encoded_form]
ping_params.deep_transform_keys { encode_brackets(_1) }
else
ping_params
end
HTTParty.post(url, body: ping_params, timeout: 5, headers: { "Content-Type" => notification_content_type })
end
def urls_for_ping_notification(resource_name)
post_urls = []
resource_subscriptions.alive.where("resource_name = ?", resource_name).find_each do |resource_subscription|
oauth_application = resource_subscription.oauth_application
# We had a bug where we were actually deleting the application instead of setting its deleted_at. Handle those gracefully.
next if oauth_application.nil? || oauth_application.deleted?
can_view_sales = Doorkeeper::AccessToken.active_for(self).where(application_id: oauth_application.id).find do |token|
token.includes_scope?(:view_sales)
end
post_urls << [resource_subscription.post_url, resource_subscription.content_type] if oauth_application && resource_subscription.post_url.present? && can_view_sales
end
post_urls << [notification_endpoint, notification_content_type] if notification_endpoint.present? && resource_name == ResourceSubscription::SALE_RESOURCE_NAME
post_urls
end
private
def encode_brackets(key)
key.to_s.gsub(/[\[\]]/) { |char| URI.encode_www_form_component(char) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/async_devise_notification.rb | app/modules/user/async_devise_notification.rb | # frozen_string_literal: true
# This module is responsible for sending Devise email notifications via ActiveJob.
# See https://github.com/heartcombo/devise/blob/098345aace53d4ddf88e04f1eb2680e2676e8c28/lib/devise/models/authenticatable.rb#L133-L194.
module User::AsyncDeviseNotification
extend ActiveSupport::Concern
included do
after_commit :send_pending_devise_notifications
end
protected
def send_devise_notification(notification, *args)
# If the record is new or changed then delay the
# delivery until the after_commit callback otherwise
# send now because after_commit will not be called.
if new_record? || changed?
pending_devise_notifications << [notification, args]
else
render_and_send_devise_message(notification, *args)
end
end
private
def send_pending_devise_notifications
pending_devise_notifications.each do |notification, args|
render_and_send_devise_message(notification, *args)
end
# Empty the pending notifications array because the
# after_commit hook can be called multiple times which
# could cause multiple emails to be sent.
pending_devise_notifications.clear
end
def pending_devise_notifications
@pending_devise_notifications ||= []
end
def render_and_send_devise_message(notification, *args)
message = devise_mailer.send(notification, self, *args)
message.deliver_later(queue: "critical", wait: 3.seconds)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user/devise_internal.rb | app/modules/user/devise_internal.rb | # frozen_string_literal: true
##
# A collection of methods used internally in devise gem.
##
class User
module DeviseInternal
def active_for_authentication?
true
end
def confirmation_required?
email_required? && !confirmed? && email.present?
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/follower/from.rb | app/modules/follower/from.rb | # frozen_string_literal: true
module Follower::From
FOLLOW_PAGE = "follow_page"
PROFILE_PAGE = "profile_page"
CSV_IMPORT = "csv_import"
EMBED_FORM = "embed_form"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/ach_account/account_type.rb | app/modules/ach_account/account_type.rb | # frozen_string_literal: true
module AchAccount::AccountType
CHECKING = "checking"
SAVINGS = "savings"
def self.all
[
CHECKING,
SAVINGS
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/recurring_service/tiers.rb | app/modules/recurring_service/tiers.rb | # frozen_string_literal: true
module RecurringService::Tiers
include ActionView::Helpers::NumberHelper
def monthly_tier_amount(customer_count)
case customer_count
when 0..999
10
when 1000..1999
25
when 2000..4999
50
when 5000..9999
75
when 10_000..14_999
100
when 15_000..24_999
150
when 25_000..49_999
200
else
250
end
end
def monthly_tier_amount_cents(customer_count)
monthly_tier_amount(customer_count) * 100
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/recurring_service/recurrence.rb | app/modules/recurring_service/recurrence.rb | # frozen_string_literal: true
module RecurringService::Recurrence
def recurrence_indicator
{
monthly: " a month",
yearly: " a year"
}[recurrence.to_sym]
end
def recurrence_duration
{
monthly: 1.month,
yearly: 1.year
}[recurrence.to_sym]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/media_location/unit.rb | app/modules/media_location/unit.rb | # frozen_string_literal: true
module MediaLocation::Unit
PAGE_NUMBER = "page_number"
SECONDS = "seconds"
PERCENTAGE = "percentage"
def self.all
[
PAGE_NUMBER,
SECONDS,
PERCENTAGE
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/shipping_destination/destinations.rb | app/modules/shipping_destination/destinations.rb | # frozen_string_literal: true
module ShippingDestination::Destinations
# constant referring to all other countries
ELSEWHERE = "ELSEWHERE"
# constants for virtual countries
EUROPE = "EUROPE"
ASIA = "ASIA"
NORTH_AMERICA = "NORTH AMERICA"
VIRTUAL_COUNTRY_CODES = [EUROPE, ASIA, NORTH_AMERICA].freeze
def self.shipping_countries
first_countries = {
"US" => "United States",
ASIA => ASIA.titleize,
EUROPE => EUROPE.titleize,
NORTH_AMERICA => NORTH_AMERICA.titleize,
ELSEWHERE => ELSEWHERE.titleize
}
first_countries.merge!(Compliance::Countries.for_select.reject { |country| Compliance::Countries.blocked?(country[0]) }.to_h)
end
def self.europe_shipping_countries
@_europe_shipping_countries ||=
ISO3166::Country.all
.select { |country| country.continent == "Europe" }
.reject { |country| Compliance::Countries.blocked?(country.alpha2) || Compliance::Countries.risk_physical_blocked?(country.alpha2) }
.map { |country| [country.alpha2, country.common_name] }
.sort_by { |pair| pair.last }
.to_h
end
def self.asia_shipping_countries
@_asia_shipping_countries ||=
ISO3166::Country.all
.select { |country| country.continent == "Asia" }
.reject { |country| Compliance::Countries.blocked?(country.alpha2) || Compliance::Countries.risk_physical_blocked?(country.alpha2) }
.map { |country| [country.alpha2, country.common_name] }
.sort_by { |pair| pair.last }
.to_h
end
def self.north_america_shipping_countries
@_north_america_shipping_countries ||=
ISO3166::Country.all
.select { |country| country.continent == "North America" }
.reject { |country| Compliance::Countries.blocked?(country.alpha2) || Compliance::Countries.risk_physical_blocked?(country.alpha2) }
.map { |country| [country.alpha2, country.common_name] }
.sort_by { |pair| pair.last }
.to_h
end
def self.virtual_countries_for_country_code(country_code)
virtual_countries = []
virtual_countries << ASIA if asia_shipping_countries.include?(country_code)
virtual_countries << EUROPE if europe_shipping_countries.include?(country_code)
virtual_countries << NORTH_AMERICA if north_america_shipping_countries.include?(country_code)
virtual_countries
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/subscription/ping_notification.rb | app/modules/subscription/ping_notification.rb | # frozen_string_literal: true
module Subscription::PingNotification
def payload_for_ping_notification(resource_name: nil, additional_params: {})
payload = {
subscription_id: external_id,
product_id: link.external_id,
product_name: link.name,
user_id: user.try(:external_id),
user_email: email,
purchase_ids: purchases.map(&:external_id),
created_at: created_at.as_json,
charge_occurrence_count:,
recurrence: price.recurrence,
free_trial_ends_at: free_trial_ends_at&.as_json,
resource_name:
}.merge(additional_params)
payload[:custom_fields] = custom_fields.pluck(:name, :value).to_h if custom_fields.present?
payload[:license_key] = license_key if license_key.present?
if resource_name == ResourceSubscription::CANCELLED_RESOURCE_NAME
payload[:cancelled] = true
if cancelled_at.present?
payload[:cancelled_at] = cancelled_at.as_json
if cancelled_by_admin?
payload[:cancelled_by_admin] = true
elsif cancelled_by_buyer?
payload[:cancelled_by_buyer] = true
else
payload[:cancelled_by_seller] = true
end
elsif failed_at.present?
payload[:cancelled_at] = failed_at.as_json
payload[:cancelled_due_to_payment_failures] = true
end
end
if resource_name == ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME
payload[:ended_at] = deactivated_at.as_json
payload[:ended_reason] = termination_reason
end
payload
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/payment/stats.rb | app/modules/payment/stats.rb | # frozen_string_literal: true
module Payment::Stats
def revenue_by_link
# First calculate the revenue per product (i.e. purchase price - affiliate commission - fee)
# based on all the sales in this payout period
# including refunded and charged-back sales.
revenue_by_link = successful_sale_amounts
revenue_by_link.default = 0
# Then deduct the (purchase price - affiliate commission - fee) for chargebacks in this payout period.
chargeback_amounts.each { |link, chargeback_amount| revenue_by_link[link] -= chargeback_amount }
# Then deduct the (refunded amount - refunded affiliate commission) for refunds in this payout period where we didn't waive our fee for the refund.
refund_amounts_with_fee_not_waived.each { |link, refund_amount| revenue_by_link[link] -= refund_amount }
# Then deduct the (refunded amount - refunded affiliate commission - refunded fees) for refunds in this payout period where we waived our fee for the refund.
refund_amounts_with_fee_waived.each { |link, refund_amount| revenue_by_link[link] -= refund_amount }
revenue_by_link
end
private
def successful_sales_grouped_by_product
user.sales
.where(purchase_success_balance_id: balances.map(&:id))
.group("link_id")
end
def chargedback_sales_grouped_by_product
user.sales
.where(purchase_chargeback_balance_id: balances.map(&:id))
.group("link_id")
end
def refunded_sales_grouped_by_product
user.sales
.joins(:refunds)
.joins("INNER JOIN balance_transactions on balance_transactions.refund_id = refunds.id")
.where("balance_transactions.balance_id IN (?)", balances.map(&:id))
.group("link_id")
end
def successful_sale_amounts
successful_sales_grouped_by_product
.sum("price_cents - fee_cents - affiliate_credit_cents")
end
def chargeback_amounts
chargedback_sales_grouped_by_product.sum("price_cents - fee_cents - affiliate_credit_cents")
end
def refund_amounts_with_fee_not_waived
refunded_sales_grouped_by_product
.not_is_refund_chargeback_fee_waived
.sum("refunds.amount_cents - refunds.fee_cents + COALESCE(refunds.json_data->'$.retained_fee_cents', 0) - TRUNCATE(purchases.affiliate_credit_cents * refunds.amount_cents / purchases.price_cents, 0)")
end
def refund_amounts_with_fee_waived
refunded_sales_grouped_by_product
.is_refund_chargeback_fee_waived
.sum("refunds.amount_cents - refunds.fee_cents - TRUNCATE(purchases.affiliate_credit_cents * refunds.amount_cents / purchases.price_cents, 0)")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/targeting.rb | app/modules/purchase/targeting.rb | # frozen_string_literal: true
module Purchase::Targeting
extend ActiveSupport::Concern
included do
scope :by_variant, lambda { |variant_id|
if variant_id.present?
joins("INNER JOIN base_variants_purchases ON base_variants_purchases.purchase_id = purchases.id")
.where("base_variants_purchases.base_variant_id IN (?)", variant_id)
end
}
scope :email_not, ->(emails) { where("purchases.email NOT IN (?)", emails) if emails.present? }
scope :paid_more_than, ->(more_than_cents) { where("purchases.price_cents > ?", more_than_cents) if more_than_cents.present? }
scope :paid_less_than, ->(less_than_cents) { where("purchases.price_cents < ?", less_than_cents) if less_than_cents.present? }
scope :country_bought_from, ->(country) { where("purchases.country IN (?) OR (purchases.country IS NULL AND purchases.ip_country IN (?))", Compliance::Countries.historical_names(country), Compliance::Countries.historical_names(country)) if country.present? }
scope :by_external_variant_ids_or_products, ->(external_variant_ids, product_ids) do
if external_variant_ids.present?
variant_ids = BaseVariant.by_external_ids(external_variant_ids).pluck(:id)
by_variants_sql = by_variant(variant_ids).to_sql
by_products_sql = where(link_id: product_ids).to_sql
sub_query = "(#{by_variants_sql}) UNION (#{by_products_sql})"
where("purchases.id IN (SELECT id FROM (#{sub_query}) AS t_purchases)")
else
for_products(product_ids)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/risk.rb | app/modules/purchase/risk.rb | # frozen_string_literal: true
module Purchase::Risk
IP_PROXY_THRESHOLD = 2
CHECK_FOR_FRAUD_TIMEOUT_SECONDS = 4
def check_for_fraud
Timeout.timeout(CHECK_FOR_FRAUD_TIMEOUT_SECONDS) do
check_for_past_blocked_email_domains
return if errors.present?
check_for_past_blocked_guids
return if errors.present?
check_for_past_chargebacks
return if errors.present?
check_for_past_fraudulent_buyers
return if errors.present?
check_for_past_fraudulent_ips
end
rescue Timeout::Error => e
# Bugsnag.notify(e)
logger.info("Check for fraud: Could not check for fraud for purchase #{id}. Exception: #{e.message}")
nil
end
def find_past_chargebacked_purchases
@_find_past_chargebacked_purchases_for_purchases ||= begin
past_email_purchases = Purchase.where(email:).chargedback.not_chargeback_reversed.order(chargeback_date: :desc)
past_guid_purchases = Purchase.where("browser_guid is not null").where(browser_guid:).chargedback.not_chargeback_reversed.order(chargeback_date: :desc)
past_email_purchases + past_guid_purchases
end
end
private
def vague_error_message
record = is_gift_receiver_purchase ? gift_received.gifter_purchase : self
if record.free_purchase?
"The transaction could not complete."
else
"Your card was not charged."
end
end
def check_for_past_blocked_email_domains
return unless blocked_by_email_domain_if_fraudulent_transaction?
self.error_code = PurchaseErrorCode::BLOCKED_EMAIL_DOMAIN
errors.add :base, vague_error_message
end
def check_for_past_blocked_guids
return unless past_blocked_object(browser_guid)
self.error_code = PurchaseErrorCode::BLOCKED_BROWSER_GUID
errors.add :base, "Your card was not charged. Please try again on a different browser and/or internet connection."
end
def check_for_past_chargebacks
return if find_past_chargebacked_purchases.none?
self.error_code = PurchaseErrorCode::BUYER_CHARGED_BACK
errors.add :base, "There's an active chargeback on one of your past Gumroad purchases. Please withdraw it by contacting your charge processor and try again later."
end
def check_for_past_fraudulent_buyers
buyer_user = User.find_by(email:)
return unless buyer_user.try(:suspended_for_fraud?)
self.error_code = PurchaseErrorCode::SUSPENDED_BUYER
errors.add :base, "Your card was not charged."
end
def check_for_past_fraudulent_ips
return if is_recurring_subscription_charge
return if free_purchase?
return if Feature.inactive?(:purchase_check_for_fraudulent_ips)
buyer_ip_addresses = User.where(email: blockable_emails_if_fraudulent_transaction).pluck(:current_sign_in_ip, :last_sign_in_ip, :account_created_ip).flatten.compact.uniq
ip_addresses_to_check = [seller.current_sign_in_ip, seller.last_sign_in_ip, seller.account_created_ip, ip_address].compact.concat(buyer_ip_addresses)
return if BlockedObject.find_active_objects(ip_addresses_to_check).count == 0
return if BlockedObject.find_active_objects(ip_addresses_to_check[0..2]).present? && seller.compliant?
self.error_code = PurchaseErrorCode::BLOCKED_IP_ADDRESS
errors.add :base, "Your card was not charged. Please try again on a different browser and/or internet connection."
end
def past_blocked_object(object)
object.present? && BlockedObject.find_active_object(object).present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/card_country_source.rb | app/modules/purchase/card_country_source.rb | # frozen_string_literal: true
module Purchase::CardCountrySource
STRIPE = "stripe"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/refundable.rb | app/modules/purchase/refundable.rb | # frozen_string_literal: true
class Purchase
module Refundable
# * amount - the amount to refund (out of `Purchase#price_cents`, VAT-exclusive). VAT will be refunded proportinally to this amount.
def refund!(refunding_user_id:, amount: nil)
if amount.blank?
refund_and_save!(refunding_user_id)
else
refund_amount_cents = refunding_amount_cents(amount)
if refund_amount_cents > amount_refundable_cents
errors.add :base, "Refund amount cannot be greater than the purchase price."
false
elsif refund_amount_cents == price_cents || refund_amount_cents == amount_refundable_cents
# User attempted a partial refund with same amount as total purchase or
# remaining refundable amount.
# Short-circuit this, so we don't need to handle edge cases about taxes
refund_and_save!(refunding_user_id)
else
refund_and_save!(refunding_user_id, amount_cents: refund_amount_cents)
end
end
end
# Refunds purchase through charge processor if price > 0. Is idempotent. Returns false on failure.
# refunding_user_id can't be enforced from console, in which case it will be nil
#
# * amount - the amount to refund (out of `Purchase#price_cents`, VAT-exclusive). VAT will be refunded proportinally to this amount.
def refund_and_save!(refunding_user_id, amount_cents: nil, is_for_fraud: false)
return if stripe_transaction_id.blank? || stripe_refunded || amount_refundable_cents <= 0
if (merchant_account.is_a_stripe_connect_account? && !merchant_account.active?) ||
(paypal_charge_processor? &&
!seller_native_paypal_payment_enabled?)
errors.add :base, "We cannot refund this sale because you have disconnected the associated payment account on " \
"#{charge_processor_id.titleize}. Please connect it and try again."
return false
end
if refunding_user_id.blank? || !User.find(refunding_user_id)&.is_team_member?
if seller.refunds_disabled?
errors.add :base, "Refunds are temporarily disabled in your account."
return false
end
amount_cents_to_refund = amount_cents.presence || amount_refundable_cents
if amount_cents_to_refund > seller.unpaid_balance_cents && charged_using_gumroad_merchant_account?
errors.add :base, "Your balance is insufficient to process this refund."
return false
end
end
begin
logger.info("Refunding purchase: #{id} and amount_cents: #{amount_cents} , amount_refundable_cents: #{amount_refundable_cents}")
# In case of combined charge with multiple purchases, if amount_cents is absent i.e. it is a full refund,
# set amount cents equal to refundable_amount_cents
# which would be price_cents if no partial refund has been issued yet
# This would make a partial refund equal to amount cents on the Stripe/PayPal charge,
# as without amount_cents set, Stripe/PayPal would refund the entire charge which contains multiple purchases
if is_part_of_combined_charge? && charge&.purchases&.many? && amount_cents.blank?
amount_cents = amount_refundable_cents
end
# If this is a partial refund and we have previously charged VAT, calculate a proportional amount of VAT to refund in addition to `amount_cents`
gross_amount_cents = if amount_cents.present? && gumroad_responsible_for_tax?
proportional_tax_cents = (amount_cents * gumroad_tax_cents / price_cents.to_f).floor
# Some VAT could have been refunded separately from the purchase price and we may not have enough refundable VAT left
tax_cents = [proportional_tax_cents, gumroad_tax_refundable_cents].min
amount_cents + tax_cents
else
amount_cents
end
paypal_order_purchase_unit_refund = true if paypal_order_id
charge_refund = ChargeProcessor.refund!(charge_processor_id,
stripe_transaction_id,
amount_cents: gross_amount_cents,
merchant_account:,
reverse_transfer: !chargedback? || !chargeback_reversed,
paypal_order_purchase_unit_refund:,
is_for_fraud:)
logger.info("Refunding purchase: #{id} completed with ID: #{charge_refund.id}, Flow of Funds: #{charge_refund.flow_of_funds.to_h}")
purchase_event = Event.where(purchase_id: id, event_name: "purchase").last
unless purchase_event.nil?
Event.create(
event_name: "refund",
purchase_id: purchase_event.purchase_id,
browser_fingerprint: purchase_event.browser_fingerprint,
ip_address: purchase_event.ip_address
)
end
if charge_refund.flow_of_funds.nil? && StripeChargeProcessor.charge_processor_id != charge_processor_id
charge_refund.flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, -(gross_amount_cents.presence || gross_amount_refundable_cents))
end
refund_purchase!(charge_refund.flow_of_funds, refunding_user_id, charge_refund.refund, is_for_fraud)
rescue ChargeProcessorAlreadyRefundedError => e
logger.error "Charge was already refunded in purchase: #{external_id}. Response: #{e.message}"
false
rescue ChargeProcessorInsufficientFundsError => e
logger.error "Creator's PayPal account does not have sufficient funds to refund purchase: #{external_id}. Response: #{e.message}"
errors.add :base, "Your PayPal account does not have sufficient funds to make this refund."
false
rescue ChargeProcessorInvalidRequestError => e
logger.error "Charge refund encountered an invalid request error in purchase: #{external_id}. Response: #{e.message}. #{e.backtrace_locations}"
false
rescue ChargeProcessorUnavailableError => e
logger.error "Charge processor unavailable in purchase: #{external_id}. Response: #{e.message}"
errors.add :base, "There is a temporary problem. Try to refund later."
false
end
end
def build_refund(gross_refund_amount: nil, refunding_user_id:)
if stripe_partially_refunded_was && stripe_refunded
build_partial_full_refund(refunding_user_id:)
elsif gross_refund_amount == total_transaction_cents
build_full_refund(refunding_user_id:)
else
build_partial_refund(gross_refund_amount: (gross_refund_amount || gross_amount_refundable_cents),
refunding_user_id:)
end
end
# Short-circuit when we want to refund full amount
def build_full_refund(refunding_user_id:)
Refund.new(total_transaction_cents:,
amount_cents: price_cents,
creator_tax_cents: tax_cents,
fee_cents:,
gumroad_tax_cents: gumroad_tax_refundable_cents,
refunding_user_id:)
end
# Short-circuit when we want to refund fully remaining amount
def build_partial_full_refund(refunding_user_id:)
new_refund_params = refundable_amounts
return nil unless new_refund_params
new_refund_params[:refunding_user_id] = refunding_user_id
new_refund = Refund.new(new_refund_params)
if new_refund.total_transaction_cents.negative? || new_refund.amount_cents.negative?
nil
else
new_refund
end
end
def build_partial_refund(gross_refund_amount: nil, refunding_user_id:)
return nil if gross_refund_amount <= 0
return nil if gross_refund_amount > gross_amount_refundable_cents
creator_tax_cents_refunded = 0
gumroad_tax_cents_refunded = 0
refund_amount_cents = gross_refund_amount
if gumroad_responsible_for_tax? && gumroad_tax_refundable_cents > 0
tax_rate = gumroad_tax_cents / total_transaction_cents.to_f
tax_refund_amount = (gross_refund_amount * tax_rate).floor
# VAT could have been refunded separately from the purchase price (`Purchase#refund_gumroad_taxes!`) and we may not have enough refundable VAT left
gumroad_tax_cents_refunded = [tax_refund_amount, gumroad_tax_refundable_cents].min
refund_amount_cents = gross_refund_amount - gumroad_tax_cents_refunded
end
if seller_responsible_for_tax?
tax_rate = tax_cents / total_transaction_cents.to_f
creator_tax_cents_refunded = (gross_refund_amount * tax_rate).floor
end
fee_refund_cents = ((fee_cents.to_f / price_cents.to_f) * refund_amount_cents).floor
Refund.new(total_transaction_cents: gross_refund_amount,
amount_cents: refund_amount_cents,
fee_cents: fee_refund_cents,
creator_tax_cents: creator_tax_cents_refunded,
gumroad_tax_cents: gumroad_tax_cents_refunded,
refunding_user_id:)
end
end
# refunding_user_id can't be enforced from console (no current user), in which case it will be nil
def refund_purchase!(flow_of_funds, refunding_user_id, stripe_refund = nil, is_for_fraud = false)
funds_refunded = flow_of_funds.issued_amount.cents.abs
partially_refunded_previously = self.stripe_partially_refunded
ActiveRecord::Base.transaction do
self.stripe_refunded = (gross_amount_refunded_cents + funds_refunded) >= total_transaction_cents
self.stripe_partially_refunded = !self.stripe_refunded
vat_already_refunded = gumroad_tax_cents > 0 && gumroad_tax_cents == gumroad_tax_refunded_cents
refund = build_refund(gross_refund_amount: funds_refunded, refunding_user_id:)
unless refund.present?
logger.error "Failed creating a refund: #{self.inspect} :: flow_of_funds :: #{flow_of_funds.inspect} :: stripe_refund :: #{stripe_refund}"
errors.add :base, "The purchase could not be refunded. Please check the refund amount."
return false
end
if stripe_refund
refund.status = stripe_refund.status
refund.processor_refund_id = stripe_refund.id
end
refund.is_for_fraud = is_for_fraud
refunds << refund
self.is_refund_chargeback_fee_waived = !charged_using_gumroad_merchant_account? || is_for_fraud
mark_giftee_purchase_as_refunded(is_partially_refunded: self.stripe_partially_refunded?) if is_gift_sender_purchase
subscription.cancel_immediately_if_pending_cancellation! if subscription.present?
decrement_balance_for_refund_or_chargeback!(flow_of_funds, refund:)
save!
reverse_the_transfer_made_for_dispute_win! if chargedback? && chargeback_reversed
reverse_excess_amount_from_stripe_transfer(refund:) if stripe_partially_refunded && vat_already_refunded
debit_processor_fee_from_merchant_account!(refund) unless is_refund_chargeback_fee_waived
Credit.create_for_vat_exclusive_refund!(refund:) if paypal_order_id.present? || merchant_account&.is_a_stripe_connect_account?
subscription.original_purchase.update!(should_exclude_product_review: true) if subscription&.should_exclude_product_review_on_charge_reversal?
send_refunded_notification_webhook
if partially_refunded_previously || self.stripe_partially_refunded
CustomerMailer.partial_refund(email, link.id, id, funds_refunded, formatted_refund_state).deliver_later(queue: "critical")
else
CustomerMailer.refund(email, link.id, id).deliver_later(queue: "critical")
end
# Those callbacks are manually invoked because of a rails issue: https://github.com/rails/rails/issues/39972
update_creator_analytics_cache(force: true)
# Refunding impacts many of the ES document fields,
# including but not limited to: amount_refunded_cents, fee_refunded_cents, affiliate_credit.*, etc.
# Reindexing the entire document is simpler, and future-proof with regards to new fields added later.
send_to_elasticsearch("index")
enqueue_update_sales_related_products_infos_job(false)
unless refund.user&.is_team_member?
# Check for low balance and put the creator on probation
LowBalanceFraudCheckWorker.perform_in(5.seconds, id)
end
true
end
end
def refund_partial_purchase!(gross_refund_amount_cents, refunding_user_id, processor_refund_id: nil)
partially_refunded_previously = self.stripe_partially_refunded
ActiveRecord::Base.transaction do
if (gross_amount_refunded_cents + gross_refund_amount_cents) >= total_transaction_cents
self.stripe_partially_refunded = false
self.stripe_refunded = true
else
self.stripe_refunded = false
self.stripe_partially_refunded = true
end
self.is_refund_chargeback_fee_waived = !charged_using_gumroad_merchant_account?
if partially_refunded_previously && stripe_refunded
refund = build_partial_full_refund(refunding_user_id:)
else
refund = build_refund(gross_refund_amount: gross_refund_amount_cents,
refunding_user_id:)
end
if refund.present?
refund.processor_refund_id = processor_refund_id
refunds << refund
end
save!
Credit.create_for_vat_exclusive_refund!(refund:) if paypal_order_id.present? || merchant_account&.is_a_stripe_connect_account?
debit_processor_fee_from_merchant_account!(refund) unless is_refund_chargeback_fee_waived
CustomerMailer.partial_refund(email, link.id, id, gross_refund_amount_cents, formatted_refund_state).deliver_later(queue: "critical")
true
end
end
def refund_gumroad_taxes!(refunding_user_id:, note: nil, business_vat_id: nil)
gumroad_tax_refundable_cents = self.gumroad_tax_refundable_cents
return false if stripe_refunded || gumroad_tax_refundable_cents <= 0
begin
logger.info("Refunding purchase: #{id} gumroad taxes: #{self.gumroad_tax_refundable_cents}")
charge_refund = ChargeProcessor.refund!(charge_processor_id, stripe_transaction_id,
amount_cents: gumroad_tax_refundable_cents,
reverse_transfer: false,
merchant_account:,
paypal_order_purchase_unit_refund: paypal_order_id.present?)
logger.info("Refunding purchase: #{id} completed with ID: #{charge_refund.id}, Flow of Funds: #{charge_refund.flow_of_funds.to_h}")
ActiveRecord::Base.transaction do
refund = Refund.new(total_transaction_cents: gumroad_tax_refundable_cents,
amount_cents: 0,
creator_tax_cents: 0,
fee_cents: 0,
gumroad_tax_cents: gumroad_tax_refundable_cents,
refunding_user_id:)
refund.note = note
refund.business_vat_id = business_vat_id
refund.processor_refund_id = charge_refund.id
refunds << refund
save!
Credit.create_for_vat_refund!(refund:) if paypal_order_id.present? || merchant_account&.is_a_stripe_connect_account?
end
true
rescue ChargeProcessorAlreadyRefundedError => e
logger.error "Charge was already refunded in purchase: #{external_id}. Response: #{e.message}"
false
rescue ChargeProcessorInvalidRequestError
false
rescue ChargeProcessorUnavailableError => e
logger.error "Error while refunding a charge: #{e.message} in purchase: #{external_id}"
errors.add :base, "There is a temporary problem. Try to refund later."
false
end
end
def refund_for_fraud_and_block_buyer!(refunding_user_id)
refund_for_fraud!(refunding_user_id)
block_buyer!(blocking_user_id: refunding_user_id)
end
def refund_for_fraud!(refunding_user_id)
refund_and_save!(refunding_user_id, is_for_fraud: true)
subscription.cancel_effective_immediately! if subscription.present? && !subscription.deactivated?
ContactingCreatorMailer.purchase_refunded_for_fraud(id).deliver_later(queue: "default") unless seller.suspended?
end
def formatted_refund_state
return "" unless stripe_partially_refunded || stripe_refunded
stripe_partially_refunded ? "partially" : "fully"
end
def within_refund_policy_timeframe?
return false unless successful? || gift_receiver_purchase_successful? || not_charged?
return false if refunded? || chargedback?
refund_policy = purchase_refund_policy
return false unless refund_policy.present?
max_days = refund_policy.max_refund_period_in_days
return false if max_days.nil? || max_days <= 0
created_at > max_days.days.ago
end
private
def refundable_amounts
amounts_query = "COALESCE(SUM(total_transaction_cents), 0) AS tt_cents, COALESCE(SUM(amount_cents), 0) AS p_cents, " \
"COALESCE(SUM(creator_tax_cents), 0) AS ct_cents, COALESCE(SUM(gumroad_tax_cents), 0) as gt_cents," \
"COALESCE(SUM(fee_cents), 0) AS ft_cents"
existing_refunds = refunds.select(amounts_query).first
return unless existing_refunds
{ total_transaction_cents: (total_transaction_cents - existing_refunds.tt_cents),
amount_cents: (price_cents - existing_refunds.p_cents),
fee_cents: (fee_cents - existing_refunds.ft_cents),
creator_tax_cents: (tax_cents - existing_refunds.ct_cents),
gumroad_tax_cents: (gumroad_tax_cents - existing_refunds.gt_cents) }
end
def reverse_the_transfer_made_for_dispute_win!
return unless merchant_account&.holder_of_funds == HolderOfFunds::STRIPE
return unless dispute&.won_at.present?
transfers = Stripe::Transfer.list({ destination: merchant_account.charge_processor_merchant_id, created: { gte: dispute.won_at.to_i - 60000 }, limit: 100 })
transfer = transfers.select { |tr| tr["description"]&.include?("Dispute #{dispute.charge_processor_dispute_id} won") }.first
Stripe::Transfer.create_reversal(transfer.id, { amount: amount_refundable_cents }) if transfer.present?
end
def debit_processor_fee_from_merchant_account!(refund)
Credit.create_for_refund_fee_retention!(refund:)
end
def reverse_excess_amount_from_stripe_transfer(refund:)
return unless merchant_account&.holder_of_funds == HolderOfFunds::STRIPE
return unless refund.purchase.gumroad_tax_cents > 0 && refund.purchase.gumroad_tax_cents == refund.purchase.gumroad_tax_refunded_cents
amount_cents_to_be_reversed_usd = refund.balance_transactions.where(user_id: refund.purchase.seller_id).last.issued_amount_net_cents.abs
stripe_charge = Stripe::Charge.retrieve(refund.purchase.stripe_transaction_id)
transfer = Stripe::Transfer.retrieve(id: stripe_charge.transfer)
amount_cents_already_reversed_usd = transfer.reversals.data.find { |d| d.source_refund == refund.processor_refund_id }.amount.abs
return unless amount_cents_already_reversed_usd < amount_cents_to_be_reversed_usd
reversal_amount_cents_usd = amount_cents_to_be_reversed_usd - amount_cents_already_reversed_usd
transfer_reversal = Stripe::Transfer.create_reversal(transfer.id, { amount: reversal_amount_cents_usd })
destination_refund = Stripe::Refund.retrieve(transfer_reversal.destination_payment_refund,
stripe_account: refund.purchase.merchant_account.charge_processor_merchant_id)
destination_balance_transaction = Stripe::BalanceTransaction.retrieve(destination_refund.balance_transaction,
stripe_account: refund.purchase.merchant_account.charge_processor_merchant_id)
Credit.create_for_partial_refund_transfer_reversal!(amount_cents_usd: -reversal_amount_cents_usd,
amount_cents_holding_currency: -destination_balance_transaction.net.abs,
merchant_account: refund.purchase.merchant_account)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/reviews.rb | app/modules/purchase/reviews.rb | # frozen_string_literal: true
module Purchase::Reviews
extend ActiveSupport::Concern
included do
COUNTS_REVIEWS_STATES = %w[successful gift_receiver_purchase_successful not_charged]
has_one :product_review
after_save :update_product_review_stat
# Important: The logic needs to be the same as the one in `#allows_review_to_be_counted?`
scope :allowing_reviews_to_be_counted, -> {
where(purchase_state: COUNTS_REVIEWS_STATES).
exclude_not_charged_except_free_trial.
not_fully_refunded.
not_chargedback.
not_subscription_or_original_purchase.
not_is_gift_sender_purchase.
not_should_exclude_product_review.
not_access_revoked_or_is_paid.
not_is_bundle_purchase.
not_is_commission_completion_purchase
}
end
def original_product_review
purchase = is_gift_sender_purchase? ? gift_given&.giftee_purchase : self
purchase&.true_original_purchase&.product_review
end
def post_review(rating:, message: nil, video_options: {})
review = original_product_review || true_original_purchase.build_product_review(link:)
ProductReview::UpdateService.new(review, rating:, message:, video_options:).update
end
# Important: The logic needs to be the same as the one in the scope `allowing_reviews_to_be_counted`
def allows_review_to_be_counted?
allows_reviews(permit_recurring_charges: false)
end
def allows_review?
allows_reviews(permit_recurring_charges: true)
end
private
def allows_reviews(permit_recurring_charges:)
allowed = purchase_state.in?(COUNTS_REVIEWS_STATES)
allowed &= !should_exclude_product_review?
allowed &= !not_charged_and_not_free_trial?
allowed &= not_is_gift_sender_purchase
allowed &= !stripe_refunded?
allowed &= chargeback_date.nil?
allowed &= subscription_id.nil? || is_original_subscription_purchase? unless permit_recurring_charges
allowed &= !is_access_revoked || paid?
allowed &= not_is_bundle_purchase
allowed &= not_is_commission_completion_purchase
allowed
end
def update_product_review_stat
return if saved_changes.blank? || original_product_review.blank? || true_original_purchase != self
link.update_review_stat_via_purchase_changes(saved_changes, product_review: original_product_review)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/ping_notification.rb | app/modules/purchase/ping_notification.rb | # frozen_string_literal: true
module Purchase::PingNotification
def payload_for_ping_notification(url_parameters: nil, resource_name: nil)
# general_permalink was being sent as "permalink' which is wrong because it's not a full url unlike the name suggests.
# Consider it deprecated; it's removed from the ping docs and replaced with product_permalink, which is a url.
payload = {
seller_id: ObfuscateIds.encrypt(seller.id),
product_id: ObfuscateIds.encrypt(link.id),
product_name: link.name,
permalink: link.general_permalink,
product_permalink: link.long_url,
short_product_id: link.unique_permalink,
email:,
price: price_cents,
gumroad_fee: fee_cents,
currency: link.price_currency_type,
quantity:,
discover_fee_charged: was_discover_fee_charged?,
can_contact: can_contact?,
referrer:,
card: {
visual: card_visual,
type: card_type,
# legacy params
bin: nil,
expiry_month: nil,
expiry_year: nil
}
}
payload[:order_number] = external_id_numeric
payload[:sale_id] = ObfuscateIds.encrypt(id)
payload[:sale_timestamp] = created_at.as_json
payload[:full_name] = full_name if full_name.present?
payload[:purchaser_id] = purchaser.external_id if purchaser
payload[:subscription_id] = subscription.external_id if subscription.present?
payload[:affiliate_credit_amount_cents] = affiliate_credit_cents if affiliate_credit.present?
payload[:url_params] = url_parameters if url_parameters.present?
payload[:variants] = variant_names_hash if variant_names_hash.present?
payload[:offer_code] = offer_code.code if offer_code.present?
payload[:test] = true if purchaser == seller
payload[:is_recurring_charge] = true if is_recurring_subscription_charge
payload[:is_preorder_authorization] = true if is_preorder_authorization
payload.merge!(shipping_information) if shipping_information.present?
payload[:shipping_information] = shipping_information if shipping_information.present?
custom_fields.each { |field| payload[field[:name]] = field[:value] }
custom_fields_payload = if custom_fields.present?
custom_fields.pluck(:name, :value).to_h
elsif subscription&.custom_fields.present?
subscription.custom_fields.pluck(:name, :value).to_h
end
payload[:custom_fields] = custom_fields_payload if custom_fields_payload.present?
payload[:license_key] = license_key if license_key.present?
payload[:is_multiseat_license] = is_multiseat_license? if license_key.present? && subscription.present?
payload[:ip_country] = ip_country if ip_country.present?
payload[:shipping_rate] = shipping_cents if link.is_physical
payload[:recurrence] = subscription.recurrence if subscription.present?
payload[:affiliate] = affiliate.affiliate_user.form_email if affiliate.present?
payload[:is_gift_receiver_purchase] = is_gift_receiver_purchase?
if is_gift_receiver_purchase?
payload[:gift_price] = gift.gifter_purchase.price_cents
payload[:gifter_email] = gift.gifter_purchase.email
end
if link.skus_enabled || link.is_physical
# Hack for accutrak (accuhack?)
payload[:sku_id] = sku_custom_name_or_external_id
# Hack for printful (hackful?)
payload[:original_sku_id] = sku.external_id if sku.try(:custom_sku).present?
end
payload[:refunded] = stripe_refunded.present?
payload[:resource_name] = resource_name if resource_name.present?
payload[:disputed] = chargedback?
payload[:dispute_won] = chargeback_reversed?
Rails.logger.info("payload_for_ping_notification #{payload.inspect}")
payload
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/completion_handler.rb | app/modules/purchase/completion_handler.rb | # frozen_string_literal: true
module Purchase::CompletionHandler
# Makes sure that a block of code that creates an in_progress purchase eventually transitions
# that purchase to a completing state, otherwise this method marks the purchase as failed.
def ensure_completion
yield
ensure
mark_failed! if persisted? && in_progress? && (!charge_intent&.is_a?(StripeChargeIntent) || !(charge_intent&.processing? || charge_intent&.requires_action?))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase/accounting.rb | app/modules/purchase/accounting.rb | # frozen_string_literal: true
##
# A collection of methods to help with accounting calculations
##
class Purchase
module Accounting
# returns price in USD. 0.15 means 15 cents
def price_dollars
convert_cents_to_dollars(price_cents)
end
def variant_extra_cost_dollars
convert_cents_to_dollars(variant_extra_cost)
end
def tax_dollars
convert_cents_to_dollars(gumroad_responsible_for_tax? ? gumroad_tax_cents : tax_cents)
end
def shipping_dollars
convert_cents_to_dollars(shipping_cents)
end
def fee_dollars
convert_cents_to_dollars(fee_cents)
end
def processor_fee_dollars
convert_cents_to_dollars(processor_fee_cents)
end
def affiliate_credit_dollars
convert_cents_to_dollars(affiliate_credit_cents)
end
# seller's revenue less our fee (assumes we take cut on gross)
def net_total
convert_cents_to_dollars(price_cents - fee_cents)
end
def sub_total
convert_cents_to_dollars(price_cents - tax_cents - shipping_cents)
end
def amount_refunded_dollars
convert_cents_to_dollars(amount_refunded_cents)
end
private
# returns US zip code (without +4) only, otherwise nil
def best_guess_zip
# trust the user if they provided a zip in a format we understand
return parsed_zip_from_user_input if parsed_zip_from_user_input
# only use geoip if we are in the united states
geo_ip = GeoIp.lookup(ip_address)
return nil unless geo_ip.try(:country_code) == "US"
geo_ip.try(:postal_code)
end
# returns US zip code from parsing user input (via shipping form), otherwise nil
# sometimes users will provide a zip+4 or add spaces on either side of zip (or in between zip+4)
def parsed_zip_from_user_input
zip_code.scan(/\d{5}/)[0] if zip_code && country == "United States" && zip_code =~ /^\s*\d{5}([\s-]?\d{4})?\s*$/
end
def convert_cents_to_dollars(cents)
(cents.to_f / 100).round(2)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/variant/prices.rb | app/modules/variant/prices.rb | # frozen_string_literal: true
module Variant::Prices
include BasePrice::Shared
delegate :price_currency_type,
:single_unit_currency?,
:enqueue_index_update_for, to: :link
def save_recurring_prices!(recurrence_price_values)
ActiveRecord::Base.transaction do
super(recurrence_price_values)
# create prices for product with price_cents == 0
product_recurrence_price_values = recurrence_price_values.each_with_object({}) do |(recurrence, recurrence_attributes), values|
product_recurrence_attributes = recurrence_attributes.dup
# TODO: :product_edit_react cleanup
product_recurrence_attributes[:price] = "0" if recurrence_attributes[:price].present?
product_recurrence_attributes[:price_cents] = 0 if recurrence_attributes[:price_cents].present?
product_recurrence_attributes[:suggested_price] = "0" if recurrence_attributes[:suggested_price].present?
product_recurrence_attributes[:suggested_price_cents] = 0 if recurrence_attributes[:suggested_price_cents].present?
values[recurrence] = product_recurrence_attributes
end
link.save_recurring_prices!(product_recurrence_price_values)
end
end
def set_customizable_price
return unless link && link.is_tiered_membership
return if prices.alive.length == 0 || prices.alive.where("price_cents > 0").exists?
update_column(:customizable_price, true)
end
def price_must_be_within_range
return unless variant_category.present? && link.present?
super
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/chile_bank_account/account_type.rb | app/modules/chile_bank_account/account_type.rb | # frozen_string_literal: true
module ChileBankAccount::AccountType
CHECKING = "checking"
SAVINGS = "savings"
def self.all
[
CHECKING,
SAVINGS
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/post/caching.rb | app/modules/post/caching.rb | # frozen_string_literal: true
module Post::Caching
def key_for_cache(key)
"#{key}_for_installment_#{id}"
end
def invalidate_cache(key)
Rails.cache.delete(key_for_cache(key))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/user_compliance_info/business_types.rb | app/modules/user_compliance_info/business_types.rb | # frozen_string_literal: true
module UserComplianceInfo::BusinessTypes
LLC = "llc"
PARTNERSHIP = "partnership"
NON_PROFIT = "profit"
REGISTERED_CHARITY = "registered_charity"
SOLE_PROPRIETORSHIP = "sole_proprietorship"
CORPORATION = "corporation"
def self.all
[
LLC,
PARTNERSHIP,
NON_PROFIT,
SOLE_PROPRIETORSHIP,
CORPORATION
]
end
# https://payable.com/taxes/part-2-how-to-set-up-a-full-form-import-1099-misc-1099-k
# ‘INDIVIDUAL’, ‘CORPORATION’, ‘LLC_SINGLE’, LLC_C_CORP’, ‘LLC_S_CORP’, ‘LLC_PARTNER’, ‘C_CORP’, ‘S_CORP’, ‘PARTNERSHIP’, ’NON_PROFIT’.
def payable_type_map
{ LLC => "LLC_PARTNER",
PARTNERSHIP => "PARTNERSHIP",
NON_PROFIT => "NON_PROFIT",
SOLE_PROPRIETORSHIP => "INDIVIDUAL",
CORPORATION => "CORPORATION"
}
end
BUSINESS_TYPES_UAE = {
"llc" => "LLC",
"sole_establishment" => "Sole Establishment",
"free_zone_llc" => "Free Zone LLC",
"free_zone_establishment" => "Free Zone Establishment"
}.freeze
BUSINESS_TYPES_INDIA = {
"sole_proprietorship" => "Sole Proprietorship",
"partnership" => "Partnership",
"llp" => "Limited Liability Partnership (LLP)",
"pvt_ltd" => "Private Limited Company (Pvt Ltd)",
"pub_ltd" => "Public Limited Company (Ltd)",
"opc" => "One-Person Company (OPC)",
"jvc" => "Joint-Venture Company (JVC)",
"ngo" => "Non-Government Organization (NGO)"
}.freeze
BUSINESS_TYPES_CANADA = {
"private_corporation" => "Private Corporation",
"private_partnership" => "Private Partnership",
"sole_proprietorship" => "Sole Proprietorship",
"public_corporation" => "Public Corporation",
"non_profit" => "Non Profit",
"registered_charity" => "Registered Charity"
}.freeze
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/currency.rb | app/business/payments/currency.rb | # frozen_string_literal: true
module Currency
# These currencies can be used as account's default currency and to set product prices,
# along with creating Stripe Connect accounts and making payouts.
CURRENCY_CHOICES.each do |currency_type, _currency_hash|
const_set(currency_type.upcase, currency_type.downcase)
end
# These currencies are only used for creating Stripe Connect accounts and making payouts.
# These cannot be used as account's default currency or to set product prices.
# Currency conversion helpers do not support for these currencies.
THB = "thb"
BAM = "bam"
BDT = "bdt"
BTN = "btn"
LAK = "lak"
MZN = "mzn"
DKK = "dkk"
HUF = "huf"
AED = "aed"
TTD = "ttd"
AOA = "aoa"
RON = "ron"
SEK = "sek"
MXN = "mxn"
ARS = "ars"
NOK = "nok"
BWP = "bwp"
PEN = "pen"
VND = "vnd"
XCD = "xcd"
TZS = "tzs"
NAD = "nad"
IDR = "idr"
CRC = "crc"
RWF = "rwf"
CLP = "clp"
PKR = "pkr"
TRY = "try"
MAD = "mad"
RSD = "rsd"
KES = "kes"
EGP = "egp"
COP = "cop"
SAR = "sar"
KZT = "kzt"
MYR = "myr"
UYU = "uyu"
MUR = "mur"
JMD = "jmd"
OMR = "omr"
DOP = "dop"
UZS = "uzs"
BOB = "bob"
TND = "tnd"
NGN = "ngn"
AZN = "azn"
JOD = "jod"
BHD = "bhd"
ALL = "all"
MDL = "mdl"
MKD = "mkd"
SVC = "svc"
MGA = "mga"
PYG = "pyg"
GHS = "ghs"
AMD = "amd"
LKR = "lkr"
KWD = "kwd"
QAR = "qar"
BSD = "bsd"
ETB = "etb"
BND = "bnd"
GYD = "gyd"
GTQ = "gtq"
XOF = "xof"
KHR = "khr"
MNT = "mnt"
XAF = "xaf"
DZD = "dzd"
MOP = "mop"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/payouts/payouts.rb | app/business/payments/payouts/payouts.rb | # frozen_string_literal: true
class Payouts
extend ActionView::Helpers::NumberHelper
MIN_AMOUNT_CENTS = 10_00
PAYOUT_TYPE_STANDARD = "standard"
PAYOUT_TYPE_INSTANT = "instant"
def self.is_user_payable(user, date, processor_type: nil, add_comment: false, from_admin: false, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
payout_date = Time.current.to_fs(:formatted_date_full_month)
unless user.compliant? || from_admin
reason = user.not_reviewed? ? "under review" : "not compliant"
user.add_payout_note(content: "Payout on #{payout_date} was skipped because the account was #{reason}.") if add_comment
return false
end
if user.payouts_paused?
payouts_paused_by = user.payouts_paused_by_source == User::PAYOUT_PAUSE_SOURCE_STRIPE ? "payout processor" : user.payouts_paused_by_source
user.add_payout_note(content: "Payout on #{payout_date} was skipped because payouts on the account were paused by the #{payouts_paused_by}.") if add_comment
return false
end
amount_payable = user.unpaid_balance_cents_up_to_date(date)
account_balance = amount_payable + user.paid_payments_cents_for_date(date)
if account_balance < user.minimum_payout_amount_cents
if add_comment && account_balance > 0
current_balance = user.formatted_dollar_amount(account_balance, with_currency: true)
minimum_balance = user.formatted_dollar_amount(user.minimum_payout_amount_cents, with_currency: true)
user.add_payout_note(content: "Payout on #{payout_date} was skipped because the account balance #{current_balance} was less than the minimum payout amount of #{minimum_balance}.") if add_comment
end
is_payable_from_admin = from_admin && account_balance > 0 && user.unpaid_balance_cents_up_to_date_held_by_gumroad(date) == account_balance
return false unless is_payable_from_admin
end
if payout_type == Payouts::PAYOUT_TYPE_INSTANT
if !user.instant_payouts_supported?
user.add_payout_note(content: "Payout on #{payout_date} was skipped because the account is not eligible for instant payouts.") if add_comment
return false
end
amount_payable = user.instantly_payable_unpaid_balance_cents_up_to_date(date)
end
processor_types = processor_type ? [processor_type] : ::PayoutProcessorType.all
processor_types.any? do |payout_processor_type|
::PayoutProcessorType.get(payout_processor_type).is_user_payable(user, amount_payable, add_comment:, from_admin:, payout_type:)
end
end
def self.create_payments_for_balances_up_to_date(date, processor_type)
users = User.holding_balance
if processor_type == PayoutProcessorType::STRIPE
users = users.joins(:merchant_accounts)
.where("merchant_accounts.deleted_at IS NULL")
.where("merchant_accounts.charge_processor_id = ?", StripeChargeProcessor.charge_processor_id)
.where("merchant_accounts.json_data->'$.meta.stripe_connect' = 'true'")
end
self.create_payments_for_balances_up_to_date_for_users(date, processor_type, users, perform_async: true)
end
def self.create_payments_for_balances_up_to_date_for_bank_account_types(date, processor_type, bank_account_types)
bank_account_types.each do |bank_account_type|
users = User.holding_balance
.joins("inner join bank_accounts on bank_accounts.user_id = users.id")
.where("bank_accounts.type = ?", bank_account_type)
.where("bank_accounts.deleted_at is null")
self.create_payments_for_balances_up_to_date_for_users(date, processor_type, users, perform_async: true, bank_account_type:)
end
end
def self.create_instant_payouts_for_balances_up_to_date(date)
users = User.holding_balance.where("json_data->'$.payout_frequency' = 'daily'")
self.create_instant_payouts_for_balances_up_to_date_for_users(date, users, perform_async: true, add_comment: true)
end
def self.create_payments_for_balances_up_to_date_for_users(date, processor_type, users, perform_async: false, retrying: false, bank_account_type: nil, from_admin: false)
raise ArgumentError.new("Cannot payout for today or future balances.") if date >= Date.current
user_ids_to_pay = []
users.each do |user|
if self.is_user_payable(
user, date,
processor_type:,
add_comment: true,
from_admin:
) &&
(
from_admin ||
(
user.next_payout_date.present? &&
date + User::PayoutSchedule::PAYOUT_DELAY_DAYS >= user.next_payout_date
)
)
user_ids_to_pay << user.id
Rails.logger.info("Payouts: Payable user: #{user.id}")
else
Rails.logger.info("Payouts: Not payable user: #{user.id}")
end
end
date_string = date.to_s
if perform_async
payout_processor = ::PayoutProcessorType.get(processor_type)
payout_processor.enqueue_payments(user_ids_to_pay, date_string)
else
payments = []
user_ids_to_pay.each do |user_id|
payments << PayoutUsersService.new(date_string:,
processor_type:,
user_ids: user_id).process
end
payments.compact
end
end
def self.create_instant_payouts_for_balances_up_to_date_for_users(date, users, perform_async: false, from_admin: false, add_comment: false)
raise ArgumentError.new("Cannot payout for today or future balances.") if date >= Date.current
user_ids_to_pay = []
users.each do |user|
if self.is_user_payable(
user, date,
processor_type: PayoutProcessorType::STRIPE,
add_comment:,
from_admin:,
payout_type: Payouts::PAYOUT_TYPE_INSTANT
)
user_ids_to_pay << user.id
Rails.logger.info("Instant Payouts: Payable user: #{user.id}")
else
Rails.logger.info("Instant Payouts: Not payable user: #{user.id}")
end
end
date_string = date.to_s
if perform_async
StripePayoutProcessor.enqueue_payments(user_ids_to_pay, date_string, payout_type: Payouts::PAYOUT_TYPE_INSTANT)
else
payments = []
user_ids_to_pay.each do |user_id|
payments << PayoutUsersService.new(date_string:,
processor_type: PayoutProcessorType::STRIPE,
payout_type: Payouts::PAYOUT_TYPE_INSTANT,
user_ids: user_id).process
end
payments.compact
end
end
def self.create_payment(date, processor_type, user, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
payout_processor = ::PayoutProcessorType.get(processor_type)
balances = mark_balances_processing(date, processor_type, user)
balance_cents = balances.sum(&:amount_cents)
if balance_cents <= 0
Rails.logger.info("Payouts: Negative balance for #{user.id}")
balances.each(&:mark_unpaid!)
return nil
end
payment = Payment.new(
user:,
balances:,
processor: processor_type,
processor_fee_cents: 0,
payout_period_end_date: date,
payout_type:,
# TODO: Refactor paypal to be a type of bank account rather than being a field on user.
payment_address: (user.paypal_payout_email if processor_type == ::PayoutProcessorType::PAYPAL),
bank_account: (user.active_bank_account if processor_type != ::PayoutProcessorType::PAYPAL)
)
payment.save!
payment_errors = payout_processor.prepare_payment_and_set_amount(payment, balances)
payment.mark_processing!
[payment, payment_errors]
end
def self.mark_balances_processing(date, processor_type, user)
user.unpaid_balances_up_to_date(date).select do |balance|
next if !::PayoutProcessorType.get(processor_type).is_balance_payable(balance)
balance.with_lock do
balance.mark_processing!
end
true
end
end
private_class_method :mark_balances_processing
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/payouts/payout_processor_type.rb | app/business/payments/payouts/payout_processor_type.rb | # frozen_string_literal: true
module PayoutProcessorType
PAYPAL = "PAYPAL"
ACH = "ACH" # Retired. Kept because we still have payments in the database for this processor.
ZENGIN = "ZENGIN" # Retired. Kept because we still have payments in the database for this processor, and validations for them.
STRIPE = "STRIPE"
ALL = {
PAYPAL => PaypalPayoutProcessor,
STRIPE => StripePayoutProcessor
}.freeze
private_constant :ALL
def self.all
ALL.keys
end
def self.get(payout_processor_type)
ALL[payout_processor_type]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/payouts/payout_estimates.rb | app/business/payments/payouts/payout_estimates.rb | # frozen_string_literal: true
module PayoutEstimates
def self.estimate_held_amount_cents(date, processor_type)
payment_estimates = estimate_payments_for_balances_up_to_date_for_users(date, processor_type, User.holding_balance)
holder_of_funds_amount_cents = Hash.new(0)
payment_estimates.each do |payment_estimate|
payment_estimate[:holder_of_funds_amount_cents].each do |holder_of_funds, amount_cents|
holder_of_funds_amount_cents[holder_of_funds] += amount_cents
end
end
holder_of_funds_amount_cents
end
def self.estimate_payments_for_balances_up_to_date_for_users(date, processor_type, users)
payment_estimates = []
users.each do |user|
next unless Payouts.is_user_payable(user, date, processor_type:)
balances = get_balances(date, processor_type, user)
balance_cents = balances.sum(&:amount_cents)
payment_estimates << {
user:,
amount_cents: balance_cents,
holder_of_funds_amount_cents: balances.each_with_object(Hash.new(0)) do |balance, hash|
hash[balance.merchant_account.holder_of_funds] += balance.amount_cents
end
}
end
payment_estimates
end
private_class_method
def self.get_balances(date, processor_type, user)
user.unpaid_balances_up_to_date(date).select do |balance|
::PayoutProcessorType.get(processor_type).is_balance_payable(balance)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/payouts/processor/stripe/stripe_payout_processor.rb | app/business/payments/payouts/processor/stripe/stripe_payout_processor.rb | # frozen_string_literal: true
class StripePayoutProcessor
extend CurrencyHelper
DEBIT_CARD_PAYOUT_MAX = 300_000
INSTANT_PAYOUT_FEE_PERCENT = 3
MINIMUM_INSTANT_PAYOUT_AMOUNT_CENTS = 10_00
MAXIMUM_INSTANT_PAYOUT_AMOUNT_CENTS = 9_999_00
# Public: Determines if it's possible for this processor to payout
# the user by checking that the user has provided us with the
# information we need to be able to payout with this processor.
#
# This payout processor can payout any user who has a Stripe managed account
# and has a bank account setup.
def self.is_user_payable(user, amount_payable_usd_cents, add_comment: false, from_admin: false, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
payout_date = Time.current.to_fs(:formatted_date_full_month)
# If a user's previous payment is still processing, don't allow for new payments.
processing_payment_ids = user.payments.processing.ids
if processing_payment_ids.any?
user.add_payout_note(content: "Payout on #{payout_date} was skipped because there was already a payout in processing.") if add_comment
return false
end
# Return true if user has a Stripe account connected
return true if user.has_stripe_account_connected? && !user.stripe_connect_account.is_a_brazilian_stripe_connect_account?
# Don't payout users who don't have a bank account
if user.active_bank_account.nil?
user.add_payout_note(content: "Payout on #{payout_date} was skipped because a bank account wasn't added at the time.") if add_comment
return false
end
# Don't payout users whose bank account is not linked to a bank account at Stripe
if user.active_bank_account.stripe_bank_account_id.blank? || user.stripe_account.nil?
user.add_payout_note(content: "Payout on #{payout_date} was skipped because the payout bank account was not correctly set up.") if add_comment
return false
end
if payout_type == Payouts::PAYOUT_TYPE_INSTANT
if amount_payable_usd_cents < StripePayoutProcessor::MINIMUM_INSTANT_PAYOUT_AMOUNT_CENTS
user.add_payout_note(content: "Instant Payout on #{payout_date} was skipped because the account balance was less than the minimum instant payout amount of $10.") if add_comment
return false
end
if amount_payable_usd_cents > StripePayoutProcessor::MAXIMUM_INSTANT_PAYOUT_AMOUNT_CENTS
user.add_payout_note(content: "Instant Payout on #{payout_date} was skipped because the account balance was greater than the maximum instant payout amount of $9999.") if add_comment
return false
end
end
true
end
def self.has_valid_payout_info?(user)
# Return true if user has a Stripe account connected
return true if user.has_stripe_account_connected?
# Don't payout users who don't have a bank account
return false if user.active_bank_account.nil?
# Don't payout users whose bank account is not linked to a bank account at Stripe
return false if user.active_bank_account.stripe_bank_account_id.blank?
# Don't payout users who don't have an active Stripe merchant account
return false if user.stripe_account.nil?
true
end
# Public: Determines if the processor can payout the balance. Since
# balances can be being held either by Gumroad or by specific processors
# a balance may not be payable by a processor if the balance is not
# being held by Gumroad.
#
# This payout processor can payout any balance that's held by Stripe,
# where the purchase was charged on a creator's own Stripe account.
def self.is_balance_payable(balance)
case balance.merchant_account.holder_of_funds
when HolderOfFunds::STRIPE
balance.holding_currency == balance.merchant_account.currency
when HolderOfFunds::GUMROAD
true
else
false
end
end
# Public: Get the payout destination and categorized balances for a user
def self.get_payout_details(user, balances)
balances_by_holder_of_funds = balances.group_by { |balance| balance.merchant_account.holder_of_funds }
balances_held_by_gumroad = balances_by_holder_of_funds[HolderOfFunds::GUMROAD] || []
balances_held_by_stripe = balances_by_holder_of_funds[HolderOfFunds::STRIPE] || []
# If user has a Stripe standard account connected and there are no balances_held_by_stripe, we issue payout to the
# connected Stripe standard account.
#
# If there is no Stripe Connect account or if there is balances_held_by_stripe,
# that means the custom Stripe connect account (which is managed by gumroad) is still in use and there's some amount
# in the custom Stripe connect account that needs to be paid out.
# We issue payout via the custom Stripe connect account in that case.
#
# Once a standard Stripe account is connected, balances_held_by_stripe will eventually come down to zero as
# new sales will go directly to the connected Stripe account and no new balance will be generated
# against the custom Stripe connect account.
merchant_account = if user.has_stripe_account_connected? && balances_held_by_stripe.blank?
user.stripe_connect_account
else
user.stripe_account || balances_held_by_stripe[0]&.merchant_account
end
return merchant_account, balances_held_by_gumroad, balances_held_by_stripe
end
def self.instantly_payable_amount_cents_on_stripe(user)
active_bank_account = user.active_bank_account
return 0 if active_bank_account.blank?
balance = Stripe::Balance.retrieve(
{ expand: ["instant_available.net_available"] },
{ stripe_account: active_bank_account.stripe_connect_account_id }
)
balance.try(:instant_available)
&.first
&.try(:net_available)
&.find { _1["destination"] == active_bank_account.stripe_bank_account_id }
&.[]("amount") || 0
end
# Public: Takes the actions required to prepare the payment, that include:
# * Setting the currency.
# * Setting the amount_cents.
# Returns an array of errors.
def self.prepare_payment_and_set_amount(payment, balances)
merchant_account, balances_held_by_gumroad, balances_held_by_stripe = get_payout_details(payment.user, balances)
payment.stripe_connect_account_id = merchant_account.charge_processor_merchant_id
payment.currency = merchant_account.currency
payment.amount_cents = 0
payment.amount_cents += balances_held_by_stripe.sum(&:holding_amount_cents)
# If the user is being paid out funds held by Gumroad, transfer those funds to the creators Stripe account.
amount_cents_held_by_gumroad = balances_held_by_gumroad.sum(&:holding_amount_cents)
if amount_cents_held_by_gumroad > 0
internal_transfer = StripeTransferInternallyToCreator.transfer_funds_to_account(
message_why: "Funds held by Gumroad for Payment #{payment.external_id}.",
stripe_account_id: payment.stripe_connect_account_id,
currency: Currency::USD,
amount_cents: amount_cents_held_by_gumroad,
metadata: {
payment: payment.external_id
}.merge(StripeMetadata.build_metadata_large_list(balances_held_by_gumroad.map(&:external_id),
key: :balances,
separator: ",",
# 1 key (`payment`) already added above so allow max - 1 more keys
max_key_length: StripeMetadata::STRIPE_METADATA_MAX_KEYS_LENGTH - 1))
)
destination_payment = Stripe::Charge.retrieve(
{
id: internal_transfer.destination_payment,
expand: %w[balance_transaction]
},
{ stripe_account: payment.stripe_connect_account_id }
)
payment.amount_cents += destination_payment.balance_transaction.amount
payment.stripe_internal_transfer_id = internal_transfer.id
end
# For HUF and TWD, Stripe only supports payout amount cents that are divisible by 100 (Ref: https://stripe.com/docs/currencies#special-cases)
# So we discard the mod hundred amount when making the payout, but mark the entire amount as paid on our end.
payment.amount_cents -= payment.amount_cents % 100 if [Currency::HUF, Currency::TWD].include?(payment.currency)
# Our currencies.yml assumes KRW to have 100 subunits, and that's how we store them in the database.
# However, Stripe treats KRW as a single-unit currency. So we convert the value here.
payment.amount_cents = payment.amount_cents * 100 if payment.currency == Currency::KRW
# For instant payouts, the amount has to be net of instant payout fees.
if payment.payout_type == Payouts::PAYOUT_TYPE_INSTANT
payment.amount_cents = (payment.amount_cents * 100.0 / (100 + INSTANT_PAYOUT_FEE_PERCENT)).floor
end
[]
rescue Stripe::InvalidRequestError => e
failed = true
Bugsnag.notify(e)
[e.message]
rescue Stripe::AuthenticationError, Stripe::APIConnectionError
failed = true
raise
rescue Stripe::StripeError => e
failed = true
Bugsnag.notify(e)
[e.message]
ensure
payment.mark_failed! if failed
end
def self.enqueue_payments(user_ids, date_string, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
user_ids.each do |user_id|
PayoutUsersWorker.perform_async(date_string, PayoutProcessorType::STRIPE, user_id, payout_type)
end
end
def self.process_payments(payments)
payments.each do |payment|
perform_payment(payment)
end
end
# Public: Actually sends the money.
# Returns an array of errors.
def self.perform_payment(payment)
# We have transferred the balance held by gumroad to the connected Stripe standard account.
# No payout needs to be issued in this case.
merchant_account = payment.user.merchant_accounts.find_by(charge_processor_merchant_id: payment.stripe_connect_account_id)
if merchant_account.is_a_stripe_connect_account?
stripe_transfer = Stripe::Transfer.retrieve(payment.stripe_internal_transfer_id)
payment.stripe_transfer_id = stripe_transfer.destination_payment
payment.mark_completed!
return
end
amount_cents = if payment.currency == Currency::KRW
# Our currencies.yml assumes KRW to have 100 subunits, and that's how we store them in the database.
# However, Stripe treats KRW as a single-unit currency. So we convert the value here.
payment.amount_cents / 100
else
payment.amount_cents
end
# Transfer the payout amount from the creators Stripe account to their bank account.
params = {
amount: amount_cents,
currency: payment.currency,
destination: payment.bank_account.stripe_external_account_id,
statement_descriptor: "Gumroad",
description: payment.external_id,
metadata: {
payment: payment.external_id,
bank_account: payment.bank_account.external_id
}.merge(StripeMetadata.build_metadata_large_list(payment.balances.map(&:external_id),
key: :balances,
separator: ",",
# 2 keys (`payment` and `bank_account`) already added above so allow max - 2 more keys
max_key_length: StripeMetadata::STRIPE_METADATA_MAX_KEYS_LENGTH - 2))
}
params.merge!(method: payment.payout_type) if payment.payout_type.present?
stripe_payout = Stripe::Payout.create(params, { stripe_account: payment.stripe_connect_account_id })
payment.stripe_transfer_id = stripe_payout.id
payment.arrival_date = stripe_payout.arrival_date
payment.gumroad_fee_cents = stripe_payout.application_fee_amount if payment.payout_type == Payouts::PAYOUT_TYPE_INSTANT
payment.save!
[]
rescue Stripe::InvalidRequestError => e
failed = true
if e.message["Cannot create live transfers"]
failure_reason = Payment::FailureReason::CANNOT_PAY
elsif e.message["Debit card transfers are only supported for amounts less"]
failure_reason = Payment::FailureReason::DEBIT_CARD_LIMIT
elsif e.message["Insufficient funds in Stripe account"]
failure_reason = Payment::FailureReason::INSUFFICIENT_FUNDS
else
Bugsnag.notify(e)
end
Rails.logger.info("Payouts: Payout errors for user with id: #{payment.user_id} #{e.message}")
[e.message]
rescue Stripe::AuthenticationError, Stripe::APIConnectionError
failed = true
raise
rescue Stripe::StripeError => e
failed = true
Bugsnag.notify(e)
Rails.logger.info("Payouts: Payout errors for user with id: #{payment.user_id} #{e.message}")
[e.message]
ensure
Rails.logger.info("Payouts: Payout of #{payment.amount_cents} attempted for user with id: #{payment.user_id}")
if failed
payment.mark_failed!(failure_reason)
reverse_internal_transfer!(payment)
end
end
def self.handle_stripe_event(stripe_event, stripe_connect_account_id:)
stripe_event_id = stripe_event["id"]
stripe_event_type = stripe_event["type"]
return unless stripe_event_type.in?(%w[
payout.paid
payout.canceled
payout.failed
])
# Get the Stripe Payout object
event_object = stripe_event["data"]["object"]
raise "Stripe Event #{stripe_event_id}: does not contain a payout object." if event_object["object"] != "payout"
is_payout_reversal = event_object["original_payout"].present?
stripe_payout_id = is_payout_reversal ? event_object["original_payout"] : event_object["id"]
raise "Stripe Event #{stripe_event_id}: payout has no payout id." if stripe_payout_id.blank?
stripe_payout = Stripe::Payout.retrieve(stripe_payout_id, { stripe_account: stripe_connect_account_id })
merchant_account = MerchantAccount.find_by(charge_processor_merchant_id: stripe_connect_account_id)
return if merchant_account.blank? || merchant_account.is_a_stripe_connect_account? || merchant_account.currency != stripe_payout["currency"]
if stripe_payout["automatic"]
if stripe_payout["amount"] >= 0
# Ignore events about automatic on-schedule payouts (not triggered by Gumroad). Ref: https://github.com/gumroad/web/issues/16938
Rails.logger.info("Ignoring automatic payout event #{stripe_event_id} for stripe account #{stripe_connect_account_id}")
else
case stripe_event_type
when "payout.paid"
# Wait 7 calendar days before checking the payout's status because state changes within next 5 business
# days aren't final: https://stripe.com/docs/api/payouts/object#payout_object-status
HandleStripeAutodebitForNegativeBalance.perform_in(7.days, stripe_event_id, stripe_connect_account_id, stripe_payout_id)
end
# We don't need to handle payout.canceled or payout.failed because we don't need to credit to gumroad account when stripe balance didnt change.
end
return
end
# We lookup the payment on master to ensure we're looking at the latest version and have the latest state.
ActiveRecord::Base.connection.stick_to_primary!
# Find the matching Payment
payment = Payment
.processed_by(PayoutProcessorType::STRIPE)
.find_by(stripe_connect_account_id:, stripe_transfer_id: stripe_payout_id)
raise "Stripe Event #{stripe_event_id}: payout does not match any payment." if payment.nil?
raise "Stripe Event #{stripe_event_id}: payout mismatches on payment ID." if payment.external_id != stripe_payout["metadata"]["payment"]
if is_payout_reversal
reversing_payout_id = event_object["id"]
case stripe_event_type
when "payout.paid"
# Wait 7 calendar days before checking the reversing payout's status because state changes within next 5 business
# days aren't final: https://stripe.com/docs/api/payouts/object#payout_object-status
# https://github.com/gumroad/web/pull/23719
HandlePayoutReversedWorker.perform_in(7.days, payment.id, reversing_payout_id, stripe_connect_account_id)
when "payout.failed"
handle_stripe_event_payout_reversal_failed(payment, reversing_payout_id)
end
else
case stripe_event_type
when "payout.paid"
handle_stripe_event_payout_paid(payment, stripe_payout)
when "payout.canceled"
handle_stripe_event_payout_cancelled(payment)
when "payout.failed"
handle_stripe_event_payout_failed(payment, failure_reason: stripe_payout["failure_code"])
end
end
end
def self.handle_stripe_negative_balance_debit_event(stripe_connect_account_id, stripe_payout_id)
# This is a stripe automatic debit made by stripe due to negative balance in user stripe account
stripe_payout = Stripe::Payout.retrieve(stripe_payout_id, { stripe_account: stripe_connect_account_id })
amount_cents = stripe_payout["amount"]
merchant_account = MerchantAccount.find_by(charge_processor_merchant_id: stripe_connect_account_id)
return unless amount_cents < 0
Credit.create_for_bank_debit_on_stripe_account!(amount_cents: amount_cents.abs, merchant_account:)
end
def self.handle_stripe_event_payout_reversed(payment, reversing_payout_id)
payment.with_lock do
case payment.state
when "processing"
payment.mark_failed!
when "completed"
payment.mark_returned!
else
return
end
reverse_internal_transfer!(payment)
payment.processor_reversing_payout_id = reversing_payout_id
payment.save!
end
end
def self.handle_stripe_event_payout_reversal_failed(payment, reversing_payout_id)
# Normally, when someone initiates a reversal of the payout from Stripe dashboard and it fails -
# there's nothing for us to do.
#
# However, as per Stripe docs: "Some failed payouts may initially show as paid but then change to failed"
# (https://stripe.com/docs/api/payouts/object#payout_object-status). So if this reversal was initially reported
# as `paid` (and we marked linked balances as `unpaid`), but has now changed to `failed`, we might have
# attempted to re-pay those balances in the meanwhile. We may also have to re-do the previously reversed internal
# transfer.
#
# We wait for the reversal transfer to be finalized before marking linked balances as `unpaid`,
# so we should never have to raise here. If we did - there's a bug in the code.
if payment.reversed_by?(reversing_payout_id)
raise "Payout #{payment.id} was reversed in Stripe console, the reversal was reported as paid, "\
"we marked the payout as returned and may have since re-paid linked balances to the creator. "\
"Stripe has now notified us that the original reversal has failed. The case needs manual review."
end
end
def self.handle_stripe_event_payout_paid(payment, stripe_payout)
payment.with_lock do
return unless payment.state == "processing"
payment.arrival_date = stripe_payout["arrival_date"]
payment.mark_completed!
end
end
def self.handle_stripe_event_payout_cancelled(payment)
payment.with_lock do
raise "Expected payment #{payment.id} to be in processing state, got: #{payment.state}" unless payment.state == "processing"
payment.mark_cancelled!
reverse_internal_transfer!(payment)
end
end
def self.handle_stripe_event_payout_failed(payment, failure_reason: nil)
payment.with_lock do
case payment.state
when "processing"
payment.mark_failed!
when "completed"
payment.mark_returned!
else
return
end
end
reverse_internal_transfer!(payment)
if failure_reason
payment.failure_reason = failure_reason
payment.save!
payment.send_payout_failure_email
end
end
def self.reverse_internal_transfer!(payment)
return if payment.stripe_internal_transfer_id.nil?
internal_transfer = Stripe::Transfer.retrieve(payment.stripe_internal_transfer_id)
internal_transfer.reversals.create
create_credit_for_difference_from_reversed_internal_transfer(payment, internal_transfer)
end
def self.create_credit_for_difference_from_reversed_internal_transfer(payment, internal_transfer)
destination_payment = Stripe::Charge.retrieve(
{
id: internal_transfer.destination_payment,
expand: %w[balance_transaction refunds]
},
{ stripe_account: internal_transfer.destination }
)
refund_balance_transaction = Stripe::BalanceTransaction.retrieve(
{ id: destination_payment.refunds.first.balance_transaction }, { stripe_account: internal_transfer.destination }
)
difference_amount_cents = destination_payment.balance_transaction.net + refund_balance_transaction.net
return if difference_amount_cents == 0
merchant_account = MerchantAccount.where(
user: payment.user,
charge_processor_id: StripeChargeProcessor.charge_processor_id,
charge_processor_merchant_id: internal_transfer.destination
).first
Credit.create_for_returned_payment_difference!(
user: payment.user,
merchant_account:,
returned_payment: payment,
difference_amount_cents:
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/payouts/processor/paypal/paypal_payout_processor.rb | app/business/payments/payouts/processor/paypal/paypal_payout_processor.rb | # frozen_string_literal: true
class PaypalPayoutProcessor
# We would split up the payment into chunks of at most this size, only when necessary, in order to get around the MassPay API limitations.
# See perform_payment_in_split_mode. This is a hack that should be replaced with a proper split payout mechanism that supports a single Balance being
# split into separate Payments, since a single day's balance could be larger than the paypal payout limit.
MAX_SPLIT_PAYMENT_BY_CENTS = 20_000_00 # $20,000 since that's the maximum the MassPay API accepts as per PayPal support
SPLIT_PAYMENT_TXN_ID = "split payment; see split_payments_info"
SPLIT_PAYMENT_UNIQUE_ID_PREFIX = "SPLIT_"
PAYPAL_API_PARAMS = {
"USER" => PAYPAL_USER,
"PWD" => PAYPAL_PASS,
"SIGNATURE" => PAYPAL_SIGNATURE,
"VERSION" => "90.0",
"CURRENCYCODE" => "USD"
}.freeze
PAYOUT_RECIPIENTS_PER_JOB = 240 # Max recipients allowed in one API call is 250. Using 240 because I don't trust PayPal.
PAYPAL_PAYOUT_FEE_PERCENT = 2
PAYPAL_PAYOUT_FEE_EXEMPT_COUNTRY_CODES = [Compliance::Countries::BRA.alpha2, Compliance::Countries::IND.alpha2]
# Public: Determines if it's possible for this processor to payout
# the user by checking that the user has provided us with the
# information we need to be able to payout with this processor.
#
# This payout processor can payout any user who has provided a paypal address,
# but will also opt to not payout users who have previous paypal payouts that were incomplete
# or if they've provided a bank account because it's possibe for users to have both
# a payment address and a bank account and we prefer bank payouts.
def self.is_user_payable(user, amount_payable_usd_cents, add_comment: false, from_admin: false, payout_type: Payouts::PAYOUT_TYPE_STANDARD)
payout_date = Time.current.to_fs(:formatted_date_full_month)
# Don't allow payout to PayPal if the user has given us a bank account.
return false if user.active_bank_account
# PayPal does not support instant payouts.
return false if payout_type == Payouts::PAYOUT_TYPE_INSTANT
# Don't allow payout to PayPal if the StripePayoutProcessor can handle it.
return false if StripePayoutProcessor.is_user_payable(user, amount_payable_usd_cents)
payout_email = user.paypal_payout_email
# User is payable on PayPal if they've provided an email address.
if !EmailFormatValidator.valid?(payout_email)
user.add_payout_note(content: "Payout via PayPal on #{payout_date} skipped because the account does not have a valid PayPal payment address") if add_comment
return false
end
# Email address contains non-ascii characters
unless payout_email.ascii_only?
user.add_payout_note(content: "Payout via PayPal on #{payout_date} skipped because the PayPal payment address contains invalid characters") if add_comment
return false
end
# User hasn't given us their compliance info.
if user.alive_user_compliance_info.try(:legal_entity_name).blank? && !user.has_paypal_account_connected?
user.add_payout_note(content: "Payout via PayPal on #{payout_date} skipped because the account does not have a valid name on record") if add_comment
return false
end
# If a user's previous payment is still processing, don't allow for new payments.
processing_payment_ids = user.payments.processing.ids
if processing_payment_ids.any?
user.add_payout_note(content: "Payout via PayPal on #{payout_date} skipped because there are already payouts (ID #{processing_payment_ids.join(', ')}) in processing") if add_comment
return false
end
true
end
def self.has_valid_payout_info?(user)
payout_email = user.paypal_payout_email
# User is payable on PayPal if they've provided an email address.
return false unless EmailFormatValidator.valid?(payout_email)
# Email address contains non-ascii characters
return false unless payout_email.ascii_only?
# User hasn't given us their compliance info.
return false if user.alive_user_compliance_info.try(:legal_entity_name).blank? && user.paypal_connect_account.blank?
true
end
# Public: Determines if the processor can payout the balance. Since
# balances can be being held either by Gumroad or by specific processors
# a balance may not be payable by a processor if the balance is not
# being held by Gumroad.
#
# This payout processor can payout any balance that's held by Gumroad,
# where the creator was a supplier and Gumroad was the merchant.
def self.is_balance_payable(balance)
balance.merchant_account.holder_of_funds == HolderOfFunds::GUMROAD && balance.holding_currency == Currency::USD
end
# Public: Takes the actions required to prepare the payment, that include:
# * Setting the currency.
# * Setting the amount_cents.
# Returns an array of errors.
def self.prepare_payment_and_set_amount(payment, balances)
payment.currency = Currency::USD
payment.amount_cents = balances.sum(&:holding_amount_cents)
if payment.user.charge_paypal_payout_fee?
payment.gumroad_fee_cents = (payment.amount_cents * PAYPAL_PAYOUT_FEE_PERCENT / 100.0).ceil
payment.amount_cents -= payment.gumroad_fee_cents
end
[]
end
def self.enqueue_payments(user_ids, date_string)
user_ids.each_slice(PAYOUT_RECIPIENTS_PER_JOB).with_index do |ids, index|
# Work around (unknown) rate-limits by introducing a delay
PayoutUsersWorker.perform_in(index.minutes, date_string, PayoutProcessorType::PAYPAL, ids)
end
end
def self.process_payments(payments)
regular_payments = []
split_mode_payments = []
payments.each do |payment|
user = payment.user
if user.should_paypal_payout_be_split? && payment.amount_cents > split_payment_by_cents(user)
split_mode_payments << payment
else
regular_payments << payment
end
end
split_mode_payments.each do |payment|
perform_split_payment(payment)
rescue => e
Rails.logger.error "Error processing payment #{payment.id} => #{e.class.name}: #{e.message}"
Rails.logger.error "Error processing payment #{payment.id} => #{e.backtrace.join("\n")}"
Bugsnag.notify(e)
next
end
perform_payments(regular_payments) if regular_payments.present?
end
def self.perform_payments(payments)
mass_pay_params = paypal_auth_params
payment_index = 0
user_ids = []
payments.each do |payment|
mass_pay_params["L_EMAIL#{payment_index}"] = payment.payment_address
mass_pay_params["L_AMT#{payment_index}"] = payment.amount_cents / 100.0
mass_pay_params["L_UNIQUEID#{payment_index}"] = payment.id
mass_pay_params["L_NOTE#{payment_index}"] = note_for_paypal_payment(payment)
user_ids << payment.user_id
payment_index += 1
end
Rails.logger.info("Paypal payouts: posting #{mass_pay_params} to #{PAYPAL_ENDPOINT} for user IDs #{user_ids}")
paypal_response = HTTParty.post(PAYPAL_ENDPOINT, body: mass_pay_params)
Rails.logger.info("Paypal payouts: received #{paypal_response} from #{PAYPAL_ENDPOINT} for user IDs #{user_ids}")
parsed_paypal_response = Rack::Utils.parse_nested_query(paypal_response)
ack_status = parsed_paypal_response["ACK"]
transaction_succeeded = %w[Success SuccessWithWarning].include?(ack_status)
correlation_id = parsed_paypal_response["CORRELATIONID"]
payments.each { |payment| payment.update(correlation_id:) }
payments.each(&:mark_failed!) unless transaction_succeeded
errors = errors_for_parsed_paypal_response(parsed_paypal_response) if ack_status != "Success"
Rails.logger.info("Paypal Payouts: Payout errors for user IDs #{user_ids}: #{errors.inspect}") if errors.present?
end
# Public: Sends the money in `split_payment_by_cents(payment.user)` increments.
def self.perform_split_payment(payment)
payment.was_created_in_split_mode = true
split_payment_cents = split_payment_by_cents(payment.user)
errors = []
number_of_split_payouts = (payment.amount_cents.to_f / split_payment_cents).ceil
paid_so_far_amount_cents = 0
(1..number_of_split_payouts).each do |payout_number|
remaining_amount_cents = payment.amount_cents - paid_so_far_amount_cents
split_payment_amount_cents = [remaining_amount_cents, split_payment_cents].min
params = paypal_auth_params
split_payment_unique_id = "#{SPLIT_PAYMENT_UNIQUE_ID_PREFIX}#{payment.id}-#{payout_number}" # According to paypal this field has a 30 byte limit.
params["L_EMAIL0"] = payment.payment_address
params["L_AMT0"] = split_payment_amount_cents / 100.0
params["L_UNIQUEID0"] = split_payment_unique_id
params["L_NOTE0"] = note_for_paypal_payment(payment)
Rails.logger.info("Paypal payouts: posting #{params} to #{PAYPAL_ENDPOINT} for user ID #{payment.user.id}")
paypal_response = HTTParty.post(PAYPAL_ENDPOINT, body: params)
Rails.logger.info("Paypal payouts: received #{paypal_response} from #{PAYPAL_ENDPOINT} for user ID #{payment.user.id}")
paid_so_far_amount_cents += split_payment_amount_cents
parsed_paypal_response = Rack::Utils.parse_nested_query(paypal_response)
ack_status = parsed_paypal_response["ACK"]
transaction_succeeded = %w[Success SuccessWithWarning].include?(ack_status)
correlation_id = parsed_paypal_response["CORRELATIONID"]
errors << errors_for_parsed_paypal_response(parsed_paypal_response) if ack_status != "Success"
split_payment_info = {
state: transaction_succeeded ? "processing" : "failed",
correlation_id:,
amount_cents: split_payment_amount_cents,
errors:
}
payment.split_payments_info.nil? ? payment.split_payments_info = [split_payment_info] : payment.split_payments_info << split_payment_info
payment.correlation_id = correlation_id
payment.save!
# Mark it as failed and stop the payments only if the first transaction failed.
payment.mark_failed! && break if !transaction_succeeded && payout_number == 1
end
Rails.logger.info("Payouts: Split mode payout of #{payment.amount_cents} attempted for user with id: #{payment.user_id}")
Rails.logger.info("Payouts: Split mode payout errors for user with id: #{payment.user_id} #{errors.inspect}") if errors.present?
end
def self.handle_paypal_event(paypal_event)
Rails.logger.info("Paypal payouts: received IPN #{paypal_event}")
# https://developer.paypal.com/docs/api-basics/notifications/ipn/IPNandPDTVariables/#payment-information-variables
payments_data = []
paypal_event.each_pair do |k, v|
next unless k =~ /.*_(\d+)$/
payments_data[Regexp.last_match[1].to_i] ||= {}
payments_data[Regexp.last_match[1].to_i][k.gsub(/_\d+$/, "")] = v
end
payments_data.compact!
payments_data.each do |payment_information|
payment_unique_id = payment_information["unique_id"].to_s
if payment_unique_id.start_with?(SPLIT_PAYMENT_UNIQUE_ID_PREFIX)
handle_paypal_event_for_split_payment(payment_unique_id, payment_information)
else
handle_paypal_event_for_non_split_payment(payment_unique_id, payment_information)
end
end
end
def self.split_payment_by_cents(user)
cents = user.split_payment_by_cents
if cents.present? && cents <= MAX_SPLIT_PAYMENT_BY_CENTS
cents
else
MAX_SPLIT_PAYMENT_BY_CENTS
end
end
# TODO: Make methods from this point onwards private
def self.paypal_auth_params
PAYPAL_API_PARAMS.merge("METHOD" => "MassPay", "RECEIVERTYPE" => "EmailAddress")
end
def self.errors_for_parsed_paypal_response(parsed_paypal_response)
errors = []
error_index = 0
while parsed_paypal_response["L_SHORTMESSAGE#{error_index}"].present?
error_code = parsed_paypal_response["L_ERRORCODE#{error_index}"]
short_message = parsed_paypal_response["L_SHORTMESSAGE#{error_index}"]
long_message = parsed_paypal_response["L_LONGMESSAGE#{error_index}"]
errors << "#{error_code} - #{short_message} - #{long_message}"
error_index += 1
end
errors
end
def self.handle_paypal_event_for_non_split_payment(payment_unique_id, paypal_event)
payment = Payment.find_by(id: payment_unique_id)
if payment.nil?
Rails.logger.warn "Paypal payouts: unique_id #{payment_unique_id} didn't correspond to a payment ID"
return
end
return unless Payment::NON_TERMINAL_STATES.include?(payment.state)
payment.with_lock do
payment.txn_id = paypal_event["masspay_txn_id"]
payment.processor_fee_cents = 100 * paypal_event["mc_fee"].to_f if paypal_event["mc_fee"]
payment.save!
new_payment_state = paypal_event["status"].try(:downcase)
# Paypal is sending incorrect payment status ('Pending') in the IPN callback for some of the payments where the
# actual status is either 'Unclaimed' or 'Completed'. Until the issue is resolved at Paypal, we get the actual
# status using another API call to Paypal.
# Ref: https://github.com/gumroad/web/issues/9474
if new_payment_state == "pending"
new_payment_state = get_latest_payment_state_from_paypal(payment.amount_cents,
payment.txn_id,
payment.created_at.beginning_of_day - 1.day,
new_payment_state)
end
if new_payment_state == "pending"
UpdatePayoutStatusWorker.perform_in(5.minutes, payment.id)
elsif payment.state != new_payment_state
if new_payment_state == "failed"
failure_reason = "PAYPAL #{paypal_event["reason_code"]}" if paypal_event["reason_code"].present?
payment.mark_failed!(failure_reason)
else
payment.mark!(new_payment_state)
end
end
end
end
def self.handle_paypal_event_for_split_payment(payment_unique_id, paypal_event)
payment_id_and_split_payment_number = payment_unique_id.split(SPLIT_PAYMENT_UNIQUE_ID_PREFIX)[1]
payment_id, split_payment_number = payment_id_and_split_payment_number.split("-").map(&:to_i)
payment = Payment.find_by(id: payment_id)
if payment.nil?
Rails.logger.warn "Paypal payouts: unique_id #{payment_unique_id} didn't correspond to a payment ID"
return
end
payment.with_lock do
split_payment_index = split_payment_number - 1 # split_payment_number is 1-based.
split_payment_info = payment.split_payments_info[split_payment_index]
return unless %w[processing pending].include?(split_payment_info["state"])
split_payment_info["txn_id"] = paypal_event["masspay_txn_id"]
split_payment_info["state"] = paypal_event["status"].try(:downcase)
payment.processor_fee_cents += 100 * paypal_event["mc_fee"].to_f if paypal_event["mc_fee"]
payment.save!
# Paypal is sending incorrect payment status ('Pending') in the IPN callback for some of the payments where the
# actual status is either 'Unclaimed' or 'Completed'. Until the issue is resolved at Paypal, we get the actual
# status using another API call to Paypal.
# Ref: https://github.com/gumroad/web/issues/9474
UpdatePayoutStatusWorker.perform_in(5.minutes, payment.id) if split_payment_info["state"] == "pending"
update_split_payment_state(payment)
end
end
def self.update_split_payment_state(payment)
split_payment_states = payment.split_payments_info.map { |payment_info| payment_info["state"] }
all_split_payments_completed = split_payment_states.all? { |state| state == "completed" }
all_split_payments_failed = split_payment_states.all? { |state| state == "failed" }
no_split_payments_are_processing = split_payment_states.none? { |state| %w[processing pending].include?(state) }
if all_split_payments_completed
payment.txn_id = SPLIT_PAYMENT_TXN_ID
payment.mark_completed!
elsif all_split_payments_failed
payment.mark_failed!
elsif no_split_payments_are_processing
# This means that no split payments are in the processing state. It also means that some of them have failed and some have succeeded.
Bugsnag.notify("Payment id #{payment.id} was split and some of the split payments failed and some succeeded")
end
end
def self.get_latest_payment_state_from_paypal(amount_cents, transaction_id, start_date, current_state)
params = PAYPAL_API_PARAMS.merge("METHOD" => "TransactionSearch", "TRANSACTIONCLASS" => "Sent")
amt_str = format("%.2f", (amount_cents / 100.0).to_s)
paypal_response = HTTParty.post(PAYPAL_ENDPOINT, body: params.merge("AMT" => amt_str,
"TRANSACTIONID" => transaction_id,
"STARTDATE" => start_date.iso8601))
response = Rack::Utils.parse_nested_query(paypal_response.parsed_response)
# Discard if the data we need is missing, or there is more than one search result, or the status is anything other than 'Unclaimed' or 'Completed'.
if response["L_STATUS0"].blank? || response["L_AMT0"].blank? || response["L_TRANSACTIONID0"].blank? || response["L_FEEAMT0"].blank? ||
response["L_TIMESTAMP1"].present? ||
%w[unclaimed completed].exclude?(response["L_STATUS0"].downcase)
current_state
else
response["L_STATUS0"].downcase
end
end
def self.search_payment_on_paypal(amount_cents:, transaction_id: nil, payment_address: nil, start_date:, end_date: nil)
return if transaction_id.blank? && payment_address.blank?
params = PAYPAL_API_PARAMS.merge("METHOD" => "TransactionSearch", "TRANSACTIONCLASS" => "Sent")
amt_str = format("%.2f", (amount_cents / 100.0).to_s)
paypal_response = if transaction_id.present?
HTTParty.post(PAYPAL_ENDPOINT, body: params.merge("TRANSACTIONID" => transaction_id,
"STARTDATE" => start_date.iso8601))
else
HTTParty.post(PAYPAL_ENDPOINT, body: params.merge("AMT" => amt_str,
"EMAIL" => payment_address,
"STARTDATE" => start_date.iso8601,
"ENDDATE" => end_date.iso8601))
end
response = Rack::Utils.parse_nested_query(paypal_response.parsed_response)
if response["L_STATUS0"].present? && response["L_STATUS1"].present? && response["L_STATUS2"].blank? &&
transaction_id.in?([response["L_TRANSACTIONID0"], response["L_TRANSACTIONID1"]]) &&
Set.new([response["L_AMT0"], response["L_AMT1"]]) == Set.new([amt_str, "-#{amt_str}"])
# If the transaction is reversed or returned or cancelled, PayPal returns both the original transaction
# and the reversed/returned/cancelled transaction, when searched with the original transaction ID.
# In that case, return proper reversed/returned/cancelled state.
if Set.new([response["L_STATUS0"].downcase, response["L_STATUS1"].downcase]) == Set.new([Payment::COMPLETED, Payment::REVERSED])
{ state: Payment::REVERSED, transaction_id: response["L_TRANSACTIONID0"], correlation_id: response["CORRELATIONID"], paypal_fee: response["L_FEEAMT0"] }
elsif Set.new([response["L_STATUS0"].downcase, response["L_STATUS1"].downcase]) == Set.new([Payment::COMPLETED, "canceled"])
{ state: Payment::CANCELLED, transaction_id: response["L_TRANSACTIONID0"], correlation_id: response["CORRELATIONID"], paypal_fee: response["L_FEEAMT0"] }
elsif Set.new([response["L_STATUS0"].downcase, response["L_STATUS1"].downcase]) == Set.new([Payment::COMPLETED, Payment::RETURNED])
{ state: Payment::RETURNED, transaction_id: response["L_TRANSACTIONID0"], correlation_id: response["CORRELATIONID"], paypal_fee: response["L_FEEAMT0"] }
else
# If two transactions are returned and they are not original and reversed/returned/canceled, raise an error as this shouldn't happen.
raise "Multiple PayPal transactions found for #{payment_address} with amount #{amt_str} between #{start_date} and #{end_date}"
end
elsif response["L_STATUS0"].present? && response["L_STATUS1"].present?
# If multiple transactions are returned and they are not original and reversed/returned/canceled, raise an error as this shouldn't happen.
raise "Multiple PayPal transactions found for #{payment_address} with amount #{amt_str} between #{start_date} and #{end_date}"
elsif response["L_STATUS0"].present?
# If only one transaction is returned, return that transaction's current state.
{ state: response["L_STATUS0"].downcase, transaction_id: response["L_TRANSACTIONID0"], correlation_id: response["CORRELATIONID"], paypal_fee: response["L_FEEAMT0"] }
else
# If we did not have a transaction ID and searched using payment address,
# it's possible that the transaction was never made on PayPal.
return if transaction_id.blank?
# But if we had a transaction ID we should find a corresponding transaction on PayPal,
# raise an error if that's not the case.
raise "No PayPal transaction found for transaction ID #{transaction_id} and amount #{amt_str}"
end
end
def self.note_for_paypal_payment(payment)
user = payment.user
legal_entity_name = user.alive_user_compliance_info&.legal_entity_name.presence || user.name_or_username
"#{legal_entity_name}, selling digital products / memberships"
end
def self.current_paypal_balance_cents
paypal_response = HTTParty.post(PAYPAL_ENDPOINT, body: PAYPAL_API_PARAMS.merge("METHOD" => "GetBalance"))
response = Rack::Utils.parse_nested_query(paypal_response.parsed_response)
(response["L_AMT0"].to_d * 100).to_i
end
# This method assumes that each topup is made for $100,000.
# We've always made topups in chunks of $100,000 so far.
# If that ever changes, this method will need to be updated accordingly.
# The bank account transfer transactions are not searchable by type,
# so using the $100,000 amount to easily search for them here.
def self.topup_amount_in_transit
individual_topup_amount = 100000
params = PAYPAL_API_PARAMS.merge("METHOD" => "TransactionSearch",
"AMT" => individual_topup_amount.to_s,
"STARTDATE" => 2.weeks.ago.iso8601) # Topups older than 2 weeks should have already completed
paypal_response = HTTParty.post(PAYPAL_ENDPOINT, body: params)
response = Rack::Utils.parse_nested_query(paypal_response.parsed_response)
return 0 unless %w[Success SuccessWithWarning].include?(response["ACK"])
topup_amount = 0
number_of_topups_made = response.keys.select { _1.include?("L_TRANSACTIONID") }.count
number_of_topups_made.times do |i|
topup_amount += individual_topup_amount if response["L_TYPE#{i}"] == "Transfer" &&
response["L_NAME#{i}"] == "Bank Account" &&
response["L_STATUS#{i}"] == "Uncleared" &&
response["L_AMT#{i}"].to_i == individual_topup_amount
end
topup_amount
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/integrations/paypal_integration_rest_api.rb | app/business/payments/integrations/paypal_integration_rest_api.rb | # frozen_string_literal: true
class PaypalIntegrationRestApi
include HTTParty
base_uri PAYPAL_REST_ENDPOINT
attr_reader :merchant, :response, :options
def initialize(merchant, options = {})
@merchant = merchant
@options = options
end
# Create a partner (Gumroad) referral for the given merchant which pre-fills the data when that merchant signs up for
# a PayPal account.
def create_partner_referral(return_url)
self.class.post("/v2/customer/partner-referrals",
headers: partner_referral_headers,
body: partner_referral_data(return_url).to_json)
end
# Get status of merchant account from PayPal using merchant account id.
def get_merchant_account_by_merchant_id(paypal_merchant_id)
self.class.get("/v1/customer/partners/#{PAYPAL_PARTNER_ID}/merchant-integrations/#{paypal_merchant_id}",
headers: partner_referral_headers)
end
private
def timestamp
Time.current.to_i.to_s
end
def partner_referral_headers
{
"Content-Type" => "application/json",
"Authorization" => options[:authorization_header]
}
end
def partner_referral_data(return_url)
{
tracking_id: merchant.external_id + "-" + timestamp,
email: merchant.email,
partner_config_override: {
return_url:,
partner_logo_url: GUMROAD_LOGO_URL
},
operations: [
{
operation: "API_INTEGRATION",
api_integration_preference: {
rest_api_integration: {
integration_method: "PAYPAL",
integration_type: "THIRD_PARTY",
third_party_details: {
features: %w(PAYMENT REFUND PARTNER_FEE DELAY_FUNDS_DISBURSEMENT ACCESS_MERCHANT_INFORMATION READ_SELLER_DISPUTE)
}
}
}
}
],
products: [
"EXPRESS_CHECKOUT"
],
legal_consents: [
{
type: "SHARE_DATA_CONSENT",
granted: true
}
]
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/integrations/paypal_partner_rest_credentials.rb | app/business/payments/integrations/paypal_partner_rest_credentials.rb | # frozen_string_literal: true
class PaypalPartnerRestCredentials
REDIS_KEY_STORAGE_NS = Redis::Namespace.new(:paypal_partner_rest_auth_token, redis: $redis)
TOKEN_KEY = "token_header"
API_RETRY_TIMEOUT_IN_SECONDS = 2 # Number of seconds before the API request is retried on failure
API_MAX_TRIES = 3 # Number of times the API request will be made including retries
include HTTParty
base_uri PAYPAL_REST_ENDPOINT
headers("Accept" => "application/json",
"Accept-Language" => "en_US")
def auth_token
load_token || generate_token
end
private
def load_token
REDIS_KEY_STORAGE_NS.get(TOKEN_KEY)
end
def generate_token
store_token(request_for_api_token)
end
def request_for_api_token
tries ||= API_MAX_TRIES
self.class.post("/v1/oauth2/token",
body: {
"grant_type" => "client_credentials"
},
basic_auth: {
username: PAYPAL_PARTNER_CLIENT_ID,
password: PAYPAL_PARTNER_CLIENT_SECRET
})
rescue *INTERNET_EXCEPTIONS => exception
if (tries -= 1).zero?
raise exception
else
sleep(API_RETRY_TIMEOUT_IN_SECONDS)
retry
end
end
def store_token(response)
auth_token = "#{response['token_type']} #{response['access_token']}"
REDIS_KEY_STORAGE_NS.set(TOKEN_KEY, auth_token)
REDIS_KEY_STORAGE_NS.expire(TOKEN_KEY, response["expires_in"].to_i)
auth_token
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/user_compliance_info_field_property.rb | app/business/payments/merchant_registration/user_compliance_info_field_property.rb | # frozen_string_literal: true
# Information about the fields stored in UserComplianceInfo, such as min/max lengths, etc.
module UserComplianceInfoFieldProperty
LENGTH = "length"
FILTER = "filter"
PROPERTIES = {
Compliance::Countries::USA.alpha2 => {
UserComplianceInfoFields::Individual::TAX_ID => { LENGTH => 9, FILTER => /[A-Za-z0-9]+/ },
UserComplianceInfoFields::Business::TAX_ID => { FILTER => /[A-Za-z0-9]+/ }
}
}.freeze
private_constant :PROPERTIES
def self.property_for_field(user_compliance_info_field, property, country:)
PROPERTIES[country].try(:[], user_compliance_info_field).try(:[], property)
end
def self.name_tag_for_field(user_compliance_info_field, country:)
case user_compliance_info_field
when "bank_account"
"Bank Account"
when "bank_account_statement"
"Bank Statement"
when "birthday"
"Date of birth"
when "business_name"
"Business name"
when "business_phone_number"
"Business phone number"
when "business_street_address"
"Address"
when "business_tax_id"
case country
when "US"
"Business EIN"
when "AU"
"Australian Business Number (ABN)"
when "CA"
"Business Number (BN)"
when "GB"
"Company Number (CRN)"
when "NO"
"Norway VAT ID Number (MVA)"
else
"Business tax ID"
end
when "business_vat_id_number"
"Business VAT ID Number"
when "first_name"
"First name"
when "individual_tax_id"
case country
when "US"
"Social Security Number (SSN)"
when "AU"
"Australian Business Number (ABN)"
when "CA"
"Social Insurance Number (SIN)"
when "GB"
"Unique Taxpayer Reference (UTR)"
when "NO"
"Norway VAT ID Number (MVA)"
else
"Individual tax ID"
end
when "last_name"
"Last name"
when "legal_entity_street_address"
"Address"
when "memorandum_of_association"
"Memorandum of Association"
when "proof_of_registration"
"Proof of Registration"
when "company_registration_verification"
"Company Registration"
when "passport"
"Passport"
when "phone_number"
"Phone number"
when "power_of_attorney"
"Power of Attorney"
when "street_address"
"Personal address"
when "stripe_additional_document_id"
"An ID or a utility bill with address"
when "stripe_company_document_id"
country == "AE" ? "Trade License issued within the UAE" : "Company registration document"
when "stripe_enhanced_identity_verification"
"Enhanced Identity Verification"
when "stripe_identity_document_id"
country == "AE" ? "Emirates ID" : "Government-issued photo ID"
when "visa"
"Visa"
else
user_compliance_info_field.split(".").last.humanize
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/user_compliance_info_fields.rb | app/business/payments/merchant_registration/user_compliance_info_fields.rb | # frozen_string_literal: true
# Fields that can be requested in a UserComplianceInfoRequest.
# Some fields map onto the UserComplianceInfo model, while others do not.
module UserComplianceInfoFields
# The following fields are attributes of UserComplianceInfo and can be referenced
# in requests for user compliance information. See UserComplianceInfoRequest.
IS_BUSINESS = "is_business"
module Individual
FIRST_NAME = "first_name"
LAST_NAME = "last_name"
DATE_OF_BIRTH = "birthday"
TAX_ID = "individual_tax_id"
STRIPE_IDENTITY_DOCUMENT_ID = "stripe_identity_document_id"
STRIPE_ADDITIONAL_DOCUMENT_ID = "stripe_additional_document_id"
STRIPE_ENHANCED_IDENTITY_VERIFICATION = "stripe_enhanced_identity_verification"
PHONE_NUMBER = "phone_number"
PASSPORT = "passport"
VISA = "visa"
POWER_OF_ATTORNEY = "power_of_attorney"
module Address
STREET = "street_address"
CITY = "city"
STATE = "state"
ZIP_CODE = "zip_code"
COUNTRY = "country"
end
end
module Business
NAME = "business_name"
TAX_ID = "business_tax_id"
STRIPE_COMPANY_DOCUMENT_ID = "stripe_company_document_id"
PHONE_NUMBER = "business_phone_number"
VAT_NUMBER = "business_vat_id_number"
BANK_STATEMENT = "bank_account_statement"
MEMORANDUM_OF_ASSOCIATION = "memorandum_of_association"
PROOF_OF_REGISTRATION = "proof_of_registration"
COMPANY_REGISTRATION_VERIFICATION = "company_registration_verification"
module Address
STREET = "business_street_address"
CITY = "business_city"
STATE = "business_state"
ZIP_CODE = "business_zip_code"
COUNTRY = "business_country"
end
end
module LegalEntity
module Address
STREET = "legal_entity_street_address"
CITY = "legal_entity_city"
STATE = "legal_entity_state"
ZIP_CODE = "legal_entity_zip_code"
COUNTRY = "legal_entity_country"
end
end
# The following fields are not found on UserComplianceInfo, and are stored in other
# objects, but conceptually make up compliance information requested for by
# the external parties facilitating our merchant registration.
BANK_ACCOUNT = "bank_account"
ALL_FIELDS_ON_USER_COMPLIANCE_INFO = [
IS_BUSINESS,
Individual::FIRST_NAME,
Individual::LAST_NAME,
Individual::DATE_OF_BIRTH,
Individual::TAX_ID,
Individual::STRIPE_IDENTITY_DOCUMENT_ID,
Individual::STRIPE_ADDITIONAL_DOCUMENT_ID,
Individual::Address::STREET,
Individual::Address::CITY,
Individual::Address::STATE,
Individual::Address::ZIP_CODE,
Individual::Address::COUNTRY,
Business::NAME,
Business::TAX_ID,
Business::STRIPE_COMPANY_DOCUMENT_ID,
Business::Address::STREET,
Business::Address::CITY,
Business::Address::STATE,
Business::Address::ZIP_CODE,
Business::Address::COUNTRY,
LegalEntity::Address::STREET,
LegalEntity::Address::CITY,
LegalEntity::Address::STATE,
LegalEntity::Address::ZIP_CODE,
LegalEntity::Address::COUNTRY
].freeze
ALL_ADDITIONAL_FIELDS = [
BANK_ACCOUNT
].freeze
ALL = ALL_FIELDS_ON_USER_COMPLIANCE_INFO + ALL_ADDITIONAL_FIELDS
VERIFICATION_PROMPT_FIELDS = [
Individual::TAX_ID,
Business::VAT_NUMBER,
Individual::STRIPE_IDENTITY_DOCUMENT_ID,
Individual::STRIPE_ADDITIONAL_DOCUMENT_ID,
Business::STRIPE_COMPANY_DOCUMENT_ID,
Individual::PASSPORT,
Individual::VISA,
Individual::POWER_OF_ATTORNEY,
Business::MEMORANDUM_OF_ASSOCIATION,
Business::BANK_STATEMENT,
Business::PROOF_OF_REGISTRATION,
Business::COMPANY_REGISTRATION_VERIFICATION,
Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION
].freeze
private_constant :ALL, :ALL_ADDITIONAL_FIELDS, :ALL_FIELDS_ON_USER_COMPLIANCE_INFO
def self.all_fields_on_user_compliance_info
ALL_FIELDS_ON_USER_COMPLIANCE_INFO
end
def self.all_additional_fields
ALL_ADDITIONAL_FIELDS
end
def self.all
ALL
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/errors/merchant_registration_user_not_ready_error.rb | app/business/payments/merchant_registration/errors/merchant_registration_user_not_ready_error.rb | # frozen_string_literal: true
class MerchantRegistrationUserNotReadyError < GumroadRuntimeError
def initialize(user_id, message_why_not_ready)
super("User #{user_id} #{message_why_not_ready}.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/errors/merchant_registration_user_already_has_account_error.rb | app/business/payments/merchant_registration/errors/merchant_registration_user_already_has_account_error.rb | # frozen_string_literal: true
class MerchantRegistrationUserAlreadyHasAccountError < GumroadRuntimeError
def initialize(user_id, charge_processor_id)
super("User #{user_id} already has a merchant account for charge processor #{charge_processor_id}.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/implementations/stripe/stripe_user_compliance_info_field_map.rb | app/business/payments/merchant_registration/implementations/stripe/stripe_user_compliance_info_field_map.rb | # frozen_string_literal: true
module StripeUserComplianceInfoFieldMap
MAP_STRIPE_FIELD_TO_INTERNAL_FIELD = {
"business_type" => UserComplianceInfoFields::IS_BUSINESS,
"individual.first_name" => UserComplianceInfoFields::Individual::FIRST_NAME,
"individual.last_name" => UserComplianceInfoFields::Individual::LAST_NAME,
"individual.dob.day" => UserComplianceInfoFields::Individual::DATE_OF_BIRTH,
"individual.dob.month" => UserComplianceInfoFields::Individual::DATE_OF_BIRTH,
"individual.dob.year" => UserComplianceInfoFields::Individual::DATE_OF_BIRTH,
"individual.ssn_last_4" => UserComplianceInfoFields::Individual::TAX_ID,
"individual.id_number" => UserComplianceInfoFields::Individual::TAX_ID,
"individual.verification.document" => UserComplianceInfoFields::Individual::STRIPE_IDENTITY_DOCUMENT_ID,
"individual.verification.additional_document" => UserComplianceInfoFields::Individual::STRIPE_ADDITIONAL_DOCUMENT_ID,
"individual.verification.proof_of_liveness" => UserComplianceInfoFields::Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION,
"company.verification.document" => UserComplianceInfoFields::Business::STRIPE_COMPANY_DOCUMENT_ID,
"documents.company_license.files" => UserComplianceInfoFields::Business::STRIPE_COMPANY_DOCUMENT_ID,
"documents.company_memorandum_of_association.files" => UserComplianceInfoFields::Business::MEMORANDUM_OF_ASSOCIATION,
"documents.company_registration_verification.files" => UserComplianceInfoFields::Business::COMPANY_REGISTRATION_VERIFICATION,
"documents.proof_of_registration.files" => UserComplianceInfoFields::Business::PROOF_OF_REGISTRATION,
"documents.bank_account_ownership_verification.files" => UserComplianceInfoFields::Business::BANK_STATEMENT,
"individual.documents.passport.files" => UserComplianceInfoFields::Individual::PASSPORT,
"individual.documents.visa.files" => UserComplianceInfoFields::Individual::VISA,
"individual.documents.company_authorization.files" => UserComplianceInfoFields::Individual::POWER_OF_ATTORNEY,
"individual.address.line1" => UserComplianceInfoFields::Individual::Address::STREET,
"individual.address.city" => UserComplianceInfoFields::Individual::Address::CITY,
"individual.address.state" => UserComplianceInfoFields::Individual::Address::STATE,
"individual.address.postal_code" => UserComplianceInfoFields::Individual::Address::ZIP_CODE,
"individual.address.country" => UserComplianceInfoFields::Individual::Address::COUNTRY,
"individual.phone" => UserComplianceInfoFields::Individual::PHONE_NUMBER,
"business_profile.name" => UserComplianceInfoFields::Business::NAME,
"company.name" => UserComplianceInfoFields::Business::NAME,
"company.tax_id" => UserComplianceInfoFields::Business::TAX_ID,
"company.business_vat_id_number" => UserComplianceInfoFields::Business::VAT_NUMBER,
"company.address.line1" => UserComplianceInfoFields::LegalEntity::Address::STREET,
"company.address.city" => UserComplianceInfoFields::LegalEntity::Address::CITY,
"company.address.state" => UserComplianceInfoFields::LegalEntity::Address::STATE,
"company.address.postal_code" => UserComplianceInfoFields::LegalEntity::Address::ZIP_CODE,
"company.address.country" => UserComplianceInfoFields::LegalEntity::Address::COUNTRY,
"company.phone" => UserComplianceInfoFields::Business::PHONE_NUMBER,
"external_account" => UserComplianceInfoFields::BANK_ACCOUNT
}.freeze
MAP_STRIPE_FIELD_TO_OPTIONS = {
"individual.ssn_last_4" => { only_needs_field_to_be_partially_provided: true }
}.freeze
private_constant :MAP_STRIPE_FIELD_TO_INTERNAL_FIELD, :MAP_STRIPE_FIELD_TO_OPTIONS
def self.map(stripe_field)
MAP_STRIPE_FIELD_TO_INTERNAL_FIELD[stripe_field]
end
def self.options_for_field(stripe_field)
MAP_STRIPE_FIELD_TO_OPTIONS[stripe_field] || {}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/implementations/stripe/stripe_merchant_account_manager.rb | app/business/payments/merchant_registration/implementations/stripe/stripe_merchant_account_manager.rb | # frozen_string_literal: true
module StripeMerchantAccountManager
REQUESTED_CAPABILITIES = %w(card_payments transfers)
CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES = %w(transfers)
COUNTRIES_SUPPORTED_BY_STRIPE_CONNECT = ["Australia", "Austria", "Belgium", "Brazil", "Bulgaria", "Canada", "Croatia",
"Cyprus", "Czechia", "Denmark", "Estonia", "Finland", "France",
"Germany", "Gibraltar", "Greece", "Hong Kong", "Hungary", "Ireland", "Italy",
"Japan", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg",
"Malta", "Netherlands", "New Zealand", "Norway", "Poland", "Portugal",
"Romania", "Singapore", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland",
"United Arab Emirates", "United Kingdom", "United States"].map { |country_name| Compliance::Countries.find_by_name(country_name).alpha2 }
# Use "CEO" as the default title for all Stripe custom connect account owners for now.
DEFAULT_RELATIONSHIP_TITLE = "CEO"
def self.create_account(user, passphrase:, from_admin: false)
tos_agreement = nil
user_compliance_info = nil
bank_account = nil
account_params = {}
merchant_account = nil
ActiveRecord::Base.connection.stick_to_primary!
user.with_lock do
raise MerchantRegistrationUserNotReadyError.new(user.id, "is not supported yet") unless user.native_payouts_supported?
user_has_a_merchant_account = if from_admin
user_has_stripe_connect_merchant_account?(user)
else
user.merchant_accounts.alive.stripe.find { |ma| !ma.is_a_stripe_connect_account? }.present?
end
raise MerchantRegistrationUserAlreadyHasAccountError.new(user.id, StripeChargeProcessor.charge_processor_id) if user_has_a_merchant_account
raise MerchantRegistrationUserNotReadyError.new(user.id, "has not agreed to TOS") if user.tos_agreements.empty?
tos_agreement = user.tos_agreements.last
user_compliance_info = user.alive_user_compliance_info
bank_account = user.active_bank_account
country_code = user_compliance_info.legal_entity_country_code
raise MerchantRegistrationUserNotReadyError.new(user.id, "does not have a legal entity country") if country_code.blank?
country = Country.new(country_code)
currency = country.payout_currency
raise MerchantRegistrationUserNotReadyError.new(user.id, "has no default currency defined for it's legal entity's country") if currency.blank?
# Stripe doesn't let us use non-USD bank accounts in the test environment, so we allow a USD bank account to be associated with a non-USD account
# outside of production to facilitate testing and debugging.
raise MerchantRegistrationUserNotReadyError.new(user.id, "has #{bank_account.type} #{bank_account.currency} that != #{country_code} #{currency}.") if Rails.env.production? && bank_account && bank_account.currency != currency
capabilities = country.stripe_capabilities
account_params = {
type: "custom",
requested_capabilities: capabilities,
country: country_code,
default_currency: currency
}
account_params.deep_merge!(account_hash(user, tos_agreement, user_compliance_info, passphrase:))
account_params.deep_merge!(bank_account_hash(bank_account, passphrase:)) if bank_account && !bank_account.is_a?(CardBankAccount)
merchant_account = MerchantAccount.create!(
user:,
country: country_code,
currency:,
charge_processor_id: StripeChargeProcessor.charge_processor_id
)
end
stripe_account = Stripe::Account.create(account_params)
merchant_account.charge_processor_merchant_id = stripe_account.id
merchant_account.save!
if user_compliance_info.is_business?
person_params = person_hash(user_compliance_info, passphrase)
person_params.deep_merge!(relationship: { representative: true, owner: true, title: user_compliance_info.job_title.presence || DEFAULT_RELATIONSHIP_TITLE, percent_ownership: 100 })
Stripe::Account.create_person(stripe_account.id, person_params)
end
# We need to update with empty full_name_aliases here as setting full_name_aliases is mandatory for Singapore accounts.
# It is a property on the `person` entity associated with the Stripe::Account.
# Ref: https://stripe.com/docs/api/persons/object#person_object-full_name_aliases
if user_compliance_info.country_code == Compliance::Countries::SGP.alpha2
stripe_person = Stripe::Account.list_persons(stripe_account.id)["data"].last
Stripe::Account.update_person(stripe_account.id, stripe_person.id, { full_name_aliases: [""] }) if stripe_person.present?
end
merchant_account.charge_processor_alive_at = Time.current
merchant_account.save!
# Non-Card bank accounts are saved at account creation time.
#
# Card bank accounts are saved when we are notified via account.updated event that charges are enabled on the account
# because token generation fails unless charges are enabled.
if bank_account && !bank_account.is_a?(CardBankAccount)
save_stripe_bank_account_info(bank_account, stripe_account)
end
begin
DefaultAbandonedCartWorkflowGeneratorService.new(seller: user).generate if merchant_account.is_a_stripe_connect_account?
rescue => e
Rails.logger.error("Failed to generate default abandoned cart workflow for user #{user.id}: #{e.message}")
Bugsnag.notify(e)
end
merchant_account
rescue Stripe::StripeError => e
merchant_account.mark_deleted! if merchant_account.present? && merchant_account.charge_processor_merchant_id.blank?
Bugsnag.notify(e)
raise
end
def self.delete_account(merchant_account)
stripe_account = Stripe::Account.retrieve(merchant_account.charge_processor_merchant_id)
result = stripe_account.delete
if result.deleted
merchant_account.charge_processor_deleted_at = Time.current
merchant_account.save!
end
result.deleted
end
def self.update_account(user, passphrase:)
validate_for_update(user)
stripe_account = Stripe::Account.retrieve(user.stripe_account.charge_processor_merchant_id)
last_user_compliance_info = UserComplianceInfo.find_by_external_id(stripe_account["metadata"]["user_compliance_info_id"])
tos_agreement = user.tos_agreements.last
user_compliance_info = user.alive_user_compliance_info
last_attributes = account_hash(user, nil, last_user_compliance_info, passphrase:)
current_attributes = account_hash(user, tos_agreement, user_compliance_info, passphrase:)
last_attributes[:metadata] = {}
last_attributes[:business_profile] = {}
if user_compliance_info.is_business?
last_attributes.delete(:individual)
if last_attributes[:company].present? && user_compliance_info.country_code == Compliance::Countries::USA.alpha2
last_attributes[:company][:structure] = nil
end
last_attributes.delete(:business_type) if user_compliance_info.country_code == Compliance::Countries::CAN.alpha2
else
last_attributes.delete(:company)
end
if last_attributes[:individual].present?
last_attributes[:individual][:email] = nil
last_attributes[:individual][:phone] = nil
last_attributes[:individual][:relationship] = nil if user_compliance_info.country_code == Compliance::Countries::CAN.alpha2
end
if last_attributes[:company].present?
last_attributes[:company][:directors_provided] = nil
last_attributes[:company][:executives_provided] = nil
end
diff_attributes = get_diff_attributes(current_attributes, last_attributes)
# If we have a full SSN, don't send the last 4 digits at the same time. If the last 4 digits are from a previous
# compliance info and don't match the new full SSN, this will result in an invalid request.
diff_attributes[:individual].delete(:ssn_last_4) if diff_attributes[:individual] && diff_attributes[:individual][:id_number].present?
if user_compliance_info.is_individual? && diff_attributes[:individual][:dob].present?
# Re-add the full DOB field if any part of it is being kept. Stripe handles this field inconsistently and the full DOB
# must be submitted if any part of it is changing.
diff_attributes[:individual][:dob] = current_attributes[:individual][:dob]
end
if last_user_compliance_info&.is_business? && user_compliance_info.is_individual?
# Set the company's name to the individual's first and last name so that this is used as the Stripe account name and during payouts
# Ref: https://github.com/gumroad/web/issues/19882
diff_attributes[:company] = { name: user_compliance_info.first_and_last_name }
end
# Only set structure for US accounts
if user_compliance_info.is_business? &&
user_compliance_info.country_code == Compliance::Countries::USA.alpha2 &&
user_compliance_info.business_type == UserComplianceInfo::BusinessTypes::SOLE_PROPRIETORSHIP
diff_attributes[:company] ||= {}
diff_attributes[:company][:structure] = user_compliance_info.business_type
end
capabilities = Country.new(user_compliance_info.legal_entity_country_code).stripe_capabilities
# Always request the capabilities assigned at account creation, plus any additional capabilities that the account already has (such as tax reporting
# capability that we request "manually" for some accounts during tax season).
capabilities = capabilities.map(&:to_sym) | stripe_account.capabilities.keys
diff_attributes[:capabilities] = capabilities.index_with { |capability| { requested: true } }
Stripe::Account.update(stripe_account.id, diff_attributes)
if user_compliance_info.is_business?
update_person(user, stripe_account, last_user_compliance_info&.external_id, passphrase)
end
end
def self.update_person(user, stripe_account, last_user_compliance_info_id, passphrase)
stripe_person = Stripe::Account.list_persons(stripe_account.id)["data"].last
last_user_compliance_info = UserComplianceInfo.find_by_external_id(last_user_compliance_info_id)
user_compliance_info = user.alive_user_compliance_info
current_attributes = person_hash(user_compliance_info, passphrase)
current_attributes.deep_merge!(relationship: { representative: true, owner: true, title: user_compliance_info.job_title.presence || DEFAULT_RELATIONSHIP_TITLE, percent_ownership: 100 })
diff_attributes = current_attributes
last_attributes = person_hash(last_user_compliance_info, passphrase)
if last_attributes
last_attributes[:email] = nil
last_attributes[:phone] = nil
diff_attributes = get_diff_attributes(current_attributes, last_attributes)
end
if diff_attributes[:dob].present?
# Re-add the full DOB field if any part of it is being kept. Stripe handles this field inconsistently and the full DOB
# must be submitted if any part of it is changing.
diff_attributes[:dob] = current_attributes[:dob]
end
Stripe::Account.update_person(stripe_account.id, stripe_person.id, diff_attributes)
end
def self.get_diff_attributes(current_attributes, last_attributes)
# Stripe will error if we send unchanged data for locked fields of a verified user.
# To work around this, we send only attributes that are not in last_attributes or are different in current_attributes.
# Attributes that are the same will be marked with the object, then removed after merging.
reject_marker = Object.new
diff_attributes = current_attributes.deep_merge(last_attributes) do |_key, current_value, last_value|
if current_value == last_value
reject_marker
else
current_value
end
end
# Remove attributes that were marked for rejection, or are an empty hash.
diff_attributes.deep_reject! do |_key, value|
if value.is_a?(Hash)
value.empty?
else
value == reject_marker
end
end
end
def self.update_bank_account(user, passphrase:)
validate_for_update(user)
bank_account = user.active_bank_account
raise MerchantRegistrationUserNotReadyError.new(user.id, "does not have a bank account") if bank_account.nil?
stripe_account = Stripe::Account.retrieve(user.stripe_account.charge_processor_merchant_id)
return if stripe_account["metadata"]["bank_account_id"] == bank_account.external_id
attributes = bank_account_hash(bank_account, stripe_account:, passphrase:)
Stripe::Account.update(stripe_account.id, attributes)
save_stripe_bank_account_info(bank_account, stripe_account.refresh)
rescue Stripe::InvalidRequestError => e
return ContactingCreatorMailer.invalid_bank_account(user.id).deliver_later(queue: "critical") if e.message["Invalid account number"] ||
e.message["couldn't find that transit"] || e.message["previous attempts to deliver payouts"]
Bugsnag.notify(e)
rescue Stripe::CardError => e
Rails.logger.error "Stripe::CardError request ID #{e.request_id} when updating bank account #{bank_account.id} for stripe account #{stripe_account.inspect}"
raise e
end
def self.disconnect(user:)
return false unless user.stripe_disconnect_allowed?
user.stripe_connect_account.delete_charge_processor_account!
user.check_merchant_account_is_linked = false
user.save!
# We deleted creator's gumroad-controlled Stripe account when they connected their own Stripe account.
# Ref: User::OmniauthCallbacksController#stripe_connect.
# Now when they are disconnecting their own Stripe account, we try and reactivate their old gumroad-controlled Stripe account.
# Their old Stripe account is the one associated with any unpaid balance, or with their active bank account
# as we didn't delete the active bank account when they connected their own Stripe account.
stripe_account = user.merchant_accounts.stripe.where(id: user.unpaid_balances.pluck(:merchant_account_id).uniq).last
stripe_account ||= user.merchant_accounts.stripe.where(charge_processor_merchant_id: user.active_bank_account&.stripe_connect_account_id).last
return true if stripe_account.blank? || stripe_account.charge_processor_merchant_id.blank?
stripe_account.deleted_at = stripe_account.charge_processor_deleted_at = nil
stripe_account.charge_processor_alive_at = Time.current
stripe_account.save!
end
private_class_method
def self.save_stripe_bank_account_info(bank_account, stripe_account)
# We replace the bank account whenever adding a new one, so there will only be one in the list.
stripe_external_account = stripe_account.external_accounts.first
bank_account.stripe_connect_account_id = stripe_account.id
bank_account.stripe_external_account_id = stripe_external_account.id
bank_account.stripe_fingerprint = stripe_external_account.fingerprint
bank_account.save!
end
private_class_method
def self.validate_for_update(user)
unless user.stripe_account
raise MerchantRegistrationUserNotReadyError
.new(user.id, "does not have a Stripe merchant account")
end
end
private_class_method
def self.user_has_stripe_connect_merchant_account?(user)
# It's really important we don't have two merchant accounts per user, so we do this check on the master database
# to ensure we're looking at the latest data.
ActiveRecord::Base.connection.stick_to_primary!
user.stripe_account.present?
end
private_class_method
def self.account_hash(user, tos_agreement, user_compliance_info, passphrase:)
hash = {
metadata: {
user_id: user.external_id
}
}
if tos_agreement
tos_acceptance = {
date: tos_agreement.created_at.to_time.to_i,
ip: tos_agreement.ip
}
cross_border_payouts_only = Country.new(user_compliance_info.legal_entity_country_code).supports_stripe_cross_border_payouts?
tos_acceptance[:service_agreement] = "recipient" if cross_border_payouts_only
hash.deep_merge!(
tos_acceptance:,
metadata: {
tos_agreement_id: tos_agreement.external_id
}
)
end
if user_compliance_info
hash.deep_merge!(
metadata: {
user_compliance_info_id: user_compliance_info.external_id
},
business_type: if user_compliance_info.is_business?
if user_compliance_info.legal_entity_country_code == Compliance::Countries::CAN.alpha2 &&
%w(non_profit registered_charity).include?(user_compliance_info.business_type)
"non_profit"
else
"company"
end
else
"individual"
end,
business_profile: {
name: user_compliance_info.legal_entity_name,
url: user.business_profile_url,
product_description: user_compliance_info.legal_entity_name
}
)
if [Compliance::Countries::ARE.alpha2, Compliance::Countries::CAN.alpha2].include?(user_compliance_info.country_code)
hash[:business_profile][:support_phone] = user_compliance_info.business_phone
end
if user_compliance_info.is_business?
hash.deep_merge!(company_hash(user_compliance_info, passphrase))
else
hash.deep_merge!(
individual: person_hash(user_compliance_info, passphrase)
)
end
end
hash.deep_values_strip!
end
private_class_method
def self.bank_account_hash(bank_account, stripe_account: {}, passphrase:)
country_code = bank_account.user.alive_user_compliance_info.legal_entity_country_code
cross_border_payouts_only = Country.new(country_code).supports_stripe_cross_border_payouts?
bank_account_field =
if bank_account.is_a?(CardBankAccount)
Stripe::Token.create({ customer: bank_account.credit_card.stripe_customer_id }, { stripe_account: stripe_account["id"] }).id
else
bank_account_hash = {
country: bank_account.country,
currency: bank_account.currency,
account_number: bank_account.account_number.decrypt(passphrase).gsub(/[ -]/, "")
}
bank_account_hash[:routing_number] = bank_account.routing_number if bank_account.routing_number.present?
bank_account_hash[:account_type] = bank_account.account_type if [Compliance::Countries::CHL.alpha2, Compliance::Countries::COL.alpha2].include?(country_code) && bank_account.account_type.present?
bank_account_hash[:account_holder_name] = bank_account.account_holder_full_name if [Compliance::Countries::JPN.alpha2, Compliance::Countries::VNM.alpha2, Compliance::Countries::IDN.alpha2].include?(country_code)
bank_account_hash
end
settings = {
payouts: {
schedule: {
interval: "manual"
},
debit_negative_balances: !cross_border_payouts_only
}
}
metadata = stripe_account["metadata"].to_h || {}
metadata[:bank_account_id] = bank_account.external_id
attributes = {
metadata:,
# TODO replace `bank_account` with `external_account` (https://stripe.com/docs/upgrades#2015-10-01)
# The `bank_account` is a deprecated field that continues to be supported, but the docs say it should
# be renamed to `external_account`. Renaming the field causes a problem when calling `update_bank_account`
# ("Cannot save property `external_account` containing an API resource. It doesn't appear to be persisted and is not marked as `save_with_parent`.")
# Everything works well during account creation. Seems to be an issue with stripe ruby gem.
bank_account: bank_account_field,
settings:
}
attributes.deep_values_strip!
end
private_class_method
def self.person_hash(user_compliance_info, passphrase)
if user_compliance_info
personal_tax_id = user_compliance_info.individual_tax_id.decrypt(passphrase)
hash = {
first_name: user_compliance_info.first_name,
last_name: user_compliance_info.last_name,
email: user_compliance_info.user.email,
phone: user_compliance_info.phone,
dob: {
day: user_compliance_info.birthday.try(:day),
month: user_compliance_info.birthday.try(:month),
year: user_compliance_info.birthday.try(:year)
}
}
if user_compliance_info.legal_entity_country_code == Compliance::Countries::CAN.alpha2
hash.deep_merge!(relationship: { title: user_compliance_info.job_title.presence || DEFAULT_RELATIONSHIP_TITLE })
end
if user_compliance_info.country_code == Compliance::Countries::JPN.alpha2
hash.deep_merge!({
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,
address_kanji: {
line1: user_compliance_info.building_number,
line2: user_compliance_info.street_address_kanji,
postal_code: user_compliance_info.zip_code
},
address_kana: {
line1: user_compliance_info.building_number,
line2: user_compliance_info.street_address_kana,
postal_code: user_compliance_info.zip_code
}
})
else
hash.deep_merge!({
address: {
line1: user_compliance_info.street_address,
line2: nil,
city: user_compliance_info.city,
state: user_compliance_info.state,
postal_code: user_compliance_info.zip_code,
country: user_compliance_info.country_code
},
})
end
# For US accounts, only submit the Personal Tax ID if it's longer than four digits, otherwise the field contains the SSN Last 4.
# For non-US accounts, always submit the Personal Tax ID.
if personal_tax_id && (user_compliance_info.country_code != Compliance::Countries::USA.alpha2 || personal_tax_id.length > 4)
hash.deep_merge!(id_number: personal_tax_id)
end
# For US accounts, only submit the SSN Last 4 if we have enough digits in the Tax ID to get the last 4.
# For non-US accounts, never submit this field, it is for US accounts only.
if user_compliance_info.country_code == Compliance::Countries::USA.alpha2 && personal_tax_id && personal_tax_id.length == 4
hash.deep_merge!(ssn_last_4: personal_tax_id.last(4))
end
if [Compliance::Countries::ARE.alpha2,
Compliance::Countries::SGP.alpha2,
Compliance::Countries::BGD.alpha2,
Compliance::Countries::PAK.alpha2].include?(user_compliance_info.country_code)
hash.deep_merge!(nationality: user_compliance_info.nationality)
end
hash.deep_values_strip!
end
end
def self.company_hash(user_compliance_info, passphrase)
return unless user_compliance_info.present?
business_tax_id = user_compliance_info.business_tax_id.decrypt(passphrase)
hash = {
company: {
name: user_compliance_info.business_name.presence,
address: {
line1: user_compliance_info.legal_entity_street_address,
line2: nil,
city: user_compliance_info.legal_entity_city,
state: user_compliance_info.legal_entity_state,
postal_code: user_compliance_info.legal_entity_zip_code,
country: user_compliance_info.legal_entity_country_code
},
tax_id: business_tax_id.presence,
phone: user_compliance_info.business_phone,
directors_provided: true,
executives_provided: true,
}
}
if user_compliance_info.country_code == Compliance::Countries::JPN.alpha2
hash.deep_merge!({
company: {
name_kanji: user_compliance_info.business_name_kanji,
name_kana: user_compliance_info.business_name_kana,
address_kanji: {
line1: user_compliance_info.business_building_number,
line2: user_compliance_info.business_street_address_kanji,
postal_code: user_compliance_info.legal_entity_zip_code
},
address_kana: {
line1: user_compliance_info.business_building_number,
line2: user_compliance_info.business_street_address_kana,
postal_code: user_compliance_info.legal_entity_zip_code
}
}
})
end
if user_compliance_info.country_code == Compliance::Countries::ARE.alpha2
hash.deep_merge!(
company: {
structure: user_compliance_info.business_type,
vat_id: user_compliance_info.business_vat_id_number
}
)
elsif user_compliance_info.legal_entity_country_code == Compliance::Countries::CAN.alpha2
hash.deep_merge!(
company: {
structure: user_compliance_info.business_type == "non_profit" ? "" : user_compliance_info.business_type,
}
)
elsif user_compliance_info.country_code == Compliance::Countries::USA.alpha2 && user_compliance_info.business_type == UserComplianceInfo::BusinessTypes::SOLE_PROPRIETORSHIP
hash[:company][:structure] = user_compliance_info.business_type
end
hash
end
def self.handle_stripe_event(stripe_event)
case stripe_event["type"]
when "account.updated"
handle_stripe_event_account_updated(stripe_event)
when "account.application.deauthorized"
handle_stripe_event_account_deauthorized(stripe_event)
when "capability.updated"
handle_stripe_event_capability_updated(stripe_event)
end
end
def self.handle_stripe_event_account_deauthorized(stripe_event)
stripe_event_id = stripe_event["id"]
stripe_account = stripe_event["data"] && stripe_event["data"]["object"]
raise "Stripe Event #{stripe_event_id} does not contain an 'account' object." if stripe_event["type"] != "account.application.deauthorized" && (stripe_account && stripe_account["object"]) != "account"
stripe_account_id = if stripe_event["type"] == "account.application.deauthorized"
stripe_event["user_id"].present? ? stripe_event["user_id"] : stripe_event["account"]
else
stripe_account["id"]
end
merchant_account = MerchantAccount.where(charge_processor_id: StripeChargeProcessor.charge_processor_id,
charge_processor_merchant_id: stripe_account_id).alive.last
return if merchant_account.nil?
merchant_account.delete_charge_processor_account!
user = merchant_account.user
if user.merchant_migration_enabled?
MerchantRegistrationMailer.account_deauthorized_to_user(
user.id,
StripeChargeProcessor.charge_processor_id
).deliver_later(queue: "critical")
end
end
def self.handle_stripe_event_capability_updated(stripe_event)
stripe_event_id = stripe_event["id"]
stripe_capability = stripe_event["data"]["object"]
stripe_previous_attributes = stripe_event["data"]["previous_attributes"] || {}
raise "Stripe Event #{stripe_event_id} does not contain a 'capability' object." if stripe_capability["object"] != "capability"
stripe_account_id = stripe_capability["account"]
merchant_account = MerchantAccount.where(charge_processor_id: StripeChargeProcessor.charge_processor_id,
charge_processor_merchant_id: stripe_account_id)
.alive.charge_processor_alive.last
return unless merchant_account&.country == Compliance::Countries::JPN.alpha2
stripe_account = Stripe::Account.retrieve(stripe_account_id)
handle_stripe_info_requirements(stripe_event_id, stripe_account, stripe_previous_attributes)
end
def self.handle_stripe_event_account_updated(stripe_event)
stripe_event_id = stripe_event["id"]
stripe_account = stripe_event["data"]["object"]
stripe_previous_attributes = stripe_event["data"]["previous_attributes"] || {}
raise "Stripe Event #{stripe_event_id} does not contain an 'account' object." if stripe_account["object"] != "account"
handle_stripe_info_requirements(stripe_event_id, stripe_account, stripe_previous_attributes)
end
def self.handle_stripe_info_requirements(stripe_event_id, stripe_account, stripe_previous_attributes)
return if stripe_account["type"] == "standard"
stripe_account_id = stripe_account["id"]
merchant_account = MerchantAccount.where(charge_processor_id: StripeChargeProcessor.charge_processor_id,
charge_processor_merchant_id: stripe_account_id).last
raise "No Merchant Account for Stripe Account ID #{stripe_account_id}" if merchant_account.nil?
return unless merchant_account.alive?
unless merchant_account.charge_processor_alive?
Rails.logger.info "Merchant account #{merchant_account.id} not marked as alive in Stripe, ignoring event #{stripe_event_id}"
return
end
user = merchant_account.user
return unless user.account_active?
requirements = stripe_account["requirements"] || {}
future_requirements = stripe_account["future_requirements"] || {}
if stripe_account["default_currency"] && stripe_account["country"]
merchant_account.currency = stripe_account["default_currency"]
merchant_account.country = stripe_account["country"]
merchant_account.save!
end
individual = if stripe_account["business_type"] == "individual"
stripe_account["individual"] || {}
else
Stripe::Account.list_persons(stripe_account_id, { limit: 1 }).first || {}
end
individual_verification_status = individual["verification"].try(:[], "status")
merchant_account.mark_charge_processor_verified! if individual_verification_status == "verified"
merchant_account.mark_charge_processor_unverified! if individual_verification_status == "unverified"
deadline = if requirements["current_deadline"].present? && future_requirements["current_deadline"].present?
[requirements["current_deadline"], future_requirements["current_deadline"]].min
else
requirements["current_deadline"].presence || future_requirements["current_deadline"]
end
requirements_due_at = Time.zone.at(deadline) if deadline.present?
alternative_requirements = requirements["alternatives"]&.map { _1["alternative_fields_due"] } || []
alternative_future_requirements = future_requirements["alternatives"]&.map { _1["alternative_fields_due"] } || []
alternative_fields_due = (alternative_requirements + alternative_future_requirements).compact.reduce([], :+).uniq
# future_requirements["eventually_due"] contains fields that will be needed sometime in the future,
# we don't need to collect those currently. E.g. Full 9-digit SSN is required for a US account once it
# $500k in payments, but Stripe shows that field under future_requirements["eventually_due"] for all US accounts.
stripe_fields_needed = [requirements["currently_due"], requirements["eventually_due"], requirements["past_due"],
future_requirements["currently_due"], future_requirements["past_due"], alternative_fields_due].compact.reduce([], :+).uniq
stripe_fields_needed.map! do |stripe_field_needed|
# Example identity-related missing field for individual account: `individual.dob.day`
# Example identity-related missing field for business account: `person_IRWHQ2ZRlwIh1j.dob.day`
# Here we convert the `person_IRWHQ2ZRlwIh1j.dob.day` => `individual.dob.day` before using it as a lookup key
stripe_field_needed.gsub(/^person_\w+\./, "individual.")
end
fields_needed = []
verification_errors = {}
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/merchant_registration/implementations/paypal/paypal_merchant_account_manager.rb | app/business/payments/merchant_registration/implementations/paypal/paypal_merchant_account_manager.rb | # frozen_string_literal: true
class PaypalMerchantAccountManager
attr_reader :response
# Ref: https://developer.paypal.com/docs/api/reference/country-codes/#paypal-commerce-platform-availability
COUNTRY_CODES_NOT_SUPPORTED_BY_PCP = [
Compliance::Countries::DZA,
Compliance::Countries::BRA,
Compliance::Countries::EGY,
Compliance::Countries::IND,
Compliance::Countries::ISR,
Compliance::Countries::JPN,
Compliance::Countries::FSM,
Compliance::Countries::MAR,
Compliance::Countries::TUR,
].map(&:alpha2).freeze
MIN_SALES_CENTS_REQ_FOR_PCP = 100_00 # $100
def create_partner_referral(user, return_url)
payment_integration_api = PaypalIntegrationRestApi.new(user, authorization_header:)
@response = payment_integration_api.create_partner_referral(return_url)
if post_partner_referral_success?
partner_referral_success_response_data
else
notify_bugsnag_partner_referral_error
partner_referral_failure_response_data
end
end
def handle_paypal_event(paypal_event)
case paypal_event["event_type"]
when PaypalEventType::MERCHANT_ONBOARDING_SELLER_GRANTED_CONSENT, PaypalEventType::MERCHANT_ONBOARDING_COMPLETED,
PaypalEventType::MERCHANT_EMAIL_CONFIRMED, PaypalEventType::MERCHANT_CAPABILITY_UPDATED,
PaypalEventType::MERCHANT_SUBSCRIPTION_UPDATED
handle_merchant_account_updated_event(paypal_event)
when PaypalEventType::MERCHANT_PARTNER_CONSENT_REVOKED, PaypalEventType::MERCHANT_IDENTITY_AUTH_CONSENT_REVOKED
handle_merchant_consent_revoked_event(paypal_event)
end
end
def update_merchant_account(user:, paypal_merchant_id:, meta: nil,
send_email_confirmation_notification: true,
create_new: true)
return "There was an error connecting your PayPal account with Gumroad." if user.blank? || paypal_merchant_id.blank?
return "Your PayPal account could not be connected because you do not meet the eligibility requirements." unless user.paypal_connect_allowed?
paypal_merchant_accounts = user.merchant_accounts
.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id)
.where(charge_processor_merchant_id: paypal_merchant_id)
if create_new
merchant_account = paypal_merchant_accounts.first_or_initialize
else
merchant_account = paypal_merchant_accounts.alive.first
end
return unless merchant_account.present?
merchant_account.deleted_at = nil
merchant_account.charge_processor_deleted_at = nil
merchant_account.charge_processor_merchant_id = paypal_merchant_id
merchant_account.meta = meta if meta.present?
merchant_account_changed = merchant_account.changed?
return "There was an error connecting your PayPal account with Gumroad." unless merchant_account.save
if merchant_account.charge_processor_verified?
MerchantRegistrationMailer.paypal_account_updated(user.id).deliver_later(queue: "default") if merchant_account_changed
return "You have successfully connected your PayPal account with Gumroad."
end
parsed_response = merchant_account.paypal_account_details
if parsed_response.present?
paypal_account_country_code = parsed_response["country"]
if PaypalMerchantAccountManager::COUNTRY_CODES_NOT_SUPPORTED_BY_PCP.include?(paypal_account_country_code)
merchant_account.delete_charge_processor_account!
return "Your PayPal account could not be connected because this PayPal integration is not supported in your country."
end
if paypal_account_country_code && parsed_response["primary_currency"]
merchant_account.country = paypal_account_country_code
merchant_account.currency = parsed_response["primary_currency"].downcase
return "There was an error connecting your PayPal account with Gumroad." unless merchant_account.save
end
oauth_integration = parsed_response["oauth_integrations"][0]
if parsed_response["primary_email_confirmed"] && parsed_response["payments_receivable"] &&
oauth_integration["integration_type"] == "OAUTH_THIRD_PARTY" &&
oauth_integration["integration_method"] == "PAYPAL"
oauth_integration["oauth_third_party"][0]["partner_client_id"] == PAYPAL_PARTNER_CLIENT_ID
merchant_account.charge_processor_alive_at = Time.current
merchant_account.mark_charge_processor_verified!
MerchantRegistrationMailer.paypal_account_updated(user.id).deliver_later(queue: "default")
user.merchant_accounts
.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id)
.where.not(id: merchant_account.id).each do |ma|
ma.delete_charge_processor_account!
end
"You have successfully connected your PayPal account with Gumroad."
elsif parsed_response["primary_email_confirmed"]
merchant_account.charge_processor_alive_at = nil
merchant_account.charge_processor_verified_at = nil
merchant_account.save!
"Your PayPal account connect with Gumroad is incomplete because of missing permissions. Please try connecting again and grant the requested permissions."
else
merchant_account.charge_processor_alive_at = nil
merchant_account.charge_processor_verified_at = nil
merchant_account.save!
MerchantRegistrationMailer.confirm_email_on_paypal(user.id, parsed_response["primary_email"]).deliver_later(queue: "default") if send_email_confirmation_notification
"You need to confirm the email address (#{parsed_response["primary_email"]}) attached to your PayPal account before you can start using it with Gumroad."
end
end
end
def disconnect(user:)
merchant_account = user.merchant_accounts.alive.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id).last
return false if merchant_account.blank?
merchant_account.delete_charge_processor_account!
end
private
def authorization_header
PaypalPartnerRestCredentials.new.auth_token
end
def post_partner_referral_success?
response.success? && post_partner_referral_redirection_url.present?
end
def post_partner_referral_redirection_url
@post_partner_referral_redirection_url ||= response["links"].detect do |link_info|
link_info.try(:[], "rel") == "action_url"
end.try(:[], "href")
end
def partner_referral_success_response_data
{
redirect_url: post_partner_referral_redirection_url,
success: true
}
end
def partner_referral_failure_response_data
{
success: false,
error_message: partner_referral_error_message
}
end
def response_error_name
response.parsed_response.try(:[], "name")
end
# Error list:
# INTERNAL_SERVICE_ERROR
# DUPLICATE_REQUEST_ID
# VALIDATION_ERROR
# INVALID_RESOURCE_ID
# PERMISSION_DENIED
# DATA_RETRIEVAL
# CONNECTION_ERROR
def partner_referral_error_message
case response_error_name
when "VALIDATION_ERROR"
"Invalid request. Please try again later."
when "PERMISSION_DENIED"
"Permission Denied. Please try again later."
when "CONNECTION_ERROR"
"Timed out. Please try again later."
else
"Please try again later."
end
end
def notify_bugsnag_partner_referral_error
return if %w[INTERNAL_SERVICE_ERROR PERMISSION_DENIED CONNECTION_ERROR].include?(response_error_name)
notify_bugsnag
end
def notify_bugsnag
Bugsnag.notify(request: response.request,
response:)
end
def handle_merchant_account_updated_event(paypal_event)
paypal_tracking_id = paypal_event["resource"]["tracking_id"]
return if paypal_tracking_id.blank?
update_merchant_account(user: User.find_by_external_id(paypal_tracking_id.split("-")[0]),
paypal_merchant_id: paypal_event["resource"]["merchant_id"],
create_new: false)
end
def handle_merchant_consent_revoked_event(paypal_event)
# IDENTITY.AUTHORIZATION-CONSENT.REVOKED webhook contains payer_id instead of merchant_id
merchant_id = paypal_event["resource"]["merchant_id"] || paypal_event["resource"]["payer_id"]
merchant_accounts = MerchantAccount.alive.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id,
charge_processor_merchant_id: merchant_id)
return if merchant_accounts.blank?
merchant_accounts.each do |merchant_account|
merchant_account.delete_charge_processor_account!
user = merchant_account.user
MerchantRegistrationMailer.account_deauthorized_to_user(
user.id,
PaypalChargeProcessor.charge_processor_id
).deliver_later(queue: "critical")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/charge_refund.rb | app/business/payments/charging/charge_refund.rb | # frozen_string_literal: true
class ChargeRefund
attr_accessor :charge_processor_id, :id, :charge_id, :flow_of_funds
attr_reader :refund
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/chargeable_funding_type.rb | app/business/payments/charging/chargeable_funding_type.rb | # frozen_string_literal: true
class ChargeableFundingType
CREDIT = "credit"
DEBIT = "debit"
PREPAID = "prepaid"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/setup_intent.rb | app/business/payments/charging/setup_intent.rb | # frozen_string_literal: true
class SetupIntent
attr_accessor :id, :setup_intent, :client_secret
def succeeded?
true
end
def requires_action?
false
end
def canceled?
false
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/in_app_purchase_details.rb | app/business/payments/charging/in_app_purchase_details.rb | # frozen_string_literal: true
InAppPurchaseDetails = Data.define(:product_id, :price_cents, :price_currency_type, :fee_per_thousand)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/charge_processor.rb | app/business/payments/charging/charge_processor.rb | # frozen_string_literal: true
module ChargeProcessor
# Time user has to complete Strong Customer Authentication (enter an OTP, confirm purchase via bank app, etc). Sensible default, not dictated by a payment processor.
TIME_TO_COMPLETE_SCA = 15.minutes
NOTIFICATION_CHARGE_EVENT = "charge_event.charge_processor.gumroad"
DEFAULT_CURRENCY_CODE = Currency::USD.upcase
DISPLAY_NAME_MAP = {
StripeChargeProcessor.charge_processor_id => StripeChargeProcessor::DISPLAY_NAME,
BraintreeChargeProcessor.charge_processor_id => BraintreeChargeProcessor::DISPLAY_NAME,
PaypalChargeProcessor.charge_processor_id => PaypalChargeProcessor::DISPLAY_NAME,
}.freeze
CHARGE_PROCESSOR_CLASS_MAP = {
StripeChargeProcessor.charge_processor_id => StripeChargeProcessor,
BraintreeChargeProcessor.charge_processor_id => BraintreeChargeProcessor,
PaypalChargeProcessor.charge_processor_id => PaypalChargeProcessor,
}.freeze
private_constant :CHARGE_PROCESSOR_CLASS_MAP
# Public: Builds a chargeable using the parameters given.
# Parameters are specific to the charge processor referenced by the charge processor id.
def self.get_chargeable_for_params(params, gumroad_guid)
chargeables = charge_processors.map { |charge_processor| charge_processor.get_chargeable_for_params(params, gumroad_guid) }.compact
return Chargeable.new(chargeables) if chargeables.present?
nil
end
# Public: Builds a chargeable using the data given.
def self.get_chargeable_for_data(reusable_tokens,
payment_method_id,
fingerprint,
stripe_setup_intent_id,
stripe_payment_intent_id,
last4,
number_length,
visual,
expiry_month,
expiry_year,
card_type,
country,
zip_code = nil,
merchant_account: nil)
chargeables = []
charge_processor_ids.each do |charge_processor_id|
reusable_token = reusable_tokens[charge_processor_id]
next unless reusable_token
chargeables << get_charge_processor(charge_processor_id).get_chargeable_for_data(reusable_token,
payment_method_id,
fingerprint,
stripe_setup_intent_id,
stripe_payment_intent_id,
last4,
number_length,
visual,
expiry_month,
expiry_year,
card_type,
country,
zip_code,
merchant_account:)
end
return Chargeable.new(chargeables) if chargeables.present?
nil
end
# Public: Gets a Charge object for a charge.
# Raises error if the charge id is not known by the charge processor.
# Returns a Charge object.
def self.get_charge(charge_processor_id, charge_id, merchant_account: nil)
get_charge_processor(charge_processor_id).get_charge(charge_id,
merchant_account:)
end
# Public: Searches for the charge on charge processor.
# Returns the charge processor response object if found (Braintree::Transaction or Stripe::Charge),
# and returns nil if no charge is found.
def self.search_charge(charge_processor_id:, purchase:)
get_charge_processor(charge_processor_id).search_charge(purchase:)
end
# Public: Gets a ChargeIntent object given its charge processor ID.
# Raises an error if the payment intent ID is not known by the charge processor.
# Returns a ChargeIntent object.
def self.get_charge_intent(merchant_account, payment_intent_id)
return if payment_intent_id.blank?
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
get_charge_processor(merchant_account.charge_processor_id).get_charge_intent(payment_intent_id, merchant_account:)
end
# Public: Gets a SetupIntent object given its charge processor ID.
# Raises error if the setup intent id is not known by the charge processor.
# Returns a SetupIntent object.
def self.get_setup_intent(merchant_account, setup_intent_id)
return if setup_intent_id.blank?
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
get_charge_processor(merchant_account.charge_processor_id).get_setup_intent(setup_intent_id, merchant_account:)
end
# Public: Creates an intent to charge chargeable in the future.
#
# Depending on the implementation this setup intent may require on-session user confirmation.
#
# Raises error if the setup is declined or there is a technical failure.
#
# Returns a SetupIntent object.
def self.setup_future_charges!(merchant_account, chargeable, mandate_options: nil)
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
charge_processor = get_charge_processor(merchant_account.charge_processor_id)
chargeable_for_charge_processor = chargeable.get_chargeable_for(merchant_account.charge_processor_id)
charge_processor.setup_future_charges!(merchant_account, chargeable_for_charge_processor, mandate_options:)
end
# Public: Charges a Chargeable object with funds destined to the merchant account.
#
# Depending on the implementation the Gumroad portion of the charge may be automatically funded to
# Gumroad's merchant account if the merchant account provided is not Gumroad's. The amount that gets
# funded to Gumroad is defined by `amount_for_gumroad_cents`. It's important this is correctly set to
# money destined for Gumroad because it will be immutable after the charge is created.
#
# Raises error if the charge is declined or there is a technical failure.
#
# Returns a ChargeIntent object.
def self.create_payment_intent_or_charge!(merchant_account, chargeable, amount_cents, amount_for_gumroad_cents,
reference, description,
metadata: nil, statement_description: nil, transfer_group: nil,
off_session: true, setup_future_charges: false, mandate_options: nil)
charge_processor = get_charge_processor(merchant_account.charge_processor_id)
chargeable_for_charge_processor = chargeable.get_chargeable_for(merchant_account.charge_processor_id)
charge_processor.create_payment_intent_or_charge!(merchant_account,
chargeable_for_charge_processor,
amount_cents,
amount_for_gumroad_cents,
reference,
description,
metadata:,
statement_description:,
transfer_group:,
off_session:,
setup_future_charges:,
mandate_options:)
end
def self.confirm_payment_intent!(merchant_account, charge_intent_id)
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
charge_processor = get_charge_processor(merchant_account.charge_processor_id)
charge_processor.confirm_payment_intent!(merchant_account, charge_intent_id)
end
def self.cancel_payment_intent!(merchant_account, charge_intent_id)
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
charge_processor = get_charge_processor(merchant_account.charge_processor_id)
charge_processor.cancel_payment_intent!(merchant_account, charge_intent_id)
end
def self.cancel_setup_intent!(merchant_account, setup_intent_id)
return unless StripeChargeProcessor.charge_processor_id == merchant_account.charge_processor_id
charge_processor = get_charge_processor(merchant_account.charge_processor_id)
charge_processor.cancel_setup_intent!(merchant_account, setup_intent_id)
end
# Public: Refunds a charge. Supports both full and partial refund.
# If amount_cents is not provided a full refund is performed.
# If refund fails an error is raised.
def self.refund!(charge_processor_id, charge_id, amount_cents: nil, merchant_account: nil,
paypal_order_purchase_unit_refund: nil,
reverse_transfer: true,
is_for_fraud: nil)
get_charge_processor(charge_processor_id).refund!(charge_id,
amount_cents:,
merchant_account:,
paypal_order_purchase_unit_refund:,
reverse_transfer:,
is_for_fraud:)
end
# Public: Handles a charge event.
# Called by Charge Processor implementations when the charge processor makes calls to their webhook.
# Not for application use.
def self.handle_event(event)
ActiveSupport::Notifications.instrument(NOTIFICATION_CHARGE_EVENT, charge_event: event)
end
# Public: Fights a chargeback by supplying evidence.
def self.fight_chargeback(charge_processor_id, charge_id, dispute_evidence)
get_charge_processor(charge_processor_id).fight_chargeback(charge_id, dispute_evidence)
end
# Public: Returns where the funds are held for this merchant account.
# Returns a constant defined in HolderOfFunds.
def self.holder_of_funds(merchant_account)
charge_processor_id = merchant_account.charge_processor_id
get_charge_processor(charge_processor_id).holder_of_funds(merchant_account)
end
def self.transaction_url(charge_processor_id, charge_id)
get_charge_processor(charge_processor_id).transaction_url(charge_id)
end
def self.transaction_url_for_seller(charge_processor_id, charge_id, charged_using_gumroad_account)
return if charge_processor_id.blank? || charge_id.blank? || charged_using_gumroad_account
transaction_url(charge_processor_id, charge_id)
end
def self.transaction_url_for_admin(charge_processor_id, charge_id, charged_using_gumroad_account)
return if charge_processor_id.blank? || charge_id.blank? || !charged_using_gumroad_account
transaction_url(charge_processor_id, charge_id)
end
def self.charge_processor_success_statuses(charge_processor_id)
charge_processor_class = CHARGE_PROCESSOR_CLASS_MAP[charge_processor_id]
return charge_processor_class::VALID_TRANSACTION_STATUSES if charge_processor_class
[]
end
def self.get_or_search_charge(purchase)
return nil unless purchase.charge_processor_id.present?
if purchase.stripe_transaction_id
charge = get_charge(purchase.charge_processor_id,
purchase.stripe_transaction_id,
merchant_account: purchase.merchant_account)
else
charge = search_charge(charge_processor_id: purchase.charge_processor_id, purchase:)
if charge &&
ChargeProcessor.charge_processor_success_statuses(purchase.charge_processor_id).include?(charge.status) &&
!charge.is_a?(BaseProcessorCharge) # PaypalChargeProcessor.search_charge already returns a `PaypalCharge` type object
charge = get_charge_processor(purchase.charge_processor_id).get_charge_object(charge)
end
end
charge
end
def self.charge_processor_ids
CHARGE_PROCESSOR_CLASS_MAP.keys
end
private_class_method
def self.charge_processors
CHARGE_PROCESSOR_CLASS_MAP.map { |_charge_processor_id, charge_processor_class| charge_processor_class.new }
end
def self.get_charge_processor(charge_processor_id)
charge_processor_class = CHARGE_PROCESSOR_CLASS_MAP[charge_processor_id]
return charge_processor_class.new if charge_processor_class
nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/chargeable_visual.rb | app/business/payments/charging/chargeable_visual.rb | # frozen_string_literal: true
module ChargeableVisual
module_function
DEFAULT_FORMAT = "**** **** **** %s"
LENGTH_TO_FORMAT = Hash.new(DEFAULT_FORMAT).merge(
16 => DEFAULT_FORMAT,
15 => "**** ****** *%s",
14 => "**** ****** %s"
)
def is_cc_visual(visual)
!(visual =~ /^[*\s\d]+$/).nil?
end
def build_visual(cc_number_last4, cc_number_length)
cc_number_last4 = get_card_last4(cc_number_last4)
format(LENGTH_TO_FORMAT[cc_number_length], cc_number_last4)
end
def get_card_last4(cc_number)
cc_number.gsub(/[^\d]/, "").rjust(4, "*").slice(-4..-1)
end
def get_card_length_from_card_type(card_type)
card_type_length_map = CreditCardUtility::CARD_TYPE_DEFAULT_LENGTHS
length = card_type_length_map[card_type]
length = card_type_length_map[CardType::UNKNOWN] if length.nil?
length
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/holder_of_funds.rb | app/business/payments/charging/holder_of_funds.rb | # frozen_string_literal: true
# Describe where funds collected by creating a charge at a charge processor
# are held until they are paid out to the creator.
module HolderOfFunds
GUMROAD = "gumroad"
STRIPE = "stripe"
CREATOR = "creator"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/charge_event.rb | app/business/payments/charging/charge_event.rb | # frozen_string_literal: true
class ChargeEvent
# An informational event that requires no action from a financial point of view.
TYPE_INFORMATIONAL = :info
# A dispute has been formalized and has financial consequences, funds have been withdrawn to cover the dispute.
TYPE_DISPUTE_FORMALIZED = :dispute_formalized
# A dispute has been closed as `won` and has financial consequences, funds have been returned.
TYPE_DISPUTE_WON = :dispute_won
# A dispute has been closed as `lost`, funds already withdrawn will not be returned.
TYPE_DISPUTE_LOST = :dispute_lost
## MerchantMigration - Remove in phase 2
# A charge failed to settle, can be caused by a charge processor bug or when a bank instant transfers goes awry
TYPE_SETTLEMENT_DECLINED = :settlement_declined
# A Charge has succeeded. We need to mark the corresponding purchase as successful if it's still in progress.
TYPE_CHARGE_SUCCEEDED = :charge_succeeded
# A PaymentIntent has failed. We need to mark the corresponding purchase as failed if it's still in progress.
TYPE_PAYMENT_INTENT_FAILED = :payment_intent_failed
# A charge has been refunded or refund has been further updated
TYPE_CHARGE_REFUND_UPDATED = :charge_refund_updated
attr_accessor :charge_processor_id, :charge_event_id, :charge_id, :charge_reference, :created_at, :type, :comment,
:flow_of_funds, :extras, :processor_payment_intent_id, :refund_id
def to_h
{
charge_processor_id:,
charge_event_id:,
charge_id:,
charge_reference:,
created_at:,
type:,
comment:,
flow_of_funds: flow_of_funds.to_h,
extras:
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/chargeable.rb | app/business/payments/charging/chargeable.rb | # frozen_string_literal: true
# Public: A chargeable contains multiple internal chargeables that are mapped to charge processor implementations.
# Externally to the charging module the application interacts with the Chargeable only but internally to the individual
# chargeables associated with each charge processor are used to retrieve information about the chargeable and perform
# charges, refunds, etc.
class Chargeable
def initialize(chargeables)
@chargeables = {}
chargeables.each do |chargeable|
@chargeables[chargeable.charge_processor_id] = chargeable
end
end
def charge_processor_ids
@chargeables.keys
end
def charge_processor_id
charge_processor_ids.join(",")
end
def prepare!
@chargeables.values.first.prepare!
end
def fingerprint
@chargeables.values.first.fingerprint
end
def funding_type
@chargeables.values.first.funding_type
end
def last4
@chargeables.values.first.last4
end
def number_length
@chargeables.values.first.number_length
end
def visual
@chargeables.values.first.visual
end
def expiry_month
@chargeables.values.first.expiry_month
end
def expiry_year
@chargeables.values.first.expiry_year
end
def zip_code
@chargeables.values.first.zip_code
end
def card_type
@chargeables.values.first.card_type
end
def country
@chargeables.values.first.country
end
def payment_method_id
@chargeables.values.first.payment_method_id
end
def stripe_setup_intent_id
chargeable = @chargeables.values.first
chargeable.respond_to?(:stripe_setup_intent_id) ? chargeable.stripe_setup_intent_id : nil
end
def stripe_payment_intent_id
chargeable = @chargeables.values.first
chargeable.respond_to?(:stripe_payment_intent_id) ? chargeable.stripe_payment_intent_id : nil
end
def reusable_token_for!(charge_processor_id, user)
chargeable = get_chargeable_for(charge_processor_id)
return chargeable.reusable_token!(user) if chargeable
nil
end
def get_chargeable_for(charge_processor_id)
@chargeables[charge_processor_id]
end
def can_be_saved?
!get_chargeable_for(PaypalChargeProcessor.charge_processor_id).is_a?(PaypalApprovedOrderChargeable)
end
# Recurring payments in India via Stripe require e-mandates.
# https://stripe.com/docs/india-recurring-payments?integration=paymentIntents-setupIntents
def requires_mandate?
@chargeables.values.first.respond_to?(:requires_mandate?) && @chargeables.values.first.requires_mandate?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/base_processor_charge.rb | app/business/payments/charging/base_processor_charge.rb | # frozen_string_literal: true
class BaseProcessorCharge
attr_accessor :charge_processor_id, :id, :status, :refunded, :disputed, :fee, :fee_currency,
:card_fingerprint, :card_instance_id,
:card_last4, :card_number_length, :card_expiry_month, :card_expiry_year, :card_zip_code,
:card_type, :card_country, :zip_check_result,
:flow_of_funds, :risk_level
# Public: Access attributes of BaseProcessorCharge via charge[:attribute].
# Historically the code base used the Stripe::Charge object which
# supports accessing attributes via []. It required less changes to
# support the same access with the new class.
def [](attribute)
send(attribute)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/flow_of_funds.rb | app/business/payments/charging/flow_of_funds.rb | # frozen_string_literal: true
class FlowOfFunds
class Amount
attr_accessor :currency, :cents
def initialize(currency:, cents:)
@currency = currency
@cents = cents
end
def to_h
{
currenty: currency,
cents:
}
end
end
attr_accessor :issued_amount, :settled_amount, :gumroad_amount, :merchant_account_gross_amount, :merchant_account_net_amount
# Public: Initialize a new FlowOfFunds with an amount describing the funds at each point in
# the flow of funds.
# - issued_amount - a FlowOfFunds::Amount object describing the amount at the issuer either being charged, refunded, etc
# - settled_amount - a FlowOfFunds::Amount object describing the amount at the time of settlement
# - gumroad_amount - a FlowOfFunds::Amount object describing the amount at the time of Gumroad collecting the portion it holds
# - merchant_account_gross_amount - a FlowOfFunds::Amount object describing the amount at the time of a merchant account collected in whole
# - merchant_account_net_amount - a FlowOfFunds::Amount object describing the amount at the time of a merchant account collected minus the gumroad_amount
def initialize(issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount: nil, merchant_account_net_amount: nil)
@issued_amount = issued_amount
@settled_amount = settled_amount
@gumroad_amount = gumroad_amount
@merchant_account_gross_amount = merchant_account_gross_amount
@merchant_account_net_amount = merchant_account_net_amount
end
# Public: Builds a simple FlowOfFunds where the issued, settled and gumroad amounts are the currency
# and amount_cents given.
# - currency - The currency of the amount
# - amount_cents - The cents of the amounts
# Returns a FlowOfFunds.
def self.build_simple_flow_of_funds(currency, amount_cents)
amount = Amount.new(currency:, cents: amount_cents)
FlowOfFunds.new(
issued_amount: amount,
settled_amount: amount,
gumroad_amount: amount
)
end
def to_h
{
issued_amount: issued_amount.to_h,
settled_amount: settled_amount.to_h,
gumroad_amount: gumroad_amount.to_h,
merchant_account_gross_amount: merchant_account_gross_amount.to_h,
merchant_account_net_amount: merchant_account_net_amount.to_h
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/charge_intent.rb | app/business/payments/charging/charge_intent.rb | # frozen_string_literal: true
# Represents the user's intent to pay. The intent may succeed immediately (resulting in a charge)
# or require additional confirmation from the user (such as 3D Secure).
#
# This is mainly a wrapper around Stripe's PaymentIntent API: https://stripe.com/docs/payments/payment-intents
#
# For other charge-based APIs (PayPal, Braintree) that don't have this notion of "intent" - and result in an
# immediate charge - we wrap the `charge` object in a `ChargeIntent` and set `succeeded` to `true` immediately.
class ChargeIntent
attr_accessor :id, :payment_intent, :charge, :client_secret
def requires_action?
false
end
def succeeded?
true
end
def canceled?
false
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_unsupported_payment_type_error.rb | app/business/payments/charging/errors/charge_processor_unsupported_payment_type_error.rb | # frozen_string_literal: true
class ChargeProcessorUnsupportedPaymentTypeError < ChargeProcessorCardError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_unsupported_payment_account_error.rb | app/business/payments/charging/errors/charge_processor_unsupported_payment_account_error.rb | # frozen_string_literal: true
class ChargeProcessorUnsupportedPaymentAccountError < ChargeProcessorCardError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_insufficient_funds_error.rb | app/business/payments/charging/errors/charge_processor_insufficient_funds_error.rb | # frozen_string_literal: true
class ChargeProcessorInsufficientFundsError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_payment_declined_by_payer_account_error.rb | app/business/payments/charging/errors/charge_processor_payment_declined_by_payer_account_error.rb | # frozen_string_literal: true
class ChargeProcessorPaymentDeclinedByPayerAccountError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_error.rb | app/business/payments/charging/errors/charge_processor_error.rb | # frozen_string_literal: true
class ChargeProcessorError < GumroadRuntimeError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_payer_cancelled_billing_agreement_error.rb | app/business/payments/charging/errors/charge_processor_payer_cancelled_billing_agreement_error.rb | # frozen_string_literal: true
class ChargeProcessorPayerCancelledBillingAgreementError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_error_generic.rb | app/business/payments/charging/errors/charge_processor_error_generic.rb | # frozen_string_literal: true
class ChargeProcessorErrorGeneric < ChargeProcessorError
attr_reader :error_code
def initialize(error_code, message: nil, original_error: nil)
@error_code = error_code
super(message, original_error:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_invalid_request_error.rb | app/business/payments/charging/errors/charge_processor_invalid_request_error.rb | # frozen_string_literal: true
class ChargeProcessorInvalidRequestError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_unavailable_error.rb | app/business/payments/charging/errors/charge_processor_unavailable_error.rb | # frozen_string_literal: true
class ChargeProcessorUnavailableError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_error_rate_limit.rb | app/business/payments/charging/errors/charge_processor_error_rate_limit.rb | # frozen_string_literal: true
class ChargeProcessorErrorRateLimit < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_not_supported_error.rb | app/business/payments/charging/errors/charge_processor_not_supported_error.rb | # frozen_string_literal: true
class ChargeProcessorNotSupportedError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_card_error.rb | app/business/payments/charging/errors/charge_processor_card_error.rb | # frozen_string_literal: true
class ChargeProcessorCardError < ChargeProcessorError
attr_reader :error_code, :charge_id
def initialize(error_code, message = nil, original_error: nil, charge_id: nil)
@error_code = error_code
@charge_id = charge_id
super(message, original_error:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_payee_account_restricted_error.rb | app/business/payments/charging/errors/charge_processor_payee_account_restricted_error.rb | # frozen_string_literal: true
class ChargeProcessorPayeeAccountRestrictedError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/errors/charge_processor_already_refunded_error.rb | app/business/payments/charging/errors/charge_processor_already_refunded_error.rb | # frozen_string_literal: true
class ChargeProcessorAlreadyRefundedError < ChargeProcessorError
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_chargeable_transient_customer.rb | app/business/payments/charging/implementations/braintree/braintree_chargeable_transient_customer.rb | # frozen_string_literal: true
class BraintreeChargeableTransientCustomer < BraintreeChargeableBase
TRANSIENT_CLIENT_TOKEN_VALIDITY_DURATION = 5.minutes
attr_accessor :customer_id, :transient_customer_store_key
def initialize(customer_id, transient_customer_store_key)
@customer_id = customer_id
@transient_customer_store_key = transient_customer_store_key
end
def self.tokenize_nonce_to_transient_customer(braintree_nonce, transient_customer_store_key)
return nil if braintree_nonce.blank?
begin
braintree_customer = Braintree::Customer.create!(
credit_card: {
payment_method_nonce: braintree_nonce
}
)
rescue Braintree::ValidationsFailed, Braintree::ServerError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
end
transient_braintree_customer_store = Redis::Namespace.new(:transient_braintree_customer_store, redis: $redis)
transient_customer_token = ObfuscateIds.encrypt(braintree_customer.id)
transient_braintree_customer_store.set(transient_customer_store_key, transient_customer_token, ex: BraintreeChargeableTransientCustomer::TRANSIENT_CLIENT_TOKEN_VALIDITY_DURATION)
new(braintree_customer.id, transient_customer_store_key)
end
def self.from_transient_customer_store_key(transient_customer_store_key)
transient_braintree_customer_store = Redis::Namespace.new(:transient_braintree_customer_store, redis: $redis)
transient_customer_token = transient_braintree_customer_store.get(transient_customer_store_key)
raise ChargeProcessorInvalidRequestError, "could not find transient client token" if transient_customer_token.nil?
new(ObfuscateIds.decrypt(transient_customer_token), transient_customer_store_key)
end
def prepare!
unless @paypal || @card
@customer = Braintree::Customer.find(customer_id)
@paypal = @customer.paypal_accounts.first
@card = @customer.credit_cards.first
end
@paypal.present? || @card.present?
rescue Braintree::ValidationsFailed, Braintree::ServerError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue Braintree::NotFoundError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_charge_processor.rb | app/business/payments/charging/implementations/braintree/braintree_charge_processor.rb | # frozen_string_literal: true
class BraintreeChargeProcessor
DISPLAY_NAME = "Braintree"
MAXIMUM_DESCRIPTOR_LENGTH = 18
PROCESSOR_UNSUPPORTED_PAYMENT_ACCOUNT_ERROR_CODE = "2071"
PROCESSOR_UNSUPPORTED_PAYMENT_INSTRUMENT_ERROR_CODE = "2074"
private_constant :MAXIMUM_DESCRIPTOR_LENGTH, :PROCESSOR_UNSUPPORTED_PAYMENT_ACCOUNT_ERROR_CODE, :PROCESSOR_UNSUPPORTED_PAYMENT_INSTRUMENT_ERROR_CODE
# https://developers.braintreepayments.com/reference/general/statuses#transaction
VALID_TRANSACTION_STATUSES = [Braintree::Transaction::Status::Settled, Braintree::Transaction::Status::Settling, Braintree::Transaction::Status::SettlementPending].freeze
def self.charge_processor_id
"braintree"
end
def get_chargeable_for_params(params, _gumroad_guid)
zip_code = params[:cc_zipcode] if params[:cc_zipcode_required]
nonce = params[:braintree_nonce]
transient_customer_token = params[:braintree_transient_customer_store_key]
braintree_chargeable = BraintreeChargeableNonce.new(nonce, zip_code) if nonce.present?
if transient_customer_token.present?
braintree_chargeable ||=
BraintreeChargeableTransientCustomer.from_transient_customer_store_key(transient_customer_token)
end
braintree_chargeable&.braintree_device_data = params[:braintree_device_data]
braintree_chargeable
end
def get_chargeable_for_data(reusable_token, _payment_method_id, fingerprint,
_stripe_setup_intent_id, _stripe_payment_intent_id,
last4, number_length, visual, expiry_month, expiry_year,
card_type, country, zip_code = nil, merchant_account: nil)
BraintreeChargeableCreditCard.new(reusable_token, fingerprint, last4, number_length, visual, expiry_month, expiry_year, card_type, country, zip_code)
end
def search_charge(purchase:)
matched_transactions = Braintree::Transaction.search do |search|
search.order_id.is purchase.external_id
end
matched_transactions.first
end
def get_charge(charge_id, **_args)
begin
braintree_transaction = Braintree::Transaction.find(charge_id)
rescue Braintree::ValidationsFailed, Braintree::ServerError, Braintree::NotFoundError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
end
get_charge_object(braintree_transaction)
end
def get_charge_object(charge)
BraintreeCharge.new(charge, load_extra_details: true)
end
def create_payment_intent_or_charge!(merchant_account, chargeable, amount_cents, _amount_for_gumroad_cents, reference,
description, metadata: nil,
statement_description: nil, **_args)
params = {
merchant_account_id: merchant_account.charge_processor_merchant_id,
amount: amount_cents / 100.0,
customer_id: chargeable.braintree_customer_id,
order_id: reference, # PayPal Invoice ID
device_data: chargeable.braintree_device_data,
options: {
submit_for_settlement: true,
paypal: {
description:
}
},
custom_fields: {
purchase_external_id: reference,
description:
},
channel: "GUMROAD_SP"
}
if statement_description
statement_description = statement_description.gsub(/[^A-Z0-9. ]/i, "").to_s.strip[0...MAXIMUM_DESCRIPTOR_LENGTH]
# This is not an ideal solution, as the resulting descriptor name will be "GUM*GUM.CO/CC Creator "
# It is this way because Braintree requires:
# Company name/DBA section must be either 3, 7 or 12 characters and the product descriptor can be up to 18, 14, or 9 characters
# respectively (with an * in between for a total descriptor name of 22 characters).
if statement_description.present?
params[:descriptor] = {
name: "GUM*#{statement_description}",
phone: GUMROAD_MERCHANT_DESCRIPTOR_PHONE_NUMBER,
url: GUMROAD_MERCHANT_DESCRIPTOR_URL
}
end
end
begin
braintree_charge = Braintree::Transaction.sale(params)
transaction = braintree_charge.transaction
unless transaction.try(:status).in?(VALID_TRANSACTION_STATUSES)
if braintree_charge.errors.any?
# Expected to contain Braintree::ValidationsFailed
error = braintree_charge.errors.first
raise ChargeProcessorCardError.new(error.code,
error.message,
charge_id: transaction.try(:id))
end
raise ChargeProcessorCardError, Braintree::Transaction::Status::Failed if transaction.nil?
if transaction.status == Braintree::Transaction::Status::GatewayRejected
raise ChargeProcessorCardError.new(Braintree::Transaction::Status::GatewayRejected,
transaction.gateway_rejection_reason,
charge_id: transaction.try(:id))
elsif transaction.status == Braintree::Transaction::Status::ProcessorDeclined
if transaction.processor_response_code == PROCESSOR_UNSUPPORTED_PAYMENT_ACCOUNT_ERROR_CODE
raise ChargeProcessorUnsupportedPaymentAccountError.new(transaction.processor_response_code,
transaction.processor_response_text,
charge_id: transaction.id)
elsif transaction.processor_response_code == PROCESSOR_UNSUPPORTED_PAYMENT_INSTRUMENT_ERROR_CODE
raise ChargeProcessorUnsupportedPaymentTypeError.new(transaction.processor_response_code,
transaction.processor_response_text,
charge_id: transaction.id)
end
raise ChargeProcessorCardError.new(transaction.processor_response_code,
transaction.processor_response_text,
charge_id: transaction.id)
elsif transaction.status == Braintree::Transaction::Status::SettlementDeclined
raise ChargeProcessorCardError.new(transaction.processor_settlement_response_code,
transaction.processor_settlement_response_text,
charge_id: transaction.id)
else
raise ChargeProcessorCardError.new(Braintree::Transaction::Status::Failed,
charge_id: transaction.id)
end
end
rescue Braintree::ServerError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
rescue Braintree::BraintreeError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
end
charge = BraintreeCharge.new(transaction, load_extra_details: false)
BraintreeChargeIntent.new(charge:)
end
def refund!(charge_id, amount_cents: nil, **_args)
begin
braintree_transaction =
if amount_cents.nil?
Braintree::Transaction.refund!(charge_id)
else
Braintree::Transaction.refund!(charge_id, amount_cents / 100.0)
end
rescue Braintree::ValidationsFailed => e
first_error = e.error_result.errors.first
if first_error.try(:code) == Braintree::ErrorCodes::Transaction::HasAlreadyBeenRefunded
raise ChargeProcessorAlreadyRefundedError.new("Braintree charge was already refunded. Braintree response: #{first_error.message}", original_error: e)
end
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue Braintree::ServerError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
rescue Braintree::BraintreeError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
end
BraintreeChargeRefund.new(braintree_transaction)
end
def holder_of_funds(_merchant_account)
HolderOfFunds::GUMROAD
end
def transaction_url(charge_id)
sub_domain = Rails.env.production? ? "www" : "sandbox"
"https://#{sub_domain}.braintreegateway.com/merchants/#{Braintree::Configuration.merchant_id}/transactions/#{charge_id}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_chargeable_nonce.rb | app/business/payments/charging/implementations/braintree/braintree_chargeable_nonce.rb | # frozen_string_literal: true
class BraintreeChargeableNonce < BraintreeChargeableBase
def initialize(nonce, zip_code)
@nonce = nonce
@zip_code = zip_code
end
def prepare!
unless @paypal || @card
@customer = Braintree::Customer.create!(
credit_card: {
payment_method_nonce: @nonce
}
)
@paypal = @customer.paypal_accounts.first
@card = @customer.credit_cards.first
end
@paypal.present? || @card.present?
rescue Braintree::ValidationsFailed, Braintree::ServerError => e
raise ChargeProcessorInvalidRequestError.new(original_error: e)
rescue *BraintreeExceptions::UNAVAILABLE => e
raise ChargeProcessorUnavailableError.new(original_error: e)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_chargeable_credit_card.rb | app/business/payments/charging/implementations/braintree/braintree_chargeable_credit_card.rb | # frozen_string_literal: true
# Public: Chargeable representing a card stored at Braintree.
class BraintreeChargeableCreditCard
attr_reader :fingerprint, :last4, :number_length, :visual, :expiry_month, :expiry_year, :zip_code, :card_type, :country
attr_reader :braintree_customer_id
def initialize(reusable_token, fingerprint, last4, number_length, visual, expiry_month, expiry_year, card_type, country, zip_code = nil)
@braintree_customer_id = reusable_token
@fingerprint = fingerprint
@last4 = last4
@number_length = number_length
@visual = visual
@expiry_month = expiry_month
@expiry_year = expiry_year
@card_type = card_type
@country = country
@zip_code = zip_code
end
def charge_processor_id
BraintreeChargeProcessor.charge_processor_id
end
def prepare!
true
end
def reusable_token!(_user)
braintree_customer_id
end
def braintree_device_data
nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_charge_refund.rb | app/business/payments/charging/implementations/braintree/braintree_charge_refund.rb | # frozen_string_literal: true
class BraintreeChargeRefund < ChargeRefund
def initialize(braintree_transaction)
self.charge_processor_id = BraintreeChargeProcessor.charge_processor_id
self.id = braintree_transaction.id
self.charge_id = braintree_transaction.refunded_transaction_id
currency = Currency::USD
amount_cents = -1 * (braintree_transaction.amount * 100).to_i
self.flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(currency, amount_cents)
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.