repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/post_email_api.rb | app/services/post_email_api.rb | # frozen_string_literal: true
class PostEmailApi
RESEND_EXCLUDED_DOMAINS = ["example.com", "example.org", "example.net", "test.com"]
private_constant :RESEND_EXCLUDED_DOMAINS
def self.process(**args)
post = args[:post]
recipients = args[:recipients]
if Feature.inactive?(:use_resend_for_post_emails, post&.seller)
return PostSendgridApi.process(**args)
end
if Feature.active?(:force_resend_for_post_emails, post&.seller)
return PostResendApi.process(**args)
end
# Split recipients based on email provider determination
recipients_by_provider = recipients.group_by do |recipient|
email = recipient[:email]
# If the email contains non-ASCII characters or special characters, route it through SendGrid
if valid_email_address_for_resend?(email)
MailerInfo::Router.determine_email_provider(MailerInfo::DeliveryMethod::DOMAIN_CREATORS)
else
MailerInfo::EMAIL_PROVIDER_SENDGRID
end
end
resend_recipients = recipients_by_provider[MailerInfo::EMAIL_PROVIDER_RESEND] || []
sendgrid_recipients = recipients_by_provider[MailerInfo::EMAIL_PROVIDER_SENDGRID] || []
PostResendApi.process(**args.merge(recipients: resend_recipients)) if resend_recipients.any?
PostSendgridApi.process(**args.merge(recipients: sendgrid_recipients)) if sendgrid_recipients.any?
end
def self.max_recipients
if Feature.active?(:use_resend_for_post_emails)
PostResendApi::MAX_RECIPIENTS
else
PostSendgridApi::MAX_RECIPIENTS
end
end
private
def self.valid_email_address_for_resend?(email)
return false unless email.present?
return false unless email.ascii_only?
return false if email.length > 254
local_part, domain = email.split("@")
return false unless local_part.present? && domain.present?
return false if local_part.length > 64
return false if local_part.match?(/[^a-zA-Z0-9.+_]/)
return false unless domain.include?(".")
return false if RESEND_EXCLUDED_DOMAINS.include?(domain)
# Use Rails' built-in email validation regex
email_regex = URI::MailTo::EMAIL_REGEXP
email.match?(email_regex)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/rpush_apns_app_service.rb | app/services/rpush_apns_app_service.rb | # frozen_string_literal: true
class RpushApnsAppService
attr_reader :name
def initialize(name:)
@name = name
end
def first_or_create!
first || create!
end
private
def first
Rpush::Apns2::App.all.select { |app| app.name == name }.first
end
def create!
certificate = File.read(Rails.root.join("config",
"certs",
certificate_name))
app = Rpush::Apns2::App.new(name:,
certificate:,
environment: app_environment,
password:,
connections: 1)
app.save!
app
end
def creator_app?
@name == Device::APP_TYPES[:creator]
end
def certificate_name
if creator_app?
"#{app_environment}_com.GRD.iOSCreator.pem"
else
"#{app_environment}_com.GRD.Gumroad.pem"
end
end
def password
creator_app? ? GlobalConfig.get("RPUSH_APN_CERT_CREATOR_PASSWORD") : GlobalConfig.get("RPUSH_APN_CERT_BUYER_PASSWORD")
end
def app_environment
(Rails.env.staging? || Rails.env.production?) ? "production" : "development"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/rpush_fcm_app_service.rb | app/services/rpush_fcm_app_service.rb | # frozen_string_literal: true
class RpushFcmAppService
attr_reader :name
def initialize(name:)
@name = name
end
def first_or_create!
first || create!
end
private
def first
Rpush::Fcm::App.all.select { |app| app.name == name }.first
end
def create!
app = Rpush::Fcm::App.new(name:,
json_key:,
firebase_project_id:,
connections: 1)
app.save!
app
end
def json_key
GlobalConfig.get("RPUSH_CONSUMER_FCM_JSON_KEY")
end
def firebase_project_id
GlobalConfig.get("RPUSH_CONSUMER_FCM_FIREBASE_PROJECT_ID")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/purchasing_power_parity_service.rb | app/services/purchasing_power_parity_service.rb | # frozen_string_literal: true
class PurchasingPowerParityService
def get_factor(country_code, seller)
factor = if country_code.present?
(ppp_namespace.get(country_code).presence || 1).to_f
else
1.0
end
[factor, seller.min_ppp_factor].max
end
def set_factor(country_code, factor)
ppp_namespace.set(country_code, factor.to_s)
end
def get_all_countries_factors(seller)
country_codes = Compliance::Countries.mapping.keys
country_codes.zip(ppp_namespace.mget(country_codes)).to_h.transform_values do |value|
[(value.presence || 1).to_f, seller.min_ppp_factor].max
end
end
private
def ppp_namespace
@_ppp_namespace ||= Redis::Namespace.new(:ppp, redis: $redis)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/instant_payouts_service.rb | app/services/instant_payouts_service.rb | # frozen_string_literal: true
class InstantPayoutsService
attr_reader :seller, :date
def initialize(seller, date: Date.today)
@seller = seller
@date = date
end
def perform
return { success: false, error: "Your account is not eligible for instant payouts at this time." } unless seller.instant_payouts_supported?
balances = seller.instantly_payable_unpaid_balances
.filter { |balance| balance.date <= date }
.sort_by(&:created_at)
return { success: false, error: "You need at least $10 in your balance to request an instant payout." } if balances.sum(&:holding_amount_cents) < StripePayoutProcessor::MINIMUM_INSTANT_PAYOUT_AMOUNT_CENTS
if balances.any? { |balance| balance.holding_amount_cents > StripePayoutProcessor::MAXIMUM_INSTANT_PAYOUT_AMOUNT_CENTS }
return { success: false, error: "Your balance exceeds the maximum instant payout amount. Please contact support for assistance." }
end
balances.each_with_object([[]]) do |balance, batches|
if batches.last.sum(&:holding_amount_cents) + balance.holding_amount_cents > StripePayoutProcessor::MAXIMUM_INSTANT_PAYOUT_AMOUNT_CENTS
batches << []
end
batches.last << balance
end.then do |batches|
results = batches.map do |batch|
payment, payment_errors = Payouts.create_payment(
batch.last.date,
PayoutProcessorType::STRIPE,
seller,
payout_type: Payouts::PAYOUT_TYPE_INSTANT
)
if payment.present? && payment_errors.blank?
StripePayoutProcessor.process_payments([payment])
{ success: !payment.failed? }
else
{ success: false }
end
end
if results.all? { |result| result[:success] }
{ success: true }
else
{ success: false, error: "Failed to process instant payout" }
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/clean_us_zip_code_database_file.rb | app/services/clean_us_zip_code_database_file.rb | # frozen_string_literal: true
# This script manipulates the United States zip codes file to only include information we need (zip codes and states).
# It's only meant to be executed locally.
#
# Steps:
#
# 1. Ask Sahil to purchase an Enterprise license from https://www.unitedstateszipcodes.org/zip-code-database/ with email address paypal@gumroad.com
# 2. After Sahil purchases, go to https://www.unitedstateszipcodes.org/order-download/
# 3. Enter paypal@gumroad.com (or the email he used for the purchase)
# 4. Download the `Enterprise in CSV Format` file (should be named zip_code_database_enterprise.csv) and place it in the /config directory
# 5. In a development Rails console: CleanUsZipCodeDatabaseFile.process
# 6. Commit, Pull Request, push
class CleanUsZipCodeDatabaseFile
def self.process
raise "Only run in development" unless Rails.env.development?
source_file_path = "#{Rails.root}/config/zip_code_database_enterprise.csv"
destination_file_path = "#{Rails.root}/config/zip_code_database.csv"
File.delete(destination_file_path) if File.exist?(destination_file_path)
rows = CSV.parse(File.read(source_file_path)).map! { |row| [row[0], row[6]] }
CSV.open(destination_file_path, "w") do |csv|
rows.each do |row|
csv << row
end
end
File.delete(source_file_path) if File.exist?(source_file_path); nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/offer_code_discount_computing_service.rb | app/services/offer_code_discount_computing_service.rb | # frozen_string_literal: true
class OfferCodeDiscountComputingService
# While computing it rejects the product if quantity of the product is greater
# than the quantity left for the offer_code for e.g. Suppose seller adds a
# universal offer code which has 4 quantity left and a user adds three products
# in bundle - A[2], B[3], C[1] (product names with quantity) and applies the
# offer code. Then offer code will be applied on A[2], B[0], C[1]. It skipped B
# because quantity of B was greater than the limit left for the offer_code.
# Taking some more examples
# => A[2], B[3], C[2] --> A[2], C[2]
# => A[2], C[3] --> A[2]
def initialize(code, products)
@code = code
@products = products
end
def process
products_data = {}
links.each do |link|
purchase_quantity = products[link.unique_permalink][:quantity].to_i
offer_code = find_applicable_offer_code_for(link)
next unless offer_code
track_applicable_offer_code(offer_code)
if eligible?(offer_code, purchase_quantity)
track_usage(offer_code, purchase_quantity)
products_data[link.unique_permalink] = { discount: offer_code.discount }
optimistically_apply_to_applicable_cross_sells(products_data, link)
else
track_ineligibility(offer_code, purchase_quantity)
end
end
{
products_data:,
error_code:
}
end
private
attr_reader :code, :products
def links
@_links ||= Link.visible
.includes({ available_cross_sells: :product })
.where(unique_permalink: products.values.map { it[:permalink] })
end
def offer_codes
return OfferCode.none if code.blank?
@_offer_codes ||= OfferCode
.includes(:products)
.where(user_id: links.map(&:user_id), code:)
.alive
end
def offer_codes_by_user_id
@_offer_codes_by_user_id ||= offer_codes.group_by(&:user_id)
end
def find_applicable_offer_code_for(link)
offer_codes_by_user_id[link.user_id]
&.find { |offer_code| offer_code.applicable?(link) }
end
def eligible?(offer_code, purchase_quantity)
return false if offer_code.inactive?
return false unless meets_minimum_purchase_quantity?(offer_code, purchase_quantity)
return false unless has_sufficient_times_of_use?(offer_code, purchase_quantity)
true
end
def meets_minimum_purchase_quantity?(offer_code, purchase_quantity)
offer_code.minimum_quantity.blank? ||
purchase_quantity >= offer_code.minimum_quantity
end
def has_sufficient_times_of_use?(offer_code, purchase_quantity)
offer_code.max_purchase_count.blank? ||
remaining_times_of_use(offer_code) >= purchase_quantity
end
def remaining_times_of_use(offer_code)
@remaining_times_of_use ||= {}
@remaining_times_of_use[offer_code.id] ||= offer_code.quantity_left
end
def track_applicable_offer_code(offer_code)
@applicable_offer_codes ||= []
@applicable_offer_codes << offer_code
end
def track_usage(offer_code, purchase_quantity)
return if offer_code.max_purchase_count.blank?
@remaining_times_of_use[offer_code.id] -= purchase_quantity
end
def track_ineligibility(offer_code, purchase_quantity)
@product_level_ineligibilities ||= {}
unless meets_minimum_purchase_quantity?(offer_code, purchase_quantity)
@product_level_ineligibilities[:unmet_minimum_purchase_quantity] = true
end
unless has_sufficient_times_of_use?(offer_code, purchase_quantity)
if @remaining_times_of_use[offer_code.id].positive?
@product_level_ineligibilities[:insufficient_times_of_use] = true
else
@product_level_ineligibilities[:sold_out] = true
end
end
end
PRODUCT_LEVEL_INELIGIBILITIES_BY_DISPLAY_PRIORITY = [
:unmet_minimum_purchase_quantity,
:insufficient_times_of_use,
:sold_out,
]
def error_code
return :invalid_offer if @applicable_offer_codes.blank?
return :inactive if @applicable_offer_codes.all?(&:inactive?)
return nil if @product_level_ineligibilities.blank?
PRODUCT_LEVEL_INELIGIBILITIES_BY_DISPLAY_PRIORITY
.find { @product_level_ineligibilities[it] }
end
# This is optimistic because additive cross-sells may not meet the minimum
# purchase quantity or the discount code may have been used up. The discount
# will still be validated and updated during checkout, where the buyer will
# be able to see the correct discount and adjust accordingly.
def optimistically_apply_to_applicable_cross_sells(products_data, link)
link.available_cross_sells.each do |cross_sell|
offer_code = find_applicable_offer_code_for(cross_sell.product)
next unless offer_code
products_data[cross_sell.product.unique_permalink] = { discount: offer_code.discount }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/black_friday_stats_service.rb | app/services/black_friday_stats_service.rb | # frozen_string_literal: true
class BlackFridayStatsService
CACHE_KEY = "black_friday_stats"
CACHE_EXPIRATION = 10.minutes
class << self
def fetch_stats
Rails.cache.fetch(CACHE_KEY, expires_in: CACHE_EXPIRATION) do
calculate_stats
end
end
def calculate_stats
# TODO: Implement actual stats calculation
# For now, returning placeholder values
{
active_deals_count: 0,
revenue_cents: 0,
average_discount_percentage: 0
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/user_balance_stats_service.rb | app/services/user_balance_stats_service.rb | # frozen_string_literal: true
class UserBalanceStatsService
include ActionView::Helpers::TranslationHelper
include PayoutsHelper
attr_reader :user
DEFAULT_SALES_CACHING_THRESHOLD = 50_000
def initialize(user:)
@user = user
end
def fetch
if should_use_cache?
UpdateUserBalanceStatsCacheWorker.perform_async(user.id)
read_cache || generate
else
generate
end
end
def write_cache
data = generate
$redis.setex(cache_key, 48.hours.to_i, data.to_json)
end
def self.cacheable_users
sales_threshold = $redis.get(RedisKey.balance_stats_sales_caching_threshold)
sales_threshold ||= DEFAULT_SALES_CACHING_THRESHOLD
excluded_user_ids = $redis.smembers(RedisKey.balance_stats_users_excluded_from_caching)
users = User
.joins(:large_seller)
.where("large_sellers.sales_count >= ?", sales_threshold.to_i)
users = users.where("large_sellers.user_id NOT IN (?)", excluded_user_ids) unless excluded_user_ids.empty?
users
end
private
def generate
balances_by_product_service = BalancesByProductService.new(user)
result = {
generated_at: Time.current,
next_payout_period_data:,
processing_payout_periods_data: user.payments.processing.order("created_at DESC").map { payout_period_data(user, _1) },
overview: {
last_payout_period_data: payout_period_data(user, user.payments.completed.last),
balance: user.unpaid_balance_cents(via: :elasticsearch),
balances_by_product: balances_by_product_service.process,
last_seven_days_sales_total: user.sales_cents_total(after: 7.days.ago),
last_28_days_sales_total: user.sales_cents_total(after: 28.days.ago),
sales_cents_total: user.sales_cents_total,
},
}
payments = user.payments.completed
.displayable
.order("created_at DESC")
if payments.size > PayoutsPresenter::PAST_PAYMENTS_PER_PAGE
payments = payments.limit(PayoutsPresenter::PAST_PAYMENTS_PER_PAGE)
result[:is_paginating] = true
else
result[:is_paginating] = false
end
payments = payments.load
result[:payout_period_data] = payments.to_h do |payment|
[payment.id, payout_period_data(user, payment)]
end
result[:payments] = payments
result
end
def read_cache
data = $redis.get(cache_key)
return nil unless data
JSON.parse(data, symbolize_names: true)
rescue JSON::ParserError => e
Rails.logger.error("Failed to parse cached balance stats for user #{user.id}: #{e.message}")
nil
end
def should_use_cache?
@should_use_cache ||= self.class.cacheable_users.where(id: user.id).exists?
end
def cache_key
"balance_stats_for_user_#{user.id}"
end
def next_payout_period_data
return if user.payments
.processing
.where("JSON_UNQUOTE(JSON_EXTRACT(json_data, '$.type')) != ? OR JSON_EXTRACT(json_data, '$.type') IS NULL", Payouts::PAYOUT_TYPE_INSTANT)
.any?
payout_period_data(user)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/redis_key.rb | app/services/redis_key.rb | # frozen_string_literal: true
class RedisKey
class << self
def total_made = "homepage:total_made"
def number_of_creators = "company_page:number_of_creators"
def prev_week_payout_usd = "homepage:prev_week_payout_usd"
def balance_stats_sales_caching_threshold = "balance_stats:sales_caching_threshold"
def balance_stats_users_excluded_from_caching = "balance_stats:users_excluded_from_caching"
def balance_stats_scheduler_minutes_between_jobs = "balance_stats_scheduler:minutes_between_jobs"
def elasticsearch_indexer_worker_ignore_404_errors_on_indices = "elasticsearch_indexer_worker:ignore_404_errors_on_indices"
def product_presenter_existing_product_files_limit = "product_presenter:existing_product_files_limit"
def seller_analytics_cache_version = "seller_analytics:cache_version"
def cf_cache_invalidated_extensions_and_cache_keys = "cf_cache_invalidated_extensions_and_cache_keys"
def user_ids_with_payment_requirements_key = "user_ids_with_payment_requirements_key"
def card_testing_product_watch_minutes = "card_testing_product_watch_minutes"
def card_testing_product_max_failed_purchases_count = "card_testing_product_max_failed_purchases_count"
def card_testing_product_block_hours = "card_testing_product_block_hours"
def card_testing_max_number_of_failed_purchases_in_a_row = "card_testing_max_number_of_failed_purchases_in_a_row"
def card_testing_failed_purchases_in_a_row_watch_days = "card_testing_failed_purchases_in_a_row_watch_days"
def followers_import_limit = "followers_import:limit"
def force_product_id_timestamp = "force_product_id_timestamp"
def api_v2_sales_deprecated_pagination_query_timeout = "api_v2_sales_deprecated_pagination_query_timeout"
def free_purchases_watch_hours = "free_purchases_watch_hours"
def max_allowed_free_purchases_of_same_product = "max_allowed_free_purchases_of_same_product"
def ai_request_throttle(user_id) = "ai_request_throttle:#{user_id}"
def fraudulent_free_purchases_block_hours = "fraudulent_free_purchases_block_hours"
def sales_related_products_internal_limit = "sales_related_products_internal_limit"
def recommended_products_associated_product_ids_limit = "recommended_products_associated_product_ids_limit"
def blast_recipients_slice_size = "blast:recipients_slice_size"
def impersonated_user(admin_user_id) = "impersonated_user_by_admin_#{admin_user_id}"
def gumroad_day_date = "gumroad_day_date"
def update_cached_srpis_job_delay_hours = "update_cached_srpis_job_delay_hours"
def iffy_moderation_probability = "iffy_moderation_probability"
def tip_options = "tip_options"
def default_tip_option = "default_tip_option"
def create_canada_monthly_sales_report_job_max_execution_time_seconds = "create_canada_monthly_sales_report_job:max_execution_time_seconds"
def generate_sales_report_job_max_execution_time_seconds = "generate_sales_report_job:max_execution_time_seconds"
def generate_canada_sales_report_job_max_execution_time_seconds = "generate_canada_sales_report_job:max_execution_time_seconds"
def create_vat_report_job_max_execution_time_seconds = "create_vat_report_job:max_execution_time_seconds"
def transcoded_videos_recentness_limit_in_months = "transcoded_videos_recentness_limit_in_months"
def generate_fees_by_creator_location_job_max_execution_time_seconds = "generate_fees_by_creator_location_job:max_execution_time_seconds"
def ytd_sales_report_emails = "reports:ytd_sales_report_emails"
def failed_seller_purchases_watch_minutes = "failed_seller_purchases_watch_minutes"
def max_seller_failed_purchases_price_cents = "max_seller_failed_purchases_price_cents"
def seller_age_threshold_days = "seller_age_threshold_days"
def sales_report_jobs = "sales_report_jobs"
def acme_challenge(token) = "acme_challenge:#{token}"
def unreviewed_users_data = "admin:unreviewed_users_data"
def unreviewed_users_cutoff_date = "admin:unreviewed_users_cutoff_date"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product_indexing_service.rb | app/services/product_indexing_service.rb | # frozen_string_literal: true
class ProductIndexingService
def self.perform(product:, action:, attributes_to_update: [], on_failure: :raise)
case action
when "index"
product.__elasticsearch__.index_document
when "update"
return if attributes_to_update.empty?
attributes = product.build_search_update(attributes_to_update)
product.__elasticsearch__.update_document_attributes(attributes.as_json)
end
rescue
if on_failure == :async
SendToElasticsearchWorker.perform_in(5.seconds, product.id, action, attributes_to_update)
Rails.logger.error("Failed to #{action} product #{product.id} (#{attributes_to_update.join(", ")}), queued job instead")
else
raise
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/email_redactor_service.rb | app/services/email_redactor_service.rb | # frozen_string_literal: true
class EmailRedactorService
def self.redact(email)
username, domain = email.split("@")
domain_name, _, tld = domain.rpartition(".")
redacted_username = username.length > 1 ? "#{username[0]}#{'*' * (username.length - 2)}#{username[-1]}" : username
redacted_domain = "#{domain_name[0]}#{'*' * (domain_name.length - 1)}"
"#{redacted_username}@#{redacted_domain}.#{tld}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/circle_api.rb | app/services/circle_api.rb | # frozen_string_literal: true
class CircleApi
include HTTParty
base_uri "https://app.circle.so/api/v1"
def initialize(api_key)
@api_key = api_key
end
def get_communities
rate_limited_call { self.class.get("/communities", headers:) }
end
def get_spaces(community_id)
rate_limited_call { self.class.get("/spaces", query: { "community_id" => community_id }, headers:) }
end
def get_space_groups(community_id)
rate_limited_call { self.class.get("/space_groups", query: { "community_id" => community_id }, headers:) }
end
def add_member(community_id, space_group_id, email)
rate_limited_call { self.class.post("/community_members", query: { "community_id" => community_id, "space_group_ids[]" => space_group_id, "email" => email }, headers:) }
end
def remove_member(community_id, email)
rate_limited_call { self.class.delete("/community_members", query: { "community_id" => community_id, "email" => email }, headers:) }
end
private
def headers
{
"Authorization" => "Token #{@api_key}"
}
end
def rate_limited_call(&block)
key = "CIRCLE_API_RATE_LIMIT"
ratelimit = Ratelimit.new(key, { redis: $redis })
ratelimit.exec_within_threshold key, threshold: 100, interval: 60 do
ratelimit.add(key)
block.call
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/handle_email_event_info.rb | app/services/handle_email_event_info.rb | # frozen_string_literal: true
# Email provider-agnostic service to handle email event info.
# The logic should not handle any email provider (Sendgrid, Resend) specific logic.
# For that, user EmailEventInfo subclasses (SendgridEventInfo, ResendEventInfo).
#
class HandleEmailEventInfo
def self.perform(email_event_info)
if email_event_info.for_installment_email?
HandleEmailEventInfo::ForInstallmentEmail.perform(email_event_info)
elsif email_event_info.for_receipt_email?
HandleEmailEventInfo::ForReceiptEmail.perform(email_event_info)
elsif email_event_info.for_abandoned_cart_email?
HandleEmailEventInfo::ForAbandonedCartEmail.perform(email_event_info)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/cleanup_rpush_device_service.rb | app/services/cleanup_rpush_device_service.rb | # frozen_string_literal: true
class CleanupRpushDeviceService
def initialize(feedback)
@feedback = feedback
end
def process
Device.where(token: @feedback.device_token).destroy_all
@feedback.destroy
rescue => e
Rails.logger.error "Could not clean up a device token based on APN feedback #{@feedback.inspect}: #{e.inspect}"
Bugsnag.notify "Could not clean up a device token based on APN feedback #{@feedback.inspect}: #{e.inspect}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/home_page_link_service.rb | app/services/home_page_link_service.rb | # frozen_string_literal: true
class HomePageLinkService
PAGES = [:privacy, :terms, :about, :features, :university, :pricing, :affiliates, :prohibited]
private_constant :PAGES
ROOT_DOMAIN_WITH_PROTCOL = UrlService.root_domain_with_protocol
private_constant :ROOT_DOMAIN_WITH_PROTCOL
class << self
PAGES.each do |page|
define_method(page) { prepend_host("/#{page}") }
end
def root
ROOT_DOMAIN_WITH_PROTCOL
end
private
def prepend_host(page)
"#{ROOT_DOMAIN_WITH_PROTCOL}#{page}"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/update_user_country.rb | app/services/update_user_country.rb | # frozen_string_literal: true
class UpdateUserCountry
attr_reader :new_country_code, :user
def initialize(new_country_code:, user:)
@old_country_code = user.alive_user_compliance_info.legal_entity_country_code
@new_country_code = new_country_code
@user = user
end
def process
keep_payment_address = !@user.native_payouts_supported? && !@user.native_payouts_supported?(country_code: @new_country_code)
@user.update!(payment_address: "") unless keep_payment_address
@user.comments.create!(
author_id: GUMROAD_ADMIN_ID,
comment_type: Comment::COMMENT_TYPE_COUNTRY_CHANGED,
content: "Country changed from #{@old_country_code} to #{@new_country_code}"
)
@user.forfeit_unpaid_balance!(:country_change)
@user.stripe_account.try(:delete_charge_processor_account!)
@user.active_bank_account.try(:mark_deleted!)
@user.user_compliance_info_requests.requested.find_each(&:mark_provided!)
@user.alive_user_compliance_info.mark_deleted!
@user.user_compliance_infos.build.tap do |new_user_compliance_info|
new_user_compliance_info.country = Compliance::Countries.mapping[@new_country_code]
new_user_compliance_info.json_data = {}
new_user_compliance_info.save!
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/robots_service.rb | app/services/robots_service.rb | # frozen_string_literal: true
class RobotsService
SITEMAPS_CACHE_EXPIRY = 1.week.to_i
private_constant :SITEMAPS_CACHE_EXPIRY
SITEMAPS_CACHE_KEY = "sitemap_configs"
private_constant :SITEMAPS_CACHE_KEY
def sitemap_configs
cache_fetch(SITEMAPS_CACHE_KEY, ex: SITEMAPS_CACHE_EXPIRY) do
generate_sitemap_configs
end
end
def user_agent_rules
[
"User-agent: *",
"Disallow: /purchases/"
]
end
def expire_sitemap_configs_cache
redis_namespace.del(SITEMAPS_CACHE_KEY)
end
private
def cache_fetch(cache_key, ex: nil)
data = redis_namespace.get(cache_key)
return JSON.parse(data) if data.present?
data = yield
redis_namespace.set(cache_key, data.to_json, ex:)
data
end
def generate_sitemap_configs
s3 = Aws::S3::Client.new
s3.list_objects(bucket: PUBLIC_STORAGE_S3_BUCKET, prefix: "sitemap/").flat_map do |response|
response.contents.map { |object| "Sitemap: #{PUBLIC_STORAGE_CDN_S3_PROXY_HOST}/#{object.key}" }
end
end
def redis_namespace
@_robots_redis_namespace ||= Redis::Namespace.new(:robots_redis_namespace, redis: $redis)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/discord_api.rb | app/services/discord_api.rb | # frozen_string_literal: true
class DiscordApi
def oauth_token(code, redirect_uri)
body = {
grant_type: "authorization_code",
code:,
client_id: DISCORD_CLIENT_ID,
client_secret: DISCORD_CLIENT_SECRET,
redirect_uri:
}
headers = { "Content-Type" => "application/x-www-form-urlencoded" }
HTTParty.post(DISCORD_OAUTH_TOKEN_URL, body: URI.encode_www_form(body), headers:)
end
def identify(token)
Discordrb::API::User.profile(bearer_token(token))
end
def disconnect(server)
Discordrb::API::User.leave_server(bot_token, server)
end
def add_member(server, user, access_token)
Discordrb::API::Server.add_member(bot_token, server, user, access_token)
end
def remove_member(server, user)
Discordrb::API::Server.remove_member(bot_token, server, user)
end
def resolve_member(server, user)
Discordrb::API::Server.resolve_member(bot_token, server, user)
end
def roles(server)
Discordrb::API::Server.roles(bot_token, server)
end
private
def bot_token
"Bot #{DISCORD_BOT_TOKEN}"
end
def bearer_token(token)
"Bearer #{token}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/merge_carts_service.rb | app/services/merge_carts_service.rb | # frozen_string_literal: true
class MergeCartsService
attr_reader :source_cart, :target_cart, :user, :browser_guid, :email
def initialize(source_cart:, target_cart:, user: nil, browser_guid: nil)
@source_cart = source_cart
@target_cart = target_cart
@user = user || @target_cart&.user.presence || @source_cart&.user.presence
@browser_guid = browser_guid || @source_cart&.browser_guid
@email = @target_cart&.email.presence || @source_cart&.email.presence || @user&.email
end
def process
ActiveRecord::Base.transaction do
if source_cart.nil? || source_cart.deleted?
target_cart&.update!(user:, browser_guid:, email:)
elsif target_cart.nil? || target_cart.deleted?
source_cart&.update!(user:, browser_guid:, email:)
elsif source_cart.id != target_cart.id
source_cart_products = source_cart.alive_cart_products
target_cart_products = target_cart.alive_cart_products
if source_cart_products.empty? && target_cart_products.empty?
source_cart.mark_deleted!
target_cart.update!(user:, browser_guid:, email:)
else
target_cart_product_ids = target_cart_products.pluck(:product_id, :option_id)
source_cart_products.each do |cart_product|
next if target_cart_product_ids.include?([cart_product.product_id, cart_product.option_id])
target_cart.cart_products << cart_product.dup
end
target_cart_discount_codes = target_cart.discount_codes.map { _1["code"] }
source_cart.discount_codes.each do |discount_code|
target_cart.discount_codes << discount_code unless target_cart_discount_codes.include?(discount_code["code"])
end
target_cart.return_url = source_cart.return_url if target_cart.return_url.blank?
target_cart.reject_ppp_discount = true if source_cart.reject_ppp_discount?
target_cart.user = user
target_cart.browser_guid = browser_guid
target_cart.email = email
target_cart.save!
source_cart.mark_deleted!
end
end
end
rescue => e
Rails.logger.error("Failed to merge source cart (#{source_cart&.id}) with target cart (#{target_cart&.id}): #{e.full_message}")
Bugsnag.notify(e)
source_cart.mark_deleted! if source_cart.alive?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/helper_user_info_service.rb | app/services/helper_user_info_service.rb | # frozen_string_literal: true
class HelperUserInfoService
include Rails.application.routes.url_helpers
def initialize(email:, recent_purchase_period: 1.year)
@email = email
@recent_purchase_period = recent_purchase_period
end
def customer_info
{
**user_details,
metadata: {
**user_metadata,
**seller_comments,
**sales_info,
**recent_purchase_info,
}
}
end
private
def user_details
return {} unless user
details = {
name: user.name,
value: [
user.sales_cents_total,
purchases_cents_total(after: 90.days.ago)
].max,
actions: {
"Admin (user)" => admin_user_url(user, host: UrlService.domain_with_protocol),
"Admin (purchases)" => admin_search_purchases_url(query: user.email, host: UrlService.domain_with_protocol),
"Impersonate" => admin_impersonate_helper_action_url(user_id: user.external_id, host: UrlService.domain_with_protocol)
}
}
if user.merchant_accounts.alive.stripe.first&.charge_processor_merchant_id
details[:actions]["View Stripe account"] = admin_stripe_dashboard_helper_action_url(user_id: user.external_id, host: UrlService.domain_with_protocol)
end
details
end
def purchases_cents_total(after: nil)
search_params = {
purchaser: user,
state: "successful",
exclude_unreversed_chargedback: true,
exclude_refunded: true,
size: 0,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
amount_refunded_cents_total: { sum: { field: "amount_refunded_cents" } }
}
}
search_params[:created_after] = after if after
result = PurchaseSearchService.search(search_params)
total = result.aggregations.price_cents_total.value - result.aggregations.amount_refunded_cents_total.value
total.to_i
end
def user
@_user ||= User.find_by(email: @email) || User.find_by(support_email: @email)
end
def user_metadata
return {} unless user
{
"User ID" => user.id,
"Account Created" => user.created_at.to_fs(:formatted_date_full_month),
"Account Status" => user.suspended? ? "Suspended" : "Active",
"Country" => user.country,
}.compact_blank
end
def seller_comments
return {} unless user
comments = user.comments.order(:created_at)
formatted_comments = comments.map do |comment|
case comment.comment_type
when Comment::COMMENT_TYPE_PAYOUT_NOTE
"Payout Note: #{comment.content}" if comment.author_id == GUMROAD_ADMIN_ID
when Comment::COMMENT_TYPE_SUSPENSION_NOTE
"Suspension Note: #{comment.content}" if user.suspended?
when *Comment::RISK_STATE_COMMENT_TYPES
"Risk Note: #{comment.content}"
else
"Comment: #{comment.content}"
end
end
{ "Comments" => formatted_comments } if formatted_comments.present?
end
def recent_purchase_info
recent_purchase = find_recent_purchase
return unless recent_purchase
product = recent_purchase.link
purchase_info = if recent_purchase.failed?
failed_purchase_info(recent_purchase, product)
else
successful_purchase_info(recent_purchase, product)
end
{ "Most Recent Purchase" => { **purchase_info, **refund_policy_info(recent_purchase) } }
end
def find_recent_purchase
if user
user.purchases.created_after(@recent_purchase_period.ago).where.not(id: user.purchases.test_successful).last
else
Purchase.created_after(@recent_purchase_period.ago).where(email: @email).last
end
end
def failed_purchase_info(purchase, product)
{
"Status" => "Failed",
"Error" => purchase.formatted_error_code,
"Product" => product.name,
"Price" => purchase.formatted_display_price,
"Date" => purchase.created_at.to_fs(:formatted_date_full_month),
}
end
def successful_purchase_info(purchase, product)
{
"Status" => "Successful",
"Product" => product.name,
"Price" => purchase.formatted_display_price,
"Date" => purchase.created_at.to_fs(:formatted_date_full_month),
"Product URL" => product.long_url,
"Creator Support Email" => purchase.seller.support_email || purchase.seller.form_email,
"Creator Email" => purchase.seller_email,
"Receipt URL" => receipt_purchase_url(purchase.external_id, host: DOMAIN, email: purchase.email),
"License Key" => purchase.license_key,
}
end
def refund_policy_info(purchase)
return unless purchase.purchase_refund_policy
policy = purchase.purchase_refund_policy
{ "Refund Policy" => policy.fine_print || policy.title }
end
def sales_info
return {} unless user
{ "Total Earnings Since Joining" => Money.from_cents(user.sales_cents_total).format }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/gumroad_daily_analytics_compiler.rb | app/services/gumroad_daily_analytics_compiler.rb | # frozen_string_literal: true
class GumroadDailyAnalyticsCompiler
class << self
def compile_gumroad_price_cents(between: nil)
paid_purchases_between(between:)
.sum(:price_cents)
end
def compile_gumroad_fee_cents(between: nil)
purchase_cents = paid_purchases_between(between:)
.sum(:fee_cents)
service_cents = service_charges_between(between:)
.sum(:charge_cents)
purchase_cents + service_cents
end
def compile_creators_with_sales(between: nil)
User
.not_suspended
.joins(:sales)
.merge(paid_purchases_between(between:))
.where("purchases.price_cents >= ?", 100)
.count("distinct users.id")
end
def compile_gumroad_discover_price_cents(between: nil)
paid_purchases_between(between:)
.was_product_recommended
.sum(:price_cents)
end
private
def paid_purchases_between(between:)
Purchase
.paid
.created_between(between)
end
def service_charges_between(between:)
ServiceCharge
.successful
.not_refunded
.created_between(between)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/admin_search_service.rb | app/services/admin_search_service.rb | # frozen_string_literal: true
class AdminSearchService
class InvalidDateError < StandardError; end
def search_purchases(query: nil, email: nil, product_title_query: nil, purchase_status: nil, creator_email: nil, license_key: nil, transaction_date: nil, last_4: nil, card_type: nil, price: nil, expiry_date: nil, limit: nil)
purchases = Purchase.order(created_at: :desc)
if email.present?
purchases = purchases.where(email: email)
end
if query.present?
unions = [
Gift.select("gifter_purchase_id as purchase_id").where(gifter_email: query).to_sql,
Gift.select("giftee_purchase_id as purchase_id").where(giftee_email: query).to_sql,
Purchase.select("purchases.id as purchase_id").where(email: query).to_sql,
Purchase.select("purchases.id as purchase_id").where(card_visual: query, card_type: CardType::PAYPAL).to_sql,
Purchase.select("purchases.id as purchase_id").where(stripe_fingerprint: query).to_sql,
Purchase.select("purchases.id as purchase_id").where(ip_address: query).to_sql,
]
if (purchase_id = Purchase.from_external_id(query))
unions << Purchase.select("purchases.id as purchase_id").where(id: purchase_id).to_sql
end
if !Purchase.external_id?(query)
unions << Purchase.select("purchases.id as purchase_id").where(id: query.to_i).to_sql
end
union_sql = <<~SQL.squish
SELECT purchase_id FROM (
#{ unions.map { |u| "(#{u})" }.join(" UNION ") }
) via_gifts_and_purchases
SQL
purchases = purchases.where("purchases.id IN (#{union_sql})")
# To be used only when query is set, as that uses an index to select purchases
if product_title_query.present?
raise ArgumentError, "product_title_query requires query parameter to be set" unless query.present?
purchases = purchases.joins(:link).where("links.name LIKE ?", "%#{product_title_query}%")
end
if purchase_status.present?
case purchase_status
when "successful"
purchases = purchases.where(purchase_state: "successful")
when "failed"
purchases = purchases.where(purchase_state: "failed")
when "not_charged"
purchases = purchases.where(purchase_state: "not_charged")
when "chargeback"
purchases = purchases.where.not(chargeback_date: nil)
.where("purchases.flags & ? = 0", Purchase.flag_mapping["flags"][:chargeback_reversed])
when "refunded"
purchases = purchases.where(stripe_refunded: true)
end
end
end
if creator_email.present?
user = User.find_by(email: creator_email)
return Purchase.none unless user
purchases = purchases.joins(:link).where(links: { user_id: user.id })
end
if license_key.present?
license = License.find_by(serial: license_key)
return Purchase.none unless license
purchases = purchases.where(id: license.purchase_id)
end
if [transaction_date, last_4, card_type, price, expiry_date].any?(&:present?)
purchases = purchases.where.not(stripe_fingerprint: nil)
if transaction_date.present?
formatted_date = parse_date!(transaction_date)
start_date = (formatted_date - 1.days).beginning_of_day.to_fs(:db)
end_date = (formatted_date + 1.days).end_of_day.to_fs(:db)
purchases = purchases.where("created_at between ? and ?", start_date, end_date)
end
purchases = purchases.where(card_type:) if card_type.present?
purchases = purchases.where(card_visual_sql_finder(last_4)) if last_4.present?
purchases = purchases.where("price_cents between ? and ?", (price.to_d * 75).to_i, (price.to_d * 125).to_i) if price.present?
if expiry_date.present?
expiry_month, expiry_year = CreditCardUtility.extract_month_and_year(expiry_date)
purchases = purchases.where(card_expiry_year: "20#{expiry_year}") if expiry_year.present?
purchases = purchases.where(card_expiry_month: expiry_month) if expiry_month.present?
end
end
purchases.limit(limit)
end
private
def parse_date!(transaction_date)
Date.strptime(transaction_date, "%Y-%m-%d").in_time_zone
rescue ArgumentError
raise InvalidDateError, "transaction_date must use YYYY-MM-DD format."
end
def card_visual_sql_finder(last_4)
[
(["card_visual = ?"] * ChargeableVisual::LENGTH_TO_FORMAT.size).join(" OR "),
*ChargeableVisual::LENGTH_TO_FORMAT.values.map { |visual_format| format(visual_format, last_4) }
]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/vat_validation_service.rb | app/services/vat_validation_service.rb | # frozen_string_literal: true
require "valvat"
class VatValidationService
attr_reader :vat_id, :valvat
def initialize(vat_id)
@vat_id = vat_id
@valvat = Valvat.new(vat_id)
end
def process
return false if vat_id.nil?
# If UK, just validate VAT id, no lookup exists for it.
if valvat.vat_country_code.to_s.upcase == "GB"
valvat.valid?
else
# First attempt lookup via the VIES service.
vat_exists = valvat.exists?(requester: GUMROAD_VAT_REGISTRATION_NUMBER) rescue nil
if vat_exists.nil?
# If VIES is down, Valvat#exists? might return nil, fallback to validation instead
# # Note that this fallback creates issue described in https://www.notion.so/gumroad/Handle-subsequent-VAT-validation-leading-to-VAT-id-be-deemed-as-invalid-2a18232e2dea427086682ac2de161676
# Basically the VAT "might not" be valid according to VIES but might pass Valvat checks,
# and subsequently on subscription charges of future be tagged as invalid leading to VAT charge on the purchase.
valvat.valid?
else
vat_exists.present?
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/save_content_upsells_service.rb | app/services/save_content_upsells_service.rb | # frozen_string_literal: true
class SaveContentUpsellsService
def initialize(seller:, content:, old_content:)
@seller = seller
@content = content
@old_content = old_content
end
def from_html
old_doc = Nokogiri::HTML.fragment(old_content)
new_doc = Nokogiri::HTML.fragment(content)
old_upsell_ids = old_doc.css("upsell-card").map { |card| card["id"] }.compact
new_upsell_cards = new_doc.css("upsell-card")
new_upsell_ids = new_upsell_cards.map { |card| card["id"] }.compact
delete_removed_upsells!(old_upsell_ids - new_upsell_ids)
new_upsell_cards.each do |card|
next if card["id"].present?
product_id = ObfuscateIds.decrypt(card["productid"])
variant_id = ObfuscateIds.decrypt(card["variantid"]) if card["variantid"]
discount = JSON.parse(card["discount"]) if card["discount"]
card["id"] = create_upsell!(product_id, variant_id, discount).external_id
end
new_doc.to_html
end
def from_rich_content
old_upsell_ids = old_content&.filter_map { |node| node["type"] == "upsellCard" ? node.dig("attrs", "id") : nil } || []
new_upsell_nodes = content&.select { |node| node["type"] == "upsellCard" } || []
new_upsell_ids = new_upsell_nodes.map { |node| node.dig("attrs", "id") }.compact
delete_removed_upsells!(old_upsell_ids - new_upsell_ids)
new_upsell_nodes.each do |node|
next if node.dig("attrs", "id").present?
product_id = ObfuscateIds.decrypt(node.dig("attrs", "productId"))
variant_id = ObfuscateIds.decrypt(node.dig("attrs", "variantId")) if node.dig("attrs", "variantId")
discount = node.dig("attrs", "discount")
node["attrs"]["id"] = create_upsell!(product_id, variant_id, discount).external_id
end
content
end
private
attr_reader :seller, :content, :old_content, :error
def delete_removed_upsells!(upsell_ids)
upsell_ids.each do |upsell_id|
upsell = seller.upsells.find_by_external_id(upsell_id)
if upsell
upsell.offer_code&.mark_deleted!
upsell.mark_deleted!
end
end
end
def create_upsell!(product_id, variant_id, discount)
Upsell.create!(
seller:,
product_id:,
variant_id:,
is_content_upsell: true,
cross_sell: true,
offer_code: build_offer_code(product_id, discount),
)
end
def build_offer_code(product_id, discount)
return nil unless discount.present?
discount = JSON.parse(discount) if discount.is_a?(String)
OfferCode.build(
user: seller,
code: nil,
amount_cents: discount["type"] == "fixed" ? discount["cents"] : nil,
amount_percentage: discount["type"] == "percent" ? discount["percents"] : nil,
universal: false,
product_ids: [product_id]
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/firs_tin_validation_service.rb | app/services/firs_tin_validation_service.rb | # frozen_string_literal: true
class FirsTinValidationService
attr_reader :tin
def initialize(tin)
@tin = tin
end
def process
return false if tin.blank?
tin.match?(/^\d{8}-\d{4}$/)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/installment_search_service.rb | app/services/installment_search_service.rb | # frozen_string_literal: true
class InstallmentSearchService
DEFAULT_OPTIONS = {
### Filters
# Values can be an ActiveRecord object, an id, or an Array of both
seller: nil,
### Fulltext search
q: nil, # String
### Booleans
exclude_deleted: false,
exclude_workflow_installments: false,
### Enum
type: nil, # values can be 'draft', 'scheduled', and 'published'
### Native ES params
# Most useful defaults to have when using this service in console
from: 0,
size: 5,
sort: nil, # usually: [ { created_at: :desc }, { id: :desc } ],
_source: false,
aggs: {},
track_total_hits: nil,
}
attr_accessor :body
def initialize(options = {})
@options = DEFAULT_OPTIONS.merge(options)
build_body
end
def process
Installment.search(@body)
end
def self.search(options = {})
new(options).process
end
private
def build_body
@body = { query: { bool: { filter: [], must: [], must_not: [] } } }
### Filters
# Objects and ids
build_body_seller
# Booleans
build_body_exclude_workflow_installments
build_body_exclude_deleted
build_body_type
# Others
build_body_slug
### Fulltext search
build_body_fulltext_search
build_body_native_params
end
def build_body_seller
return if @options[:seller].blank?
should = Array.wrap(@options[:seller]).map do |seller|
seller_id = seller.is_a?(User) ? seller.id : seller
{ term: { "seller_id" => seller_id } }
end
@body[:query][:bool][:filter] << { bool: { minimum_should_match: 1, should: } }
end
def build_body_exclude_workflow_installments
return unless @options[:exclude_workflow_installments]
@body[:query][:bool][:must_not] << { exists: { field: "workflow_id" } }
end
def build_body_exclude_deleted
return unless @options[:exclude_deleted]
@body[:query][:bool][:must_not] << { exists: { field: "deleted_at" } }
end
def build_body_type
case @options[:type]
when "published"
@body[:query][:bool][:must] << { exists: { field: "published_at" } }
when "scheduled"
@body[:query][:bool][:must_not] << { exists: { field: "published_at" } }
@body[:query][:bool][:must] << { term: { "selected_flags" => "ready_to_publish" } }
when "draft"
@body[:query][:bool][:must_not] << { exists: { field: "published_at" } }
@body[:query][:bool][:must_not] << { term: { "selected_flags" => "ready_to_publish" } }
end
end
def build_body_slug
return unless @options[:slug]
@body[:query][:bool][:filter] << { term: { "slug" => @options[:slug] } }
end
def build_body_fulltext_search
return if @options[:q].blank?
query_string = @options[:q].strip.downcase
@body[:query][:bool][:must] << {
bool: {
minimum_should_match: 1,
should: [
{
multi_match: {
query: query_string,
fields: %w[name message]
}
}
]
}
}
end
def build_body_native_params
[
:from,
:size,
:sort,
:_source,
:aggs,
:track_total_hits,
].each do |option_name|
next if @options[option_name].nil?
@body[option_name] = @options[option_name]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/safe_redirect_path_service.rb | app/services/safe_redirect_path_service.rb | # frozen_string_literal: true
class SafeRedirectPathService
def initialize(path, request, allow_subdomain_host: true)
@path = path
@allow_subdomain_host = allow_subdomain_host
@request = request
end
def process
if (allow_subdomain_host && subdomain_host?) || same_host?
path
else
relative_path
end
end
private
attr_reader :path, :request, :allow_subdomain_host
def relative_path
_path = url.path.gsub(/^\/+/, "/")
[_path, url.query].compact.join("?")
end
def subdomain_host?
url.host =~ /.*\.#{Regexp.escape(domain)}\z/
end
def same_host?
url.host == request.host
end
def url
@_url ||= URI.parse(Addressable::URI.escape(CGI.unescape(path).split("#").first))
end
def domain
ROOT_DOMAIN
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/google_calendar_api.rb | app/services/google_calendar_api.rb | # frozen_string_literal: true
class GoogleCalendarApi
include HTTParty
GOOGLE_CALENDAR_OAUTH_URL = "https://oauth2.googleapis.com"
base_uri "https://www.googleapis.com/"
def oauth_token(code, redirect_uri)
body = {
grant_type: "authorization_code",
code:,
redirect_uri:,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}
HTTParty.post("#{GOOGLE_CALENDAR_OAUTH_URL}/token", body: URI.encode_www_form(body))
end
def calendar_list(token)
rate_limited_call { self.class.get("/calendar/v3/users/me/calendarList", headers: request_header(token)) }
end
def user_info(token)
rate_limited_call { self.class.get("/oauth2/v2/userinfo", query: { access_token: token }) }
end
def disconnect(token)
HTTParty.post("#{GOOGLE_CALENDAR_OAUTH_URL}/revoke", query: { token: }, headers: { "Content-type" => "application/x-www-form-urlencoded" })
end
def refresh_token(refresh_token)
body = {
grant_type: "refresh_token",
refresh_token:,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}
HTTParty.post("#{GOOGLE_CALENDAR_OAUTH_URL}/token", body: URI.encode_www_form(body))
end
def insert_event(calendar_id, event, access_token:)
headers = request_header(access_token)
rate_limited_call do
self.class.post(
"/calendar/v3/calendars/#{calendar_id}/events",
headers: headers,
body: event.to_json
)
end
end
private
def request_header(token)
{ "Authorization" => "Bearer #{token}" }
end
def rate_limited_call(&block)
key = "GOOGLE_CALENDAR_API_RATE_LIMIT"
ratelimit = Ratelimit.new(key, { redis: $redis })
ratelimit.exec_within_threshold key, threshold: 10000, interval: 60 do
ratelimit.add(key)
block.call
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/default_abandoned_cart_workflow_generator_service.rb | app/services/default_abandoned_cart_workflow_generator_service.rb | # frozen_string_literal: true
class DefaultAbandonedCartWorkflowGeneratorService
include Rails.application.routes.url_helpers
def initialize(seller:)
@seller = seller
end
def generate
return if seller.workflows.abandoned_cart_type.exists?
ActiveRecord::Base.transaction do
workflow = seller.workflows.abandoned_cart_type.create!(name: "Abandoned cart")
installment = workflow.installments.create!(
name: "You left something in your cart",
message: "<p>When you're ready to buy, <a href=\"#{checkout_index_url(host: DOMAIN)}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">complete checking out</a>.</p><#{Installment::PRODUCT_LIST_PLACEHOLDER_TAG_NAME} />",
installment_type: workflow.workflow_type,
json_data: workflow.json_data,
seller_id: workflow.seller_id,
send_emails: true,
)
installment.create_installment_rule!(time_period: InstallmentRule::HOUR, delayed_delivery_time: InstallmentRule::ABANDONED_CART_DELAYED_DELIVERY_TIME_IN_SECONDS)
workflow.publish!
end
end
private
attr_reader :seller
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/seller_mobile_analytics_service.rb | app/services/seller_mobile_analytics_service.rb | # frozen_string_literal: true
class SellerMobileAnalyticsService
SALES_LIMIT = 300
def initialize(user, range: "day", query: nil, fields: [])
@user = user
@range = range
@query = query
@fields = fields
@result = {}
end
def process
@search_result = PurchaseSearchService.search(search_params)
add_revenue_to_result
add_sales_count_to_result
add_purchases_to_result
@result
end
private
def search_params
params = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
seller: @user,
exclude_refunded: false,
exclude_unreversed_chargedback: false,
size: 0,
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
amount_refunded_cents_total: { sum: { field: "amount_refunded_cents" } },
chargedback_agg: {
filter: { term: { not_chargedback_or_chargedback_reversed: false } },
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
}
}
}
)
params[:track_total_hits] = @fields.include?(:sales_count)
if @fields.include?(:purchases)
params[:size] = SALES_LIMIT
params[:sort] = [{ created_at: { order: :desc } }, { id: { order: :desc } }]
params[:seller_query] = @query if @query.present?
end
unless @range == "all"
now = Time.now.in_time_zone(@user.timezone)
raise "Invalid range #{@range}" unless @range.in?(%w[day week month year])
params[:created_on_or_after] = now.public_send("beginning_of_#{@range}")
end
params
end
def add_revenue_to_result
aggregations = @search_result.aggregations
revenue = \
aggregations.price_cents_total.value - \
aggregations.amount_refunded_cents_total.value - \
aggregations.chargedback_agg.price_cents_total.value
@result.merge!(
revenue:,
formatted_revenue: @user.formatted_dollar_amount(revenue),
)
end
def add_sales_count_to_result
@result[:sales_count] = @search_result.results.total if @fields.include?(:sales_count)
end
def add_purchases_to_result
return if @fields.exclude?(:purchases)
purchases_json = @search_result.records.includes(
:seller,
:purchaser,
link: :variant_categories_alive
).as_json(creator_app_api: true)
@result[:purchases] = purchases_json
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/balances_by_product_service.rb | app/services/balances_by_product_service.rb | # frozen_string_literal: true
class BalancesByProductService
def initialize(user)
@user = user
@products = Link.for_balance_page(@user).select(:id, :name, :user_id).order(id: :desc).load
end
def process
return [] if @products.empty?
aggregations = PurchaseSearchService.search(search_options).aggregations
product_buckets = aggregations.product_id_agg.buckets
@products.map do |product|
bucket = product_buckets.find { |product_bucket| product_bucket[:key] == product.id }
next unless bucket # happens if product has no sales
@for_seller = product.user_id == @user.id
balance = {
"link_id" => product.id,
"name" => product.name,
"gross" => 0,
"fees" => 0,
"taxes" => 0,
"net" => 0,
"refunds" => 0,
"chargebacks" => 0,
}
paid_agg = bucket.not_chargedback_agg.not_fully_refunded_agg
balance["gross"] = bucket.dig(agg_key("price_cents_sum"), :value).to_i
chargebacks_fee_returned = bucket.chargedback_agg.dig(agg_key("fee_returned_cents_sum"), :value).to_i
refunds_fee_returned = if @for_seller
bucket.not_chargedback_agg.dig(:fee_refunded_cents_sum, :value).to_i
else
bucket.not_chargedback_agg.dig(:affiliate_fee_refunded_cents_sum, :value).to_i +
bucket.not_chargedback_agg.fully_refunded_agg.dig(:affiliate_fee_refunded_cents_sum, :value).to_i
end
balance["refunds"] = if @for_seller
bucket.not_chargedback_agg.dig(:amount_refunded_cents_sum, :value).to_i
else
# affiliate revenue is already net of fees, so we need to add fees back to get gross refunds
bucket.not_chargedback_agg.dig(:affiliate_amount_refunded_cents_sum, :value).to_i +
bucket.not_chargedback_agg.fully_refunded_agg.dig(:affiliate_amount_refunded_cents_sum, :value).to_i +
refunds_fee_returned
end
balance["chargebacks"] = if @for_seller
bucket.chargedback_agg.dig(:chargedback_cents_sum, :value).to_i
else
# affiliate revenue is already net of fees, so we need to add fees back to get gross chargebacks
bucket.chargedback_agg.dig(:affiliate_chargedback_cents_sum, :value).to_i + chargebacks_fee_returned
end
gross_fees = bucket.dig(agg_key("fee_cents_sum"), :value).to_i
balance["fees"] = gross_fees - chargebacks_fee_returned - refunds_fee_returned
balance["taxes"] = if @for_seller
chargebacks_taxes_returned = bucket.chargedback_agg.dig(:tax_returned_cents_sum, :value).to_i
full_refunds_taxes_returned = bucket.not_chargedback_agg.fully_refunded_agg.dig(:tax_refunded_cents_sum, :value).to_i
partial_refunds_taxes_returned = paid_agg.dig(:tax_refunded_cents_sum, :value).to_i
bucket.dig(:tax_cents_sum, :value).to_i - chargebacks_taxes_returned - full_refunds_taxes_returned - partial_refunds_taxes_returned
else
0
end
balance["gross"] += gross_fees unless @for_seller # affiliate revenue is already net of fees, so we need to add fees back to get gross revenue
balance["net"] = balance["gross"] - balance["refunds"] - balance["chargebacks"] - balance["fees"] - balance["taxes"]
balance
end.compact
end
private
def search_options
{
revenue_sharing_user: @user,
state: "successful",
price_greater_than: 0,
exclude_bundle_product_purchases: true,
size: 0,
aggs: { product_id_agg: }
}
end
def product_id_agg
{
terms: {
field: "product_id",
size: @products.size,
order: { _key: "desc" }
},
aggs: {
price_cents_sum: { sum: { field: "price_cents" } },
fee_cents_sum: { sum: { field: "fee_cents" } },
tax_cents_sum: { sum: { field: "tax_cents" } },
affiliate_price_cents_sum: { sum: { field: "affiliate_credit_amount_cents" } },
affiliate_fee_cents_sum: { sum: { field: "affiliate_credit_fee_cents" } },
chargedback_agg:,
not_chargedback_agg:
}
}
end
def chargedback_agg
{
filter: { term: { not_chargedback_or_chargedback_reversed: false } },
aggs: {
chargedback_cents_sum: { sum: { field: "price_cents" } },
fee_returned_cents_sum: { sum: { field: "fee_cents" } },
tax_returned_cents_sum: { sum: { field: "tax_cents" } },
affiliate_chargedback_cents_sum: { sum: { field: "affiliate_credit_amount_cents" } },
affiliate_fee_returned_cents_sum: { sum: { field: "affiliate_credit_fee_cents" } },
}
}
end
def not_chargedback_agg
{
filter: { term: { not_chargedback_or_chargedback_reversed: true } },
aggs: {
amount_refunded_cents_sum: { sum: { field: "amount_refunded_cents" } },
fee_refunded_cents_sum: { sum: { field: "fee_refunded_cents" } },
affiliate_amount_refunded_cents_sum: { sum: { field: "affiliate_credit_amount_partially_refunded_cents" } },
affiliate_fee_refunded_cents_sum: { sum: { field: "affiliate_credit_fee_partially_refunded_cents" } },
fully_refunded_agg:,
not_fully_refunded_agg:
}
}
end
def fully_refunded_agg
{
filter: { term: { stripe_refunded: true } },
aggs: {
amount_refunded_cents_sum: { sum: { field: "amount_refunded_cents" } },
fee_refunded_cents_sum: { sum: { field: "fee_cents" } },
tax_refunded_cents_sum: { sum: { field: "tax_cents" } },
affiliate_amount_refunded_cents_sum: { sum: { field: "affiliate_credit_amount_cents" } },
affiliate_fee_refunded_cents_sum: { sum: { field: "affiliate_credit_fee_cents" } },
}
}
end
def not_fully_refunded_agg
{
filter: { term: { stripe_refunded: false } },
aggs: {
tax_refunded_cents_sum: { sum: { field: "tax_refunded_cents" } }
}
}
end
def agg_key(key)
:"#{@for_seller ? "" : "affiliate_"}#{key}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/ai/product_details_generator_service.rb | app/services/ai/product_details_generator_service.rb | # frozen_string_literal: true
class Ai::ProductDetailsGeneratorService
class MaxRetriesExceededError < StandardError; end
class InvalidPromptError < StandardError; end
PRODUCT_DETAILS_GENERATION_TIMEOUT_IN_SECONDS = 30
RICH_CONTENT_PAGES_GENERATION_TIMEOUT_IN_SECONDS = 90
COVER_IMAGE_GENERATION_TIMEOUT_IN_SECONDS = 90
SUPPORTED_PRODUCT_NATIVE_TYPES = [
Link::NATIVE_TYPE_DIGITAL,
Link::NATIVE_TYPE_COURSE,
Link::NATIVE_TYPE_EBOOK,
Link::NATIVE_TYPE_MEMBERSHIP
].freeze
MAX_NUMBER_OF_CONTENT_PAGES_TO_GENERATE = 6
DEFAULT_NUMBER_OF_CONTENT_PAGES_TO_GENERATE = 4
MAX_PROMPT_LENGTH = 500
def initialize(current_seller:)
@current_seller = current_seller
end
# @param prompt [String] The user's prompt
# @return [Hash] with the following keys:
# - name: [String] The product name
# - description: [String] The product description as an HTML string
# - summary: [String] The product summary
# - native_type: [String] The product native type
# - number_of_content_pages: [Integer] The number of content pages to generate
# - price: [Float] The product price
# - currency_code: [String] The product price currency code
# - price_frequency_in_months: [Integer] The product price frequency in months (1, 3, 6, 12, 24)
# - duration_in_seconds: [Integer] The duration of the operation in seconds
def generate_product_details(prompt:)
raise InvalidPromptError, "Prompt cannot be blank" if prompt.to_s.strip.blank?
result, duration = with_retries(operation: "Generate product details", context: prompt) do
response = openai_client(PRODUCT_DETAILS_GENERATION_TIMEOUT_IN_SECONDS).chat(
parameters: {
model: "gpt-4o-mini",
messages: [
{
role: "system",
content: %Q{
You are an expert digital product creator. Generate detailed product information based on the user's prompt.
IMPORTANT: Carefully extract price and currency information from the user's prompt:
- Look for explicit prices like "for 2 yen", "$10", "€15", "£20", etc.
- Always use the exact numerical value from the prompt without currency conversion
- Common currency mappings: "yen" = "jpy", "dollar"/"$" = "usd", "euro"/"€" = "eur", "pound"/"£" = "gbp"
- Allowed currency codes: #{CURRENCY_CHOICES.keys.join(", ")}
- If no price is specified, use your best guess based on the product type
- If no currency is specified, use the seller's default currency: #{current_seller.currency_type}
Return the following JSON format **only**:
{
"name": "Product name as a string",
"number_of_content_pages": 2, // Number of chapters or pages to generate based on the user's prompt. If specified more than #{MAX_NUMBER_OF_CONTENT_PAGES_TO_GENERATE} pages/chapters, generate only #{MAX_NUMBER_OF_CONTENT_PAGES_TO_GENERATE} pages/chapters. If no number is specified, generate #{DEFAULT_NUMBER_OF_CONTENT_PAGES_TO_GENERATE} pages/chapters
"description": "Product description as a safe HTML string with only <p>, <ul>, <ol>, <li>, <h2>, <h3>, <h4>, <strong>, and <em> tags; feel free to add emojis. Don't mention the number of pages or chapters in the description.",
"summary": "Short summary of the product",
"native_type": "Must be one of: #{SUPPORTED_PRODUCT_NATIVE_TYPES.join(", ")}",
"price": 4.99, // Extract the exact price from the prompt if specified, otherwise use your best guess
"currency_code": "usd", // Extract currency from prompt if specified, otherwise use seller default (#{current_seller.currency_type})
"price_frequency_in_months": 1 // Only include if native_type is 'membership' (1, 3, 6, 12, 24)
}
}.split("\n").map(&:strip).join("\n")
},
{
role: "user",
content: prompt.truncate(MAX_PROMPT_LENGTH, omission: "...")
}
],
response_format: { type: "json_object" },
temperature: 0.5
}
)
content = response.dig("choices", 0, "message", "content")
raise "Failed to generate product details - no content returned" if content.blank?
JSON.parse(content, symbolize_names: true)
end
result.merge(duration_in_seconds: duration)
end
# @param product_name [String] The product name
# @return [Hash] with the following keys:
# - image_data: [String] The base64 decoded image data
# - duration_in_seconds: [Integer] The duration of the operation in seconds
def generate_cover_image(product_name:)
image_data, duration = with_retries(operation: "Generate cover image", context: product_name) do
image_prompt = "Professional, fully covered, high-quality digital product cover image with a modern, clean design and elegant typography. The cover features the product name, '#{product_name}', centered and fully visible, with proper text wrapping, balanced spacing, and padding. Design is optimized to ensure no text is cropped or cut off. Avoid any clipping or cropping of text, and maintain a margin around all edges. Include subtle gradients, minimalist icons, and a harmonious color palette suited for a digital marketplace. The style is sleek, professional, and visually balanced within a square 1024x1024 canvas."
response = openai_client(COVER_IMAGE_GENERATION_TIMEOUT_IN_SECONDS).images.generate(
parameters: {
prompt: image_prompt,
model: "gpt-image-1",
size: "1024x1024",
quality: "medium",
output_format: "jpeg"
}
)
b64_json = response.dig("data", 0, "b64_json")
raise "Failed to generate cover image - no image data returned" if b64_json.blank?
Base64.decode64(b64_json)
end
{
image_data:,
duration_in_seconds: duration
}
end
# @param product_info [Hash] The product info
# - name: [String] The product name
# - description: [String] The product description as an HTML string
# - native_type: [String] The product native type
# - number_of_content_pages: [Integer] The number of content pages to generate
# @return [Hash] with the following keys:
# - pages: [Array<Hash>] The rich content pages
# - duration_in_seconds: [Integer] The duration of the operation in seconds
def generate_rich_content_pages(product_info)
number_of_content_pages = product_info[:number_of_content_pages] || DEFAULT_NUMBER_OF_CONTENT_PAGES_TO_GENERATE
pages, duration = with_retries(operation: "Generate rich content pages", context: product_info[:name]) do
response = openai_client(RICH_CONTENT_PAGES_GENERATION_TIMEOUT_IN_SECONDS).chat(
parameters: {
model: "gpt-4o-mini",
messages: [
{
role: "system",
content: %Q{
You are creating rich content pages for a digital product.
Generate exactly #{number_of_content_pages} pages in valid Tiptap JSON format, each page having a title and content array with at least 5-6 meaningful and contextually relevant paragraphs, headings, and lists. Try to match the page titles from the titles of pages/chapters in the description of the product if any.
CRITICAL: Generate ONLY valid JSON. Always use exactly "type" as the key name, never "type: " or any variation. Ensure all JSON syntax is correct.
Return a JSON object with pages array. Example output format:
{
"pages": [
{ "title": "Page 1",
"content": [
{ "type": "heading", "attrs": { "level": 2 }, "content": [ { "type": "text", "text": "Heading" } ] },
{ "type": "paragraph", "content": [ { "type": "text", "text": "Paragraph 1" } ] },
{ "type": "orderedList", "content": [ { "type": "listItem", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "List item" } ] } ] } ] },
{ "type": "bulletList", "content": [ { "type": "listItem", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "List item" } ] } ] } ] },
{ "type": "codeBlock", "content": [ { "type": "text", "text": "class Dog\n def bark\n puts 'Woof!'\n end\nend" } ] }
]
}
]
}
}.split("\n").map(&:strip).join("\n")
},
{
role: "user",
content: %Q{
Create detailed content pages for #{product_info[:native_type]} product:
Product name: "#{product_info[:name]}".
Number of content pages: #{number_of_content_pages}.
Product description: "#{product_info[:description]}".
}
}
],
response_format: { type: "json_object" },
temperature: 0.5
}
)
content = response.dig("choices", 0, "message", "content")
raise "Failed to generate rich content pages - no content returned" if content.blank?
# Clean up any malformed JSON keys (e.g., "type: " instead of "type")
cleaned_content = content.gsub(/"type:\s*"/, '"type"')
JSON.parse(cleaned_content)
end
{
pages: pages["pages"],
duration_in_seconds: duration
}
end
private
attr_reader :current_seller
def openai_client(timeout_in_seconds)
OpenAI::Client.new(request_timeout: timeout_in_seconds)
end
def with_retries(operation:, context: nil, max_tries: 2, delay: 1)
tries = 0
start_time = Time.now
begin
tries += 1
result = yield
duration = Time.now - start_time
Rails.logger.info("Successfully completed '#{operation}' in #{duration.round(2)}s")
[result, duration]
rescue => e
duration = Time.now - start_time
if tries < max_tries
Rails.logger.info("Failed to perform '#{operation}', attempt #{tries}/#{max_tries}: #{context}: #{e.message}")
sleep(delay)
retry
else
Rails.logger.error("Failed to perform '#{operation}' after #{max_tries} attempts in #{duration.round(2)}s: #{context}: #{e.message}")
raise MaxRetriesExceededError, "Failed to perform '#{operation}' after #{max_tries} attempts: #{e.message}"
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/push_notification_service/ios.rb | app/services/push_notification_service/ios.rb | # frozen_string_literal: true
module PushNotificationService
class Ios
attr_reader :device_token, :title, :body, :data
def initialize(device_token:, title:, body:, data: {}, app_type:, sound: nil)
@device_token = device_token
@title = title
@body = body
@data = data
@app_type = app_type
@sound = sound
end
def process
send_notification
end
def self.creator_app
@_creator_app ||= RpushApnsAppService.new(name: Device::APP_TYPES[:creator]).first_or_create!
end
def self.consumer_app
@_consumer_app ||= RpushApnsAppService.new(name: Device::APP_TYPES[:consumer]).first_or_create!
end
private
def send_notification
init_args = { app:,
device_token:,
alert:,
data: data_with_headers }
init_args[:sound] = @sound if @sound.present?
notification = Rpush::Apns2::Notification.new(init_args)
notification.save!
end
def alert
if body.present?
{
"title" => title,
"body" => body
}
else
title
end
end
def creator_app?
@app_type == Device::APP_TYPES[:creator]
end
def app
creator_app? ? self.class.creator_app : self.class.consumer_app
end
def bundle_id
creator_app? ? "com.GRD.iOSCreator" : "com.GRD.Gumroad"
end
def data_with_headers
data.merge({ headers: { 'apns-topic': bundle_id } })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/push_notification_service/android.rb | app/services/push_notification_service/android.rb | # frozen_string_literal: true
module PushNotificationService
class Android
attr_reader :device_token, :title, :body, :data
def initialize(device_token:, title:, body:, data: {}, app_type:, sound: nil)
@device_token = device_token
@title = title
@body = body
@data = data
@app_type = app_type
@sound = sound
end
def process
return if Feature.inactive?(:send_notifications_to_android_devices)
return if creator_app?
send_notification
end
private
def self.consumer_app
@_consumer_app ||= RpushFcmAppService.new(name: Device::APP_TYPES[:consumer]).first_or_create!
end
def send_notification
notification_args = { title:, body:, icon: "notification_icon" }.compact
notification = Rpush::Fcm::Notification.new
notification.app = app
notification.alert = title
notification.device_token = device_token
notification.content_available = true
if @sound.present?
notification.sound = @sound
notification_args[:channel_id] = "Purchases"
end
notification.notification = notification_args
if consumer_app?
notification.data = data.merge(message: title)
end
notification.save!
end
def creator_app?
@app_type == Device::APP_TYPES[:creator]
end
def consumer_app?
@app_type == Device::APP_TYPES[:consumer]
end
def app
self.class.consumer_app
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/handle_email_event_info/for_receipt_email.rb | app/services/handle_email_event_info/for_receipt_email.rb | # frozen_string_literal: true
class HandleEmailEventInfo::ForReceiptEmail
attr_reader :email_event_info
def self.perform(email_event_info)
new(email_event_info).perform
end
def initialize(email_event_info)
@email_event_info = email_event_info
end
def perform
email_info = find_or_initialize_customer_email_info(email_event_info)
case email_event_info.type
when EmailEventInfo::EVENT_BOUNCED
email_info.mark_bounced!
when EmailEventInfo::EVENT_DELIVERED
email_info.mark_delivered!(email_event_info.created_at)
when EmailEventInfo::EVENT_OPENED
email_info.mark_opened!(email_event_info.created_at)
when EmailEventInfo::EVENT_COMPLAINED
unless email_event_info.email_provider == MailerInfo::EMAIL_PROVIDER_RESEND
Purchase.find_by(id: email_event_info.purchase_id)&.unsubscribe_buyer
end
end
end
private
# We create these records when sending emails so we shouldn't really need to create them again here.
# However, this code needs to stay so as to support events which are triggered on emails which were sent before
# the code to create these records was in place. From our investigation, we saw that we still receive events
# for ancient purchases.
def find_or_initialize_customer_email_info(email_event_info)
if email_event_info.charge_id.present?
CustomerEmailInfo.find_or_initialize_for_charge(
charge_id: email_event_info.charge_id,
email_name: email_event_info.mailer_method
)
else
CustomerEmailInfo.find_or_initialize_for_purchase(
purchase_id: email_event_info.purchase_id,
email_name: email_event_info.mailer_method
)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/handle_email_event_info/for_installment_email.rb | app/services/handle_email_event_info/for_installment_email.rb | # frozen_string_literal: true
class HandleEmailEventInfo::ForInstallmentEmail
attr_reader :email_event_info
def self.perform(email_event_info)
new(email_event_info).perform
end
def initialize(email_event_info)
@email_event_info = email_event_info
end
def perform
case email_event_info.type
when EmailEventInfo::EVENT_BOUNCED
handle_bounce_event!
when EmailEventInfo::EVENT_DELIVERED
handle_delivered_event!
when EmailEventInfo::EVENT_OPENED
handle_open_event!
when EmailEventInfo::EVENT_CLICKED
handle_click_event!
when EmailEventInfo::EVENT_COMPLAINED
unless email_event_info.email_provider == MailerInfo::EMAIL_PROVIDER_RESEND
handle_spamreport_event!
end
end
end
private
def handle_bounce_event!
email_info = pull_creator_contacting_customers_email_info(email_event_info)
if email_info.present?
email_info.mark_bounced!
else
# Unsubscribe the follower
seller_id = Installment.find(email_event_info.installment_id).seller_id
Follower.unsubscribe(seller_id, email_event_info.email)
end
end
def handle_delivered_event!
email_info = pull_creator_contacting_customers_email_info(email_event_info)
email_info.mark_delivered!(email_event_info.created_at) if email_info.present?
end
def handle_open_event!
open_event = CreatorEmailOpenEvent.where(
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
installment_id: email_event_info.installment_id
).last
if open_event.present?
open_event.add_to_set(open_timestamps: Time.current)
open_event.inc(open_count: 1)
else
CreatorEmailOpenEvent.create!(
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
installment_id: email_event_info.installment_id,
open_timestamps: [Time.current],
open_count: 1
)
end
email_info = pull_creator_contacting_customers_email_info(email_event_info)
email_info.mark_opened!(email_event_info.created_at) if email_info.present?
update_installment_cache(email_event_info.installment_id, :unique_open_count)
end
def handle_click_event!
return if email_event_info.click_url_as_mongo_key.blank?
summary = CreatorEmailClickSummary.where(installment_id: email_event_info.installment_id).last
if summary.present?
email_click_event_args = {
installment_id: email_event_info.installment_id,
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
}
email_click_event_cache_key = Digest::MD5.hexdigest(email_click_event_args.inspect)
email_click_event_present = Rails.cache.fetch("#{email_event_info.email_provider}_#{email_click_event_cache_key}") do
# Return nil if `present?` returns false. That way, the query will be run again next time.
CreatorEmailClickEvent.where(email_click_event_args).last.present? || nil
end
if email_click_event_present
url_click_event_args = {
installment_id: email_event_info.installment_id,
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
click_url: email_event_info.click_url_as_mongo_key
}
url_click_event_cache_key = Digest::MD5.hexdigest(url_click_event_args.inspect)
url_click_event_present = Rails.cache.fetch("#{email_event_info.email_provider}_#{url_click_event_cache_key}") do
# Return nil if `present?` returns false. That way, the query will be run again next time.
CreatorEmailClickEvent.where(url_click_event_args).last.present? || nil
end
return if url_click_event_present
else
summary.inc(total_unique_clicks: 1)
end
summary.inc("urls.#{email_event_info.click_url_as_mongo_key}" => 1)
else
CreatorEmailClickSummary.create!(
installment_id: email_event_info.installment_id,
total_unique_clicks: 1,
urls: { email_event_info.click_url_as_mongo_key => 1 }
)
end
CreatorEmailClickEvent.create(
installment_id: email_event_info.installment_id,
mailer_args: email_event_info.mailer_args,
mailer_method: email_event_info.mailer_class_and_method,
click_url: email_event_info.click_url_as_mongo_key,
click_timestamps: [Time.current],
click_count: 1
)
update_installment_cache(email_event_info.installment_id, :unique_click_count)
# If a corresponding open event does not exist, create a new open event. This compensates for blocked image tracking pixels.
unless creator_email_open_event_exists?(email_event_info)
CreatorEmailOpenEvent.create!(
installment_id: email_event_info.installment_id,
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
open_timestamps: [Time.current],
open_count: 1
)
update_installment_cache(email_event_info.installment_id, :unique_open_count)
end
end
def handle_spamreport_event!
purchase = Purchase.find_by(id: email_event_info.purchase_id)
if purchase.present?
purchase.unsubscribe_buyer
else
# Unsubscribe the follower
seller_id = Installment.find(email_event_info.installment_id).seller_id
Follower.unsubscribe(seller_id, email_event_info.email)
end
end
def pull_creator_contacting_customers_email_info(email_event_info)
purchase_id = email_event_info.purchase_id
installment_id = email_event_info.installment_id
email_name = nil
if email_event_info.mailer_class_and_method.end_with?(EmailEventInfo::PURCHASE_INSTALLMENT_MAILER_METHOD)
email_name = EmailEventInfo::PURCHASE_INSTALLMENT_MAILER_METHOD
email_info = CreatorContactingCustomersEmailInfo.where(purchase_id:, installment_id:).last
elsif email_event_info.mailer_class_and_method.end_with?(EmailEventInfo::SUBSCRIPTION_INSTALLMENT_MAILER_METHOD)
email_name = EmailEventInfo::SUBSCRIPTION_INSTALLMENT_MAILER_METHOD
purchase_id = Subscription.find(email_event_info.purchase_id).original_purchase.id
email_info = CreatorContactingCustomersEmailInfo.where(purchase_id:, installment_id:).last
else
return nil
end
# We create these records when sending emails so we shouldn't really need to create them again here.
# However, this code needs to stay so as to support events which are triggered on emails which were sent before
# the code to create these records was in place. From our investigation, we saw that we still receive events
# for ancient purchases.
email_info || CreatorContactingCustomersEmailInfo.new(purchase_id:, installment_id:, email_name:)
end
def update_installment_cache(installment_id, key)
installment = Installment.find(installment_id)
# Clear cache and precompute the result
installment.invalidate_cache(key)
installment.send(key)
end
def creator_email_open_event_exists?(email_event_info)
CreatorEmailOpenEvent.where(
installment_id: email_event_info.installment_id,
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
).exists?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/handle_email_event_info/for_abandoned_cart_email.rb | app/services/handle_email_event_info/for_abandoned_cart_email.rb | # frozen_string_literal: true
class HandleEmailEventInfo::ForAbandonedCartEmail
attr_reader :email_event_info
def self.perform(email_event_info)
new(email_event_info).perform
end
def initialize(email_event_info)
@email_event_info = email_event_info
end
def perform
email_event_info.workflow_ids.each do |workflow_id|
workflow = Workflow.find(workflow_id)
installment = workflow.alive_installments.sole
case email_event_info.type
when EmailEventInfo::EVENT_DELIVERED
handle_delivered_event!(installment)
when EmailEventInfo::EVENT_OPENED
handle_open_event!(installment)
when EmailEventInfo::EVENT_CLICKED
handle_click_event!(installment)
end
end
end
private
def handle_delivered_event!(installment)
installment.increment_total_delivered(by: 1)
end
def handle_open_event!(installment)
open_event = CreatorEmailOpenEvent.where(common_event_attributes(installment)).last
if open_event.present?
open_event.add_to_set(open_timestamps: Time.current)
open_event.inc(open_count: 1)
else
CreatorEmailOpenEvent.create!(common_event_attributes(installment).merge(open_timestamps: [Time.current], open_count: 1))
end
update_installment_cache(installment, :unique_open_count)
end
def handle_click_event!(installment)
return if email_event_info.click_url_as_mongo_key.blank?
summary = CreatorEmailClickSummary.where(installment_id: installment.id).last
if summary.present?
email_click_event_args = common_event_attributes(installment)
email_click_event_cache_key = Digest::MD5.hexdigest(email_click_event_args.inspect)
email_click_event_present = Rails.cache.fetch("sendgrid_#{email_click_event_cache_key}") do
# Return nil if `present?` returns false. That way, the query will be run again next time.
CreatorEmailClickEvent.where(email_click_event_args).last.present? || nil
end
if email_click_event_present
url_click_event_args = common_event_attributes(installment).merge(click_url: email_event_info.click_url_as_mongo_key)
url_click_event_cache_key = Digest::MD5.hexdigest(url_click_event_args.inspect)
url_click_event_present = Rails.cache.fetch("sendgrid_#{url_click_event_cache_key}") do
# Return nil if `present?` returns false. That way, the query will be run again next time.
CreatorEmailClickEvent.where(url_click_event_args).last.present? || nil
end
return if url_click_event_present
else
summary.inc(total_unique_clicks: 1)
end
summary.inc("urls.#{email_event_info.click_url_as_mongo_key}" => 1)
else
CreatorEmailClickSummary.create!(
installment_id: installment.id,
total_unique_clicks: 1,
urls: { email_event_info.click_url_as_mongo_key => 1 }
)
end
CreatorEmailClickEvent.create(
common_event_attributes(installment).merge(
click_url: email_event_info.click_url_as_mongo_key,
click_timestamps: [Time.current],
click_count: 1
)
)
update_installment_cache(installment, :unique_click_count)
# If a corresponding open event does not exist, create a new open event. This compensates for blocked image tracking pixels.
unless CreatorEmailOpenEvent.where(common_event_attributes(installment)).exists?
CreatorEmailOpenEvent.create!(common_event_attributes(installment).merge(open_timestamps: [Time.current], open_count: 1))
update_installment_cache(installment, :unique_open_count)
end
end
def update_installment_cache(installment, key)
# Clear cache and precompute the result
installment.invalidate_cache(key)
installment.send(key)
end
def common_event_attributes(installment)
{
installment_id: installment.id,
mailer_method: email_event_info.mailer_class_and_method,
mailer_args: email_event_info.mailer_args,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/integrations/base_integration_service.rb | app/services/integrations/base_integration_service.rb | # frozen_string_literal: true
class Integrations::BaseIntegrationService
include ActiveModel::Validations
attr_accessor :integration_name
validates :integration_name, presence: true
def initialize
raise "#{self.class.name} should not be instantiated. Instantiate child classes instead."
end
def activate(purchase)
integration = purchase.find_enabled_integration(integration_name)
return unless integration
yield integration if block_given?
end
def deactivate(purchase)
integration = purchase.find_enabled_integration(integration_name)
return if integration.blank? || integration.keep_inactive_members?
yield integration if block_given?
end
# For now since all tiers have the same integration, the logic is simple.
# In case we allow different integrations for different tiers we will have a
# lot of edge cases to check when we update a tier.
def update_on_tier_change(subscription)
previous_purchase = subscription.purchases.is_original_subscription_purchase.order(:id)[-2]
return unless previous_purchase.present?
old_integration = previous_purchase.find_enabled_integration(integration_name)
new_integration = subscription.original_purchase.find_enabled_integration(integration_name)
activate(subscription.original_purchase) if new_integration.present? && old_integration.blank?
deactivate(previous_purchase) if new_integration.blank? && old_integration.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/integrations/circle_integration_service.rb | app/services/integrations/circle_integration_service.rb | # frozen_string_literal: true
class Integrations::CircleIntegrationService < Integrations::BaseIntegrationService
def initialize
@integration_name = Integration::CIRCLE
end
def activate(purchase)
super { |integration| CircleApi.new(integration.api_key).add_member(integration.community_id, integration.space_group_id, purchase.email) }
end
def deactivate(purchase)
super { |integration| CircleApi.new(integration.api_key).remove_member(integration.community_id, purchase.email) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/integrations/discord_integration_service.rb | app/services/integrations/discord_integration_service.rb | # frozen_string_literal: true
class Integrations::DiscordIntegrationService < Integrations::BaseIntegrationService
def initialize
@integration_name = Integration::DISCORD
end
def deactivate(purchase)
super do |integration|
discord_user_id = DiscordIntegration.discord_user_id_for(purchase)
if discord_user_id.present?
begin
DiscordApi.new.remove_member(integration.server_id, discord_user_id)
purchase.live_purchase_integrations.find_by(integration:).mark_deleted!
rescue Discordrb::Errors::NoPermission
if gumroad_role_higher_than_member_role?(integration.server_id, discord_user_id)
Bugsnag.notify("Received a Discord permissions error for something other than role position - purchase id #{purchase.id} - server id #{integration.server_id} - discord user id #{discord_user_id}")
raise
else
ContactingCreatorMailer.unremovable_discord_member(discord_user_id, integration.server_name, purchase.id).deliver_later(queue: "critical")
end
rescue Discordrb::Errors::UnknownServer => e
Rails.logger.info("DiscordIntegrationService: Purchase id #{purchase.id} is being deactivated for a deleted Discord server. Discord server id #{integration.server_id} and Discord user id #{discord_user_id}. Proceeding to mark the PurchaseIntegration as deleted. Error: #{e.class} => #{e.message}")
purchase.live_purchase_integrations.find_by(integration:).mark_deleted!
end
end
end
end
private
def gumroad_role_higher_than_member_role?(discord_server_id, discord_user_id)
member_role_ids = resolve_member_roles(discord_server_id, discord_user_id)
return true if member_role_ids.blank?
gumroad_role_ids = resolve_member_roles(discord_server_id, DISCORD_GUMROAD_BOT_ID)
roles_response = DiscordApi.new.roles(discord_server_id)
server_roles = JSON.parse(roles_response.body).sort_by { -_1["position"] }
member_roles = server_roles.filter { member_role_ids.include?(_1["id"]) }
gumroad_roles = server_roles.filter { gumroad_role_ids.include?(_1["id"]) }
highest_member_role_position = member_roles.first&.dig("position") || -1
highest_gumroad_role_position = gumroad_roles.first&.dig("position") || -1
highest_gumroad_role_position > highest_member_role_position
end
def resolve_member_roles(discord_server_id, discord_user_id)
resolve_member_response = DiscordApi.new.resolve_member(discord_server_id, discord_user_id)
member = JSON.parse(resolve_member_response.body)
member["roles"].uniq
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/audience_export_service.rb | app/services/exports/audience_export_service.rb | # frozen_string_literal: true
require "csv"
class Exports::AudienceExportService
FIELDS = ["Subscriber Email", "Subscribed Time"].freeze
def initialize(user, options = {})
@user = user
@options = options.with_indifferent_access
timestamp = Time.current.to_fs(:db).gsub(/ |:/, "-")
@filename = "Subscribers-#{@user.username}_#{timestamp}.csv"
validate_options!
end
attr_reader :filename, :tempfile
def perform
@tempfile = Tempfile.new(["Subscribers", ".csv"], encoding: "UTF-8")
CSV.open(@tempfile, "wb", headers: FIELDS, write_headers: true) do |csv|
query = @user.audience_members.select(:id, :email, :min_created_at)
conditions = []
conditions << "follower = true" if @options[:followers]
conditions << "customer = true" if @options[:customers]
conditions << "affiliate = true" if @options[:affiliates]
query = query.where(conditions.join(" OR "))
query.order(:min_created_at).find_each do |member|
csv << [member.email, member.min_created_at]
end
end
@tempfile.rewind
self
end
private
def validate_options!
unless @options[:followers] || @options[:customers] || @options[:affiliates]
raise ArgumentError, "At least one audience type (followers, customers, or affiliates) must be selected"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/purchase_export_service.rb | app/services/exports/purchase_export_service.rb | # frozen_string_literal: true
class Exports::PurchaseExportService
PURCHASE_FIELDS = [
"Purchase ID", "Item Name", "Buyer Name", "Purchase Email", "Buyer Email", "Do not contact?",
"Purchase Date", "Purchase Time (UTC timezone)", "Subtotal ($)", "Taxes ($)", "Tax Type", "Shipping ($)",
"Sale Price ($)", "Fees ($)", "Net Total ($)", "Tip ($)", "Tax Included in Price?",
"Street Address", "City", "Zip Code", "State", "Country", "Referrer", "Refunded?",
"Partial Refund ($)", "Fully Refunded?", "Disputed?", "Dispute Won?", "Access Revoked?", "Variants",
"Discount Code", "Recurring Charge?", "Free trial purchase?", "Pre-order authorization?", "Product ID", "Order Number",
"Pre-order authorization time (UTC timezone)", "Custom Fields", "Item Price ($)",
"Variants Price ($)", "Giftee Email", "SKU ID", "Quantity", "Recurrence",
"Affiliate", "Affiliate commission ($)", "Discover?", "Subscription End Date", "Rating", "Review",
"License Key", "License Key Activation Count", "License Key Enabled?", "Payment Type", "PayPal Transaction ID", "PayPal Fee Amount", "PayPal Fee Currency",
"Stripe Transaction ID", "Stripe Fee Amount", "Stripe Fee Currency",
"Purchasing Power Parity Discounted?", "Upsold?", "Sent Abandoned Cart Email?",
"UTM Source", "UTM Medium", "UTM Campaign", "UTM Term", "UTM Content"
].freeze
TOTALS_COLUMN_NAME = "Totals"
TOTALS_FIELDS = [
"Subtotal ($)", "Taxes ($)", "Shipping ($)", "Sale Price ($)", "Fees ($)", "Net Total ($)",
"Tip ($)", "Partial Refund ($)", "Variants Price ($)", "Item Price ($)", "Affiliate commission ($)",
"PayPal Fee Amount", "Stripe Fee Amount"
].freeze
SYNCHRONOUS_EXPORT_THRESHOLD = 2_000
def initialize(purchases)
@purchases = purchases
end
def custom_fields
@_custom_fields ||= @purchases.includes(:purchase_custom_fields, link: :custom_fields).find_each.flat_map do |purchase|
[
purchase.custom_fields.pluck(:name),
purchase.link.custom_fields.map { |product_custom_field| product_custom_field["name"] }
].flatten
end.uniq
end
def purchases_data
gift_includes = {
giftee_purchase: [
:link, :product_review, :license,
subscription: { true_original_purchase: :product_review, original_purchase: :license }
]
}
purchases_with_includes = @purchases.includes(
:link, :variant_attributes, :license, :purchaser, :offer_code, :product_review, :purchase_custom_fields, :upsell_purchase, :merchant_account,
subscription: [{ true_original_purchase: :product_review }],
order: { cart: { sent_abandoned_cart_emails: :installment } },
gift_received: gift_includes,
gift_given: gift_includes,
utm_link: [target_resource: [:seller, :user]],
)
purchases_with_includes.find_each.map do |purchase|
purchase_data(purchase)
end
end
def perform
self.class.compile(custom_fields, purchases_data)
end
def self.compile(custom_fields, purchases_data_enumerator)
fields = PURCHASE_FIELDS + custom_fields
tempfile = Tempfile.new(["Sales", ".csv"], "tmp", encoding: "UTF-8")
totals = Hash.new(0)
CSV.open(tempfile, "wb") do |csv|
csv << fields
purchases_data_enumerator.each do |(purchase_fields_data, custom_fields_data)|
row = Array.new(fields.size)
purchase_fields_data.each do |column_name, value|
row[fields.index(column_name)] = value
totals[column_name] += value.to_f if TOTALS_FIELDS.include?(column_name)
end
custom_fields_data.each do |column_name, value|
row[fields.rindex(column_name)] = value
end
csv << row
end
totals_row = Array.new(fields.size)
totals_row[0] = TOTALS_COLUMN_NAME
totals.each do |column_name, value|
totals_row[fields.index(column_name)] = value.round(2)
end
csv << totals_row
end
tempfile
end
def self.export(seller:, recipient:, filters: {})
product_ids = Link.by_external_ids(filters[:product_ids]).ids if filters[:product_ids].present?
variant_ids = BaseVariant.by_external_ids(filters[:variant_ids]).ids if filters[:variant_ids].present?
start_time = Date.parse(filters[:start_time]).in_time_zone(seller.timezone).beginning_of_day if filters[:start_time].present?
end_time = Date.parse(filters[:end_time]).in_time_zone(seller.timezone).end_of_day if filters[:end_time].present?
search_service = PurchaseSearchService.new(
seller:,
state: Purchase::NON_GIFT_SUCCESS_STATES,
exclude_not_charged_non_free_trial_purchases: true,
exclude_bundle_product_purchases: true,
any_products_or_variants: { products: product_ids, variants: variant_ids },
created_on_or_after: start_time,
created_before: end_time,
size: SYNCHRONOUS_EXPORT_THRESHOLD
)
count = EsClient.count(index: Purchase.index_name, body: { query: search_service.query })["count"]
if count <= SYNCHRONOUS_EXPORT_THRESHOLD
records = Purchase.where(id: search_service.process.results.map(&:id))
Exports::PurchaseExportService.new(records).perform
else
export = SalesExport.create!(recipient:, query: search_service.query.deep_stringify_keys)
Exports::Sales::CreateAndEnqueueChunksWorker.perform_async(export.id)
false
end
end
private
def purchase_data(purchase)
variants_price_dollars = purchase.variant_extra_cost_dollars
main_or_giftee_purchase = (purchase.is_gift_sender_purchase? ? purchase.gift_given.giftee_purchase : purchase)
custom_fields_data = purchase.custom_fields.pluck(:name, :value).to_h
utm_link = purchase.utm_link
data = {
"Purchase ID" => purchase.external_id,
"Item Name" => purchase.link.name,
"Buyer Name" => purchase.full_name.presence || purchase.purchaser&.name,
"Purchase Email" => purchase.email,
"Buyer Email" => purchase.purchaser.try(:email),
"Do not contact?" => purchase.can_contact? ? 0 : 1,
"Purchase Date" => purchase.created_at.to_date.to_s,
"Purchase Time (UTC timezone)" => purchase.created_at.to_time.to_s,
"Subtotal ($)" => purchase.sub_total,
"Taxes ($)" => purchase.tax_dollars,
"Tax Type" => purchase.has_tax_label? ? purchase.tax_label(include_tax_rate: false) : "",
"Shipping ($)" => purchase.shipping_dollars,
"Sale Price ($)" => purchase.price_dollars,
"Fees ($)" => purchase.fee_dollars,
"Tip ($)" => (purchase.tip&.value_usd_cents || 0) / 100.0,
"Net Total ($)" => purchase.net_total,
"Tax Included in Price?" => determine_exclusive_tax_report_field(purchase),
"Street Address" => pseudo_transliterate(purchase.street_address),
"City" => pseudo_transliterate(purchase.city),
"Zip Code" => purchase.zip_code && purchase.zip_code.to_s.rjust(5, "0"),
"State" => pseudo_transliterate(purchase.state_or_from_ip_address),
"Country" => pseudo_transliterate(purchase.country_or_from_ip_address),
"Referrer" => purchase.referrer,
"Refunded?" => (purchase.stripe_refunded || purchase.stripe_partially_refunded) ? 1 : 0,
"Partial Refund ($)" => purchase.stripe_partially_refunded ? purchase.amount_refunded_dollars : 0.0,
"Fully Refunded?" => purchase.stripe_refunded ? 1 : 0,
"Disputed?" => purchase.chargeback_date ? 1 : 0,
"Dispute Won?" => purchase.chargeback_reversed? ? 1 : 0,
"Access Revoked?" => purchase.is_access_revoked ? 1 : 0,
"Variants" => purchase.variants_list,
"Discount Code" => purchase.offer_code&.code,
"Recurring Charge?" => purchase.is_recurring_subscription_charge ? 1 : 0,
"Free trial purchase?" => purchase.is_free_trial_purchase? ? 1 : 0,
"Pre-order authorization?" => purchase.is_preorder_authorization? ? 1 : 0,
"Product ID" => purchase.link.unique_permalink,
"Order Number" => purchase.external_id_numeric,
"Pre-order authorization time (UTC timezone)" => (purchase.preorder.created_at.to_time.to_s if purchase.is_preorder_charge?),
"Custom Fields" => custom_fields_data.to_s,
"Item Price ($)" => purchase.price_dollars - variants_price_dollars,
"Variants Price ($)" => variants_price_dollars,
"Giftee Email" => purchase.giftee_email.presence,
"SKU ID" => purchase.sku&.custom_name_or_external_id,
"Quantity" => purchase.quantity,
"Recurrence" => purchase.subscription&.price&.recurrence,
"Affiliate" => purchase.affiliate&.affiliate_user&.form_email,
"Affiliate commission ($)" => (purchase.affiliate_credit_dollars if purchase.affiliate_credit_cents.present?),
"Discover?" => purchase.was_product_recommended? ? 1 : 0,
"Subscription End Date" => purchase.subscription&.termination_date&.to_s,
"Rating" => main_or_giftee_purchase&.original_product_review&.rating,
"Review" => main_or_giftee_purchase&.original_product_review&.message,
"License Key" => main_or_giftee_purchase&.license_key,
"License Key Activation Count" => main_or_giftee_purchase&.license&.uses,
"License Key Enabled?" => main_or_giftee_purchase&.license&.then { |l| l.disabled? ? 0 : 1 },
"Payment Type" => ((purchase.card_type == "paypal" ? "PayPal" : "Card") if purchase.card_type.present?),
"PayPal Transaction ID" => (purchase.stripe_transaction_id if purchase.paypal_order_id?),
"PayPal Fee Amount" => (purchase.processor_fee_dollars if purchase.paypal_order_id?),
"PayPal Fee Currency" => (purchase.processor_fee_cents_currency if purchase.paypal_order_id?),
"Stripe Transaction ID" => (purchase.stripe_transaction_id if purchase.charged_using_stripe_connect_account?),
"Stripe Fee Amount" => (purchase.processor_fee_dollars if purchase.charged_using_stripe_connect_account?),
"Stripe Fee Currency" => (purchase.processor_fee_cents_currency if purchase.charged_using_stripe_connect_account?),
"Purchasing Power Parity Discounted?" => purchase.is_purchasing_power_parity_discounted ? 1 : 0,
"Upsold?" => purchase.upsell_purchase.present? ? 1 : 0,
"Sent Abandoned Cart Email?" => sent_abandoned_cart_email?(purchase) ? 1 : 0,
"UTM Source" => utm_link&.utm_source,
"UTM Medium" => utm_link&.utm_medium,
"UTM Campaign" => utm_link&.utm_campaign,
"UTM Term" => utm_link&.utm_term,
"UTM Content" => utm_link&.utm_content
}
raise "This data is not JSON safe: #{data.inspect}" if !Rails.env.production? && !data.eql?(JSON.load(JSON.dump(data)))
[data, custom_fields_data]
end
# Internal: Get the CSV field for taxation type - inclusive(Y) / exclusive(N) / not applicable(N/A)
# Returns a value that logically answers - "Is Tax Included in Price ?"
#
# purchase - The purchase being serialized to CSV
def determine_exclusive_tax_report_field(purchase)
return unless purchase.was_purchase_taxable?
purchase.was_tax_excluded_from_price ? 0 : 1
end
def pseudo_transliterate(string)
return if string.nil?
transliterated = ActiveSupport::Inflector.transliterate(string)
return transliterated unless transliterated.include? "?"
string
end
def sent_abandoned_cart_email?(purchase)
return if purchase.order&.cart.blank?
purchase.order.cart.sent_abandoned_cart_emails.any? { _1.installment.seller_id == purchase.link.user_id }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/affiliate_export_service.rb | app/services/exports/affiliate_export_service.rb | # frozen_string_literal: true
class Exports::AffiliateExportService
AFFILIATE_FIELDS = [
"Affiliate ID", "Name", "Email", "Fee", "Products", "Sales ($)",
"Referral URL", "Destination URL", "Created At",
].freeze
TOTALS_FIELDS = ["Sales ($)"].freeze
TOTALS_COLUMN_NAME = "Totals"
SYNCHRONOUS_EXPORT_THRESHOLD = 500
attr_reader :filename, :tempfile
def initialize(seller)
@seller = seller
timestamp = Time.current.to_fs(:db).gsub(/ |:/, "-")
@filename = "Affiliates-#{@seller.username}_#{timestamp}.csv"
@totals = Hash.new(0)
end
def perform
@tempfile = Tempfile.new(["Affiliates", ".csv"], "tmp", encoding: "UTF-8")
CSV.open(@tempfile, "wb") do |csv|
csv << AFFILIATE_FIELDS
@seller.direct_affiliates.alive.includes(:affiliate_user, :products).find_each do |affiliate|
csv << affiliate_row(affiliate)
end
totals_row = Array.new(AFFILIATE_FIELDS.size)
totals_row[0] = TOTALS_COLUMN_NAME
totals.each do |column_name, value|
totals_row[AFFILIATE_FIELDS.index(column_name)] = value.round(2)
end
csv << totals_row
end
@tempfile.rewind
self
end
def self.export(seller:, recipient: seller)
if seller.direct_affiliates.alive.count <= SYNCHRONOUS_EXPORT_THRESHOLD
new(seller).perform
else
Exports::AffiliateExportWorker.perform_async(seller.id, recipient.id)
false
end
end
private
attr_reader :totals
def affiliate_row(affiliate)
data = {
"Affiliate ID" => affiliate.external_id_numeric,
"Name" => affiliate.affiliate_user.name.presence || affiliate.affiliate_user.username,
"Email" => affiliate.affiliate_user.email,
"Fee" => "#{affiliate.affiliate_percentage} %",
"Sales ($)" => MoneyFormatter.format(affiliate.total_amount_cents, :usd, symbol: false),
"Products" => affiliate.products.map(&:name),
"Referral URL" => affiliate.referral_url,
"Destination URL" => affiliate.destination_url,
"Created At" => affiliate.created_at.in_time_zone(affiliate.affiliate_user.timezone).to_date,
}
row = Array.new(AFFILIATE_FIELDS.size)
data.each do |column_name, value|
row[AFFILIATE_FIELDS.index(column_name)] = value
@totals[column_name] += value.to_f if TOTALS_FIELDS.include?(column_name)
end
row
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/payouts/csv.rb | app/services/exports/payouts/csv.rb | # frozen_string_literal: true
class Exports::Payouts::Csv < Exports::Payouts::Base
HEADERS = ["Type", "Date", "Purchase ID", "Item Name", "Buyer Name", "Buyer Email", "Taxes ($)", "Shipping ($)", "Sale Price ($)", "Gumroad Fees ($)", "Net Total ($)"]
TOTALS_COLUMN_NAME = "Totals"
TOTALS_FIELDS = ["Taxes ($)", "Shipping ($)", "Sale Price ($)", "Gumroad Fees ($)", "Net Total ($)"]
def initialize(payment_id:)
@payment_id = payment_id
end
def perform
data = payout_data
CSV.generate do |csv|
csv << HEADERS
data.each do |row|
csv << row
end
totals = calculate_totals(data)
csv << generate_totals_row(totals)
end.encode("UTF-8", invalid: :replace, replace: "?")
end
private
def calculate_totals(data, from_totals: Hash.new(0))
totals = from_totals.dup
data.each do |row|
TOTALS_FIELDS.each do |column_name|
column_index = HEADERS.index(column_name)
totals[column_name] += row[column_index].to_f if column_index.present?
end
end
totals
end
def generate_totals_row(totals)
totals_row = Array.new(HEADERS.size)
totals_row[0] = TOTALS_COLUMN_NAME
totals.each do |column_name, value|
totals_row[HEADERS.index(column_name)] = value.round(2)
end
totals_row
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/payouts/annual.rb | app/services/exports/payouts/annual.rb | # frozen_string_literal: true
class Exports::Payouts::Annual < Exports::Payouts::Csv
include CurrencyHelper
def initialize(user:, year:)
@user = user
@year = Date.new(year)
end
# Note: This returns a csv tempfile object. Please close and unlink the file after usage for better GC.
def perform
# Fetch payments from over the year and a week before/after.
# We then filter out any transaction that does not fall in the year later.
payments_scope = @user.payments.completed.where("created_at BETWEEN ? AND ?",
(@year.beginning_of_year - 1.week),
(@year.end_of_year + 1.week))
return { csv_file: nil, total_amount: 0 } unless payments_scope.exists?
totals = Hash.new(0)
total_amount = 0
tempfile = Tempfile.open(File.join(Rails.root, "tmp", "#{@user.id}_#{@year}_annual.csv"),
encoding: "UTF-8")
CSV.open(tempfile, "wb") do |csv|
csv << HEADERS
payments_scope.find_each do |payment|
@payment_id = payment.id
data = payout_data
totals = calculate_totals(data, from_totals: totals)
data.each do |row|
date = Date.parse(row[1])
if date <= @year.end_of_year && date >= @year.beginning_of_year
total_amount += row[-1].to_f unless row[0] == PAYPAL_PAYOUTS_HEADING
csv << row
end
end
GC.start
end
csv << generate_totals_row(totals)
end
tempfile.rewind
{ csv_file: tempfile, total_amount: }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/payouts/base.rb | app/services/exports/payouts/base.rb | # frozen_string_literal: true
class Exports::Payouts::Base
PAYPAL_PAYOUTS_HEADING = "PayPal Payouts"
STRIPE_CONNECT_PAYOUTS_HEADING = "Stripe Connect Payouts"
def initialize(payment_id)
@payment_id = payment_id
@running_total = 0
end
private
def payout_data
payout = Payment.find(@payment_id)
@running_total = 0
data = []
payout.balances.find_each do |bal|
bal.successful_sales.joins(:link).find_each do |purchase|
data << summarize_sale(purchase)
end
bal.chargedback_sales.joins(:link).find_each do |purchase|
data << summarize_chargeback(purchase)
end
bal.refunded_sales.joins(:link).find_each do |purchase|
balance_transactions_related_to_purchase_refunds = bal.balance_transactions.joins(:refund).where("balance_transactions.refund_id in (?)", purchase.refunds.pluck(:id))
if balance_transactions_related_to_purchase_refunds.size == 0 && purchase.refunds.size == 1
# Refunds made a while ago don't seem to have a balance_transaction associated with them.
# If that's the case, and if there is only one refund in the full amount, we can format that refund properly
# even with the missing balance transaction.
refund = purchase.refunds.first
if refund.total_transaction_cents == purchase.total_transaction_cents
data << summarize_full_refund(refund, purchase)
end
else
balance_transactions_related_to_purchase_refunds.find_each do |btxn|
# This should always be in USD cents.
gross_amount = -btxn.refund.amount_cents / 100.0
if gross_amount == -purchase.price_dollars
data << summarize_full_refund(btxn.refund, purchase)
else
data << summarize_partial_refund(btxn, purchase)
end
end
end
end
affiliate_credit_cents = calculate_affiliate_for_balance(bal)
if affiliate_credit_cents != 0
data << summarize_affiliate_credit(bal, affiliate_credit_cents)
end
Credit.where(balance: bal).find_each do |credit|
next if credit.fee_retention_refund.present? && credit.amount_cents <= 0
amount = (credit.amount_cents / 100.0).round(2)
@running_total += credit.amount_cents
data << [
"Credit",
bal.date.to_s,
credit.fee_retention_refund.present? ? credit.fee_retention_refund.purchase.external_id.to_s : credit.chargebacked_purchase&.external_id.to_s,
"",
"",
"",
"",
"",
amount,
"",
amount,
]
end
end
data = merge_paypal_sales_data(data)
data = merge_stripe_connect_sales_data(data)
if payout.gumroad_fee_cents.present?
data << [
"Payout Fee",
payout.payout_period_end_date.to_s,
"",
"",
"",
"",
"",
"",
"",
(payout.gumroad_fee_cents / 100.0).round(2),
-(payout.gumroad_fee_cents / 100.0).round(2),
]
@running_total -= payout.gumroad_fee_cents
end
data.sort_by!(&:second) # Sort by date
if payout.currency == Currency::USD && payout.amount_cents != @running_total
# Our calculation produced a net total that is different from the actual payout total.
# We can, at the very least, add an adjustment row to the CSV so that the "net total" column adds up.
# We can also use this conditional to mark the payout for future review.
# We don't include non-usd payments here since the currency mismatch leads to
# wrong totals and erroneous entries most of the time.
adjustment_cents = payout.amount_cents - @running_total
adjustment = adjustment_cents / 100.0
data << [
"Technical Adjustment",
payout.payout_period_end_date.to_s,
"",
"",
"",
"",
"",
"",
"",
"",
adjustment,
]
end
data
end
def merge_paypal_sales_data(data)
payout = Payment.find(@payment_id)
user = payout.user
previous_payout = payout.user.payments.completed.where("created_at < ?", payout.created_at).order(:payout_period_end_date).last
payout_start_date = previous_payout&.payout_period_end_date.try(:next)
payout_start_date ||= PayoutsHelper::OLDEST_DISPLAYABLE_PAYOUT_PERIOD_END_DATE.to_date
payout_end_date = payout.payout_period_end_date || Date.today.to_date
user.paypal_sales_in_duration(start_date: payout_start_date, end_date: payout_end_date).joins(:link).find_each do |purchase|
data << summarize_sale(purchase)
end
user.paypal_sales_chargebacked_in_duration(start_date: payout_start_date, end_date: payout_end_date).joins(:link).find_each do |purchase|
data << summarize_chargeback(purchase)
end
user.paypal_refunds_in_duration(start_date: payout_start_date, end_date: payout_end_date).find_each do |refund|
data << summarize_paypal_refund(refund)
end
(payout_start_date..payout_end_date).each do |date|
affiliate_fees_entry = summarize_paypal_affiliate_fee(user, date)
data << affiliate_fees_entry if affiliate_fees_entry.last != 0
end
paypal_sales_data = user.paypal_sales_data_for_duration(start_date: payout_start_date, end_date: payout_end_date)
paypal_payout_amount = user.paypal_payout_net_cents(paypal_sales_data)
data << summarize_paypal_payout(paypal_payout_amount, payout_end_date) if paypal_payout_amount != 0
data
end
def merge_stripe_connect_sales_data(data)
payout = Payment.find(@payment_id)
user = payout.user
previous_payout = payout.user.payments.completed.where("created_at < ?", payout.created_at).order(:payout_period_end_date).last
payout_start_date = previous_payout&.payout_period_end_date.try(:next)
payout_start_date ||= PayoutsHelper::OLDEST_DISPLAYABLE_PAYOUT_PERIOD_END_DATE.to_date
payout_end_date = payout.payout_period_end_date || Date.today.to_date
user.stripe_connect_sales_in_duration(start_date: payout_start_date, end_date: payout_end_date).joins(:link).find_each do |purchase|
data << summarize_sale(purchase)
end
user.stripe_connect_sales_chargebacked_in_duration(start_date: payout_start_date, end_date: payout_end_date).joins(:link).find_each do |purchase|
data << summarize_chargeback(purchase)
end
user.stripe_connect_refunds_in_duration(start_date: payout_start_date, end_date: payout_end_date).find_each do |refund|
data << summarize_stripe_connect_refund(refund)
end
(payout_start_date..payout_end_date).each do |date|
affiliate_fees_entry = summarize_stripe_connect_affiliate_fee(user, date)
data << affiliate_fees_entry if affiliate_fees_entry.last != 0
end
stripe_connect_sales_data = user.stripe_connect_sales_data_for_duration(start_date: payout_start_date, end_date: payout_end_date)
stripe_connect_payout_amount = user.stripe_connect_payout_net_cents(stripe_connect_sales_data)
data << summarize_stripe_connect_payout(stripe_connect_payout_amount, payout_end_date) if stripe_connect_payout_amount != 0
data
end
def summarize_sale(purchase)
@running_total += purchase.payment_cents
[
"Sale",
purchase.succeeded_at.to_date.to_s,
purchase.external_id,
purchase.link.name,
purchase.full_name,
purchase.purchaser_email_or_email,
purchase.tax_dollars,
purchase.shipping_dollars,
purchase.price_dollars,
purchase.fee_dollars,
purchase.net_total,
]
end
def summarize_chargeback(purchase)
@running_total += -purchase.payment_cents
[
"Chargeback",
purchase.chargeback_date.to_date.to_s,
purchase.external_id,
purchase.link.name,
purchase.full_name,
purchase.purchaser_email_or_email,
-purchase.tax_dollars,
-purchase.shipping_dollars,
-purchase.price_dollars,
-purchase.fee_dollars,
-purchase.net_total,
]
end
def summarize_full_refund(refund, purchase)
@running_total += purchase.is_refund_chargeback_fee_waived? ? -purchase.payment_cents : -purchase.payment_cents - refund.retained_fee_cents.to_i
[
"Full Refund",
refund.created_at.to_date.to_s,
purchase.external_id,
purchase.link.name,
purchase.full_name,
purchase.purchaser_email_or_email,
-purchase.tax_dollars,
-purchase.shipping_dollars,
-purchase.price_dollars,
purchase.is_refund_chargeback_fee_waived? ? -purchase.fee_dollars : -purchase.fee_dollars + (refund.retained_fee_cents.to_i / 100.0).round(2),
purchase.is_refund_chargeback_fee_waived? ? -purchase.net_total : -purchase.net_total - (refund.retained_fee_cents.to_i / 100.0).round(2),
]
end
def summarize_partial_refund(btxn, purchase)
# These should always be in USD cents.
gross_amount = -btxn.refund.amount_cents / 100.0
net_amount = btxn.issued_amount_net_cents / 100.0
gumroad_fee_amount = -btxn.refund.fee_cents / 100.0
@running_total += btxn.issued_amount_net_cents
unless purchase.is_refund_chargeback_fee_waived?
gumroad_fee_amount += btxn.refund.retained_fee_cents.to_i / 100.0
net_amount -= btxn.refund.retained_fee_cents.to_i / 100.0
@running_total -= btxn.refund.retained_fee_cents.to_i
end
[
"Partial Refund",
btxn.refund.created_at.to_date.to_s,
purchase.external_id,
purchase.link.name,
purchase.full_name,
purchase.purchaser_email_or_email,
-(btxn.refund.creator_tax_cents / 100.0).round(2),
-0.0, # TODO can be partial - what happens to shipping?
gross_amount.round(2),
gumroad_fee_amount.round(2),
net_amount.round(2),
]
end
def summarize_paypal_refund(refund)
@running_total -= refund.amount_cents - refund.fee_cents
[
"PayPal Refund",
refund.created_at.to_date.to_s,
refund.purchase.external_id,
refund.purchase.link.name,
refund.purchase.full_name,
refund.purchase.purchaser_email_or_email,
-(refund.creator_tax_cents / 100.0).round(2),
-0.0, # TODO can be partial - what happens to shipping?
-(refund.amount_cents / 100.0).round(2),
(refund.fee_cents / 100.0).round(2),
-(refund.amount_cents / 100.0).round(2) + (refund.fee_cents / 100.0).round(2),
]
end
def summarize_stripe_connect_refund(refund)
@running_total -= refund.amount_cents - refund.fee_cents
[
"Stripe Connect Refund",
refund.created_at.to_date.to_s,
refund.purchase.external_id,
refund.purchase.link.name,
refund.purchase.full_name,
refund.purchase.purchaser_email_or_email,
-(refund.creator_tax_cents / 100.0).round(2),
-0.0, # TODO can be partial - what happens to shipping?
-(refund.amount_cents / 100.0).round(2),
(refund.fee_cents / 100.0).round(2),
-(refund.amount_cents / 100.0).round(2) + (refund.fee_cents / 100.0).round(2),
]
end
def summarize_affiliate_credit(bal, amount)
@running_total += amount
[
"Affiliate Credit",
bal.date.to_s,
"",
"",
"",
"",
"",
"",
(amount / 100.0),
"",
(amount / 100.0),
]
end
def summarize_paypal_affiliate_fee(user, date)
amount = user.paypal_affiliate_fee_cents_for_duration(start_date: date, end_date: date)
@running_total -= amount
[
"PayPal Connect Affiliate Fees",
date.to_s,
"",
"",
"",
"",
"",
"",
-(amount / 100.0),
"",
-(amount / 100.0),
]
end
def summarize_stripe_connect_affiliate_fee(user, date)
amount = user.stripe_connect_affiliate_fee_cents_for_duration(start_date: date, end_date: date)
@running_total -= amount
[
"Stripe Connect Affiliate Fees",
date.to_s,
"",
"",
"",
"",
"",
"",
-(amount / 100.0),
"",
-(amount / 100.0),
]
end
def summarize_paypal_payout(amount, date)
@running_total -= amount
[
PAYPAL_PAYOUTS_HEADING,
date.to_s,
"",
"",
"",
"",
"",
"",
-(amount / 100.0),
"",
-(amount / 100.0),
]
end
def summarize_stripe_connect_payout(amount, date)
@running_total -= amount
[
STRIPE_CONNECT_PAYOUTS_HEADING,
date.to_s,
"",
"",
"",
"",
"",
"",
-(amount / 100.0),
"",
-(amount / 100.0),
]
end
# Affiliate credits for a balance consist of:
# - sum of affiliate credits accurred for this balance
# - minus sum of affiliate credits that were refunded/charged back for this balance
# (the positive credit itself for the purchase most likely has happened in a different, previous balance)
def calculate_affiliate_for_balance(bal)
affiliate_credit_cents_for_balance = AffiliateCredit
.where(affiliate_credit_success_balance_id: bal.id)
.sum("amount_cents")
affiliate_fee_cents_for_balance = Purchase
.where(purchase_success_balance_id: bal.id)
.sum("affiliate_credit_cents")
refunded_affiliate_credit_cents_for_balance = AffiliateCredit
.where(affiliate_credit_refund_balance_id: bal.id)
.sum("amount_cents")
refunded_affiliate_fee_cents_for_balance = Purchase
.where(purchase_refund_balance_id: bal.id)
.sum("affiliate_credit_cents")
chargeback_affiliate_credit_cents_for_balance = AffiliateCredit
.where(affiliate_credit_chargeback_balance_id: bal.id)
.sum("amount_cents")
chargeback_affiliate_fee_cents_for_balance = Purchase
.where(purchase_chargeback_balance_id: bal.id)
.sum("affiliate_credit_cents")
total_affiliate_credit_cents = affiliate_credit_cents_for_balance - refunded_affiliate_credit_cents_for_balance - chargeback_affiliate_credit_cents_for_balance
total_affiliate_fee_cents = affiliate_fee_cents_for_balance - refunded_affiliate_fee_cents_for_balance - chargeback_affiliate_fee_cents_for_balance
(total_affiliate_credit_cents - total_affiliate_fee_cents)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/tax_summary/annual.rb | app/services/exports/tax_summary/annual.rb | # frozen_string_literal: true
class Exports::TaxSummary::Annual
def initialize(year:, start: nil, finish: nil)
@year = year
@start = start
@finish = finish
end
def perform
tempfile = Tempfile.new(File.join(Rails.root, "tmp", tempfile_name),
encoding: "UTF-8")
CSV.open(tempfile, "wb") do |csv|
headers_added = false
User.alive.find_each(start: @start, finish: @finish) do |user|
if user.eligible_for_1099?(@year)
Rails.logger.info("Exporting tax summary for user #{user.id}")
payable_service = Exports::TaxSummary::Payable.new(user:, year: @year)
unless headers_added
csv << payable_service.payable_headers
headers_added = true
end
summary = payable_service.perform(as_csv: false)
csv << summary if summary
end
end
end
tempfile.rewind
ExpiringS3FileService.new(file: tempfile,
extension: "csv",
filename: tempfile_name).perform
end
private
def tempfile_name
"annual_exports_#{@year}_#{SecureRandom.uuid}-#{Time.current.strftime('%W')}.csv"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/exports/tax_summary/base.rb | app/services/exports/tax_summary/base.rb | # frozen_string_literal: true
class Exports::TaxSummary::Base
attr_reader :date_in_year
def initialize(user:, year:)
@user = user
@date_in_year = Date.new(year)
end
def perform
payouts_summary
end
private
def payouts_summary
return { transaction_cents_by_month: {},
total_transaction_cents: 0,
transactions_count: 0 } unless @user.sales.where("created_at BETWEEN ? AND ?",
date_in_year.beginning_of_year,
date_in_year.end_of_year).exists?
transaction_cents_by_month = Hash.new(0)
total_transaction_cents = 0
transactions_count = 0
(0..11).each do |i|
month_date = date_in_year + i.months
sales_scope = sales_scope_for(month_date)
transaction_cents = sales_scope.sum(:total_transaction_cents)
transaction_cents_by_month[i] = transaction_cents
total_transaction_cents += transaction_cents
transactions_count += sales_scope.count
end
{ transaction_cents_by_month:,
total_transaction_cents:,
transactions_count: }
end
def sales_scope_for(date)
@user.sales.successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback.
where("created_at BETWEEN ? AND ?",
date.beginning_of_month,
date.end_of_month)
.where("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/services/exports/tax_summary/payable.rb | app/services/exports/tax_summary/payable.rb | # frozen_string_literal: true
class Exports::TaxSummary::Payable < Exports::TaxSummary::Base
# When we want to use this to build the bigger report,
# we pass as_csv: false to just fetch row to be added to bigger CSV
# Otherwise the default behaviour to generate this report for single
# user, when we want to file for corrections for some user.
def perform(as_csv: true)
unless compliance_info&.has_completed_compliance_info?
Rails.logger.info("Failed to export tax summary for user #{@user.id}")
return nil
end
data = payouts_summary
return nil unless data && data[:total_transaction_cents] > 0
if as_csv
CSV.generate do |csv|
csv << payable_headers
row = build_payable_summary(data)
csv << row if row
end
else
build_payable_summary(data)
end
end
# Header references: https://payable.com/taxes/part-2-how-to-set-up-a-full-form-import-1099-misc-1099-k
def payable_headers
["Payable Worker ID",
"External Worker ID",
"Stripe ID",
"Display Name", "First Name", "Last Name", "Business Name",
"Email",
"Address Line 1", "Address Line 2", "City", "Region", "Postal Code", "Country",
"Business Type",
"SSN", "EIN",
"Filer Is",
"Transactions Reported Are",
"PSE's Name", "PSE's Phone",
"Box 1a - Gross Amount of Transactions", "Box 1b - Card Not Present Transactions",
"Box 2 - Merchant Category Code",
"Box 3 - Number of Payment Transactions",
"Box 4 - Federal Income Tax Withheld",
"Box 5a - Jan", "Box 5b - Feb", "Box 5c - Mar", "Box 5d - Apr", "Box 5e - May", "Box 5f - Jun", "Box 5g - Jul", "Box 5h - Aug", "Box 5i - Sep", "Box 5j - Oct", "Box 5k - Nov", "Box 5l - Dec",
"Box 6 - State Abbreviation", "Box 6 (Other State) - Other State Abbreviation",
"Box 7 - Filer's State ID", "Box 7 (Other State) - Filer's Other State ID",
"Box 8 - State Tax Withheld", "Box 8 (Other State) - Other State Tax Withheld"]
end
private
# See https://payable.com/taxes/part-2-how-to-set-up-a-full-form-import-1099-misc-1099-k
# for how we get these values
def build_payable_summary(data)
row = [nil, # "Payable Worker ID": We don't have this value and should be null # [0]
# Payable uses this to match users the next time we upload
@user.external_id, # [1]
# "Stripe ID",
stripe_id, # [2]
# "Display Name", "First Name", "Last Name", "Business Name",
compliance_info.first_and_last_name, compliance_info.first_name, compliance_info.last_name, compliance_info.legal_entity_name, # [3, 4, 5, 6]
# Email
@user.email, # [7]
# "Address Line 1", "Address Line 2", "City", "Region", "Postal Code", "Country",
compliance_info.legal_entity_street_address, nil, compliance_info.legal_entity_city, compliance_info.legal_entity_state_code, compliance_info.legal_entity_zip_code, compliance_info.legal_entity_country_code, # [8, 9, 10, 11, 12, 13]
# "Business Type",
compliance_info.legal_entity_payable_business_type, # [14]
# "SSN", "EIN",
personal_tax_id.presence, business_tax_id.presence, # [15, 16]
# "Filer Is",
"EPF Other", # [17]
# "Transactions Reported Are",
"Third Party Network", # [18]
# "PSE's Name", "PSE's Phone",
"Gumroad", "(650) 204-3486", # [19, 20]
# Box 1a - Gross Amount of Transactions
(data[:total_transaction_cents] / 100.0), # [21]
# Box 1b - Card Not Present Transactions
nil, # [22]
# "Box 2 - Merchant Category Code", this is empty on payable
nil, # [23]
# Box 3 - Number of Payment Transactions
# The total count of all payment transactions for the Payee in the given tax year
data[:transactions_count], # [24]
# "Box 4 - Federal Income Tax Withheld", this is empty on payable
nil] # [25]
row.concat(monthly_summary_for(data))
row.concat([ # "Box 6 - State Abbreviation",
compliance_info.legal_entity_state_code,
# "Box 6 (Other State) - Other State Abbreviation"
nil,
# "Box 7 - Filer's State ID",
nil,
# "Box 7 (Other State) - Filer's Other State ID",
nil,
# "Box 8 - State Tax Withheld", this, its zero on payable.
nil,
# "Box 8 (Other State) - Other State Tax Withheld"
nil])
row
end
def compliance_info
@compliance_info ||= @user.alive_user_compliance_info
end
def stripe_id
stripe_merchant_account = @user.merchant_accounts.alive.stripe.first
stripe_merchant_account.present? ? stripe_merchant_account.charge_processor_merchant_id : nil
end
def personal_tax_id
compliance_info.individual_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))
end
def business_tax_id
compliance_info.business_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")) if compliance_info.is_business
end
def monthly_summary_for(data)
monthly_summary = []
data[:transaction_cents_by_month].each do |index, amount_cents|
monthly_summary[index] = amount_cents / 100.0
end
monthly_summary
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/variants_updater_service.rb | app/services/product/variants_updater_service.rb | # frozen_string_literal: true
class Product::VariantsUpdaterService
attr_reader :product, :skus_params
attr_accessor :variants_params
delegate :price_currency_type,
:skus_enabled,
:variant_categories_alive,
:skus, to: :product
def initialize(product:, variants_params:, skus_params: {})
@product = product
@variants_params = variants_params
@skus_params = skus_params.values
end
def perform
self.variants_params = clean_variants_params(variants_params)
existing_categories = variant_categories_alive.to_a
keep_categories = []
variants_params.each do |category|
variant_category_updater = Product::VariantCategoryUpdaterService.new(
product:,
category_params: category
)
variant_category = variant_category_updater.perform
keep_categories << variant_category if category[:id].present?
end
categories_to_delete = existing_categories - keep_categories
categories_to_delete.each do |variant_category|
variant_category.mark_deleted! unless variant_category.has_alive_grouping_variants_with_purchases?
end
begin
Product::SkusUpdaterService.new(product:, skus_params:).perform if skus_enabled
rescue ActiveRecord::RecordInvalid => e
product.errors.add(:base, e.message)
raise e
end
end
private
def clean_variants_params(params)
return [] if !params.present?
variant_array = params.is_a?(Hash) ? params.values : params
variant_array.map do |variant|
# TODO: product_edit_react cleanup
options = variant[:options].is_a?(Hash) ? variant[:options].values : variant[:options]
{
title: variant[:name],
id: variant[:id],
options: options&.map do |option|
new_option = option.slice(:id, :temp_id, :name, :description, :url, :customizable_price, :recurrence_price_values, :max_purchase_count, :integrations, :rich_content, :apply_price_changes_to_existing_memberships, :subscription_price_change_effective_date, :subscription_price_change_message, :duration_in_minutes)
# TODO: :product_edit_react cleanup
if option[:price_difference_cents].present?
option[:price] = option[:price_difference_cents]
option[:price] /= 100.0 unless @product.single_unit_currency?
end
new_option.merge!(price_difference: option[:price])
if price_change_settings = option.dig(:settings, :apply_price_changes_to_existing_memberships)
if price_change_settings[:enabled] == "1"
new_option[:apply_price_changes_to_existing_memberships] = true
new_option[:subscription_price_change_effective_date] = price_change_settings[:effective_date]
new_option[:subscription_price_change_message] = price_change_settings[:custom_message]
else
new_option[:apply_price_changes_to_existing_memberships] = false
new_option[:subscription_price_change_effective_date] = nil
new_option[:subscription_price_change_message] = nil
end
end
if price_change_settings.blank? && !option[:apply_price_changes_to_existing_memberships]
new_option[:subscription_price_change_effective_date] = nil
new_option[:subscription_price_change_message] = nil
end
new_option
end
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/save_cancellation_discount_service.rb | app/services/product/save_cancellation_discount_service.rb | # frozen_string_literal: true
class Product::SaveCancellationDiscountService
attr_reader :product, :cancellation_discount_params
def initialize(product, cancellation_discount_params)
@product = product
@cancellation_discount_params = cancellation_discount_params
end
def perform
if cancellation_discount_params.blank?
product.cancellation_discount_offer_code&.mark_deleted!
return
end
discount = cancellation_discount_params[:discount]
offer_code_params = {
products: [product],
user_id: product.user_id,
is_cancellation_discount: true,
duration_in_billing_cycles: cancellation_discount_params[:duration_in_billing_cycles],
}
if discount[:type] == "fixed"
offer_code_params[:amount_cents] = discount[:cents]
offer_code_params[:amount_percentage] = nil
else
offer_code_params[:amount_percentage] = discount[:percents]
offer_code_params[:amount_cents] = nil
end
cancellation_offer_code = product.cancellation_discount_offer_code
if cancellation_offer_code.present?
cancellation_offer_code.update!(offer_code_params)
else
OfferCode.create!(offer_code_params)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/compute_call_availabilities_service.rb | app/services/product/compute_call_availabilities_service.rb | # frozen_string_literal: true
class Product::ComputeCallAvailabilitiesService
def initialize(product)
@product = product
end
def perform
return [] unless product.native_type == Link::NATIVE_TYPE_CALL
Time.use_zone(product.user.timezone) do
untaken_availabilities.map do |interval|
interval
.then { adjust_for_minimum_notice_period(_1) }
.then { adjust_for_maximum_calls_per_day(_1) }
end.compact
end
end
private
attr_reader :product
delegate :call_availabilities, :sold_calls, :call_limitation_info, to: :product
def untaken_availabilities
availability_changes = Hash.new(0)
all_availabilities.each do |interval|
availability_changes[interval[:start_time]] += 1
availability_changes[interval[:end_time]] -= 1
end
taken_availabilities.each do |interval|
availability_changes[interval[:start_time]] -= 1
availability_changes[interval[:end_time]] += 1
end
availabilities = []
current_start = nil
current_availability = 0
availability_changes.sort_by(&:first).each do |time, availability_change|
current_availability += availability_change
if current_availability > 0
current_start ||= time
end
if current_availability <= 0 && current_start
availabilities << { start_time: current_start, end_time: time }
current_start = nil
end
end
availabilities
end
def adjust_for_minimum_notice_period(interval)
return nil if interval.nil?
return nil if interval[:end_time] < earliest_available_at
interval[:start_time] = earliest_available_at if interval[:start_time] < earliest_available_at
interval
end
def adjust_for_maximum_calls_per_day(interval)
return nil if interval.nil?
if !can_take_more_calls?(interval[:start_time])
next_available_day = (interval[:start_time].to_date.next_day).upto(interval[:end_time].to_date)
.find { can_take_more_calls?(_1) }
return nil unless next_available_day
interval[:start_time] = next_available_day.beginning_of_day
end
if !can_take_more_calls?(interval[:end_time])
previous_available_day = (interval[:end_time].to_date.prev_day).downto(interval[:start_time].to_date)
.find { can_take_more_calls?(_1) }
return nil unless previous_available_day
interval[:end_time] = previous_available_day.end_of_day
end
interval
end
def can_take_more_calls?(date)
calls_per_day[date.to_date] < maximum_calls_per_day
end
def maximum_calls_per_day
@_maximum_calls_per_day ||= call_limitation_info.maximum_calls_per_day || Float::INFINITY
end
def earliest_available_at
@_earliest_available_at ||= call_limitation_info.minimum_notice_in_minutes&.minutes&.from_now || Time.current
end
def calls_per_day
@_calls_per_day ||= taken_availabilities.each_with_object(Hash.new(0)) do |interval, hash|
# Do not count end time's date towards the number of calls, to allow for
# maximum number of sales.
# Even if the call spans 3+ days (however unlikely), the middle day
# would be fully booked and would not have any more availabilities.
hash[interval[:start_time].to_date] += 1
end
end
def all_availabilities
@_all_availabilities ||= fetch_intervals(call_availabilities.upcoming.ordered_chronologically)
end
def taken_availabilities
@_taken_availabilities ||= fetch_intervals(sold_calls.occupies_availability.upcoming.ordered_chronologically)
end
def fetch_intervals(relation)
relation
.pluck(:start_time, :end_time)
.map { |start_time, end_time| { start_time:, end_time: } }
.then { group_overlapping_intervals(_1) }
end
def group_overlapping_intervals(sorted_intervals)
sorted_intervals.each_with_object([]) do |interval, grouped|
if grouped.empty? || interval[:start_time] > grouped.last[:end_time]
grouped << interval
else
grouped.last[:end_time] = [grouped.last[:end_time], interval[:end_time]].max
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/variant_category_updater_service.rb | app/services/product/variant_category_updater_service.rb | # frozen_string_literal: true
class Product::VariantCategoryUpdaterService
include CurrencyHelper
attr_reader :product, :category_params
attr_accessor :variant_category
delegate :price_currency_type,
:is_tiered_membership,
:product_files,
:errors,
:variant_categories, to: :product
ALLOWED_ATTRIBUTES = %i[
name
description
price_difference_cents
max_purchase_count
position_in_category
customizable_price
subscription_price_change_effective_date
subscription_price_change_message
duration_in_minutes
apply_price_changes_to_existing_memberships
variant_category
product_files
].freeze
def initialize(product:, category_params:)
@product = product
@category_params = category_params
end
def perform
if category_params[:id].present?
self.variant_category = variant_categories.find_by_external_id(category_params[:id])
variant_category.update(title: category_params[:title])
else
self.variant_category = variant_categories.build(title: category_params[:title])
end
if category_params[:options].nil?
variant_category.variants.map(&:mark_deleted)
variant_category.mark_deleted! if variant_category.title.blank?
else
existing_variants = variant_category.variants.to_a
keep_variants = []
validate_variant_recurrences!(category_params[:options])
category_params[:options].each_with_index do |option, index|
begin
variant = create_or_update_variant!(option[:id],
name: option[:name],
description: option[:description],
duration_in_minutes: option[:duration_in_minutes],
price_difference_cents: string_to_price_cents(
price_currency_type.to_sym,
option[:price_difference].to_s
),
customizable_price: option[:customizable_price],
max_purchase_count: option[:max_purchase_count],
position_in_category: index,
variant_category:,
apply_price_changes_to_existing_memberships: !!option[:apply_price_changes_to_existing_memberships],
subscription_price_change_effective_date: option[:subscription_price_change_effective_date],
subscription_price_change_message: option[:subscription_price_change_message])
save_integrations(variant, option)
save_rich_content(variant, option)
variant.product_files = ProductFile.find(variant.alive_rich_contents.flat_map { _1.embedded_product_file_ids_in_order }.uniq)
save_recurring_prices!(variant, option) if is_tiered_membership && has_variant_recurrences?
rescue ActiveRecord::RecordInvalid, Link::LinkInvalid, ArgumentError => e
error_message = variant.present? ? variant.errors.full_messages.to_sentence : e.message
errors.add(:base, error_message)
raise Link::LinkInvalid
end
keep_variants << variant if option[:id]
end
variants_to_delete = existing_variants - keep_variants
variants_to_delete.map(&:mark_deleted) if variants_to_delete.present?
end
variant_category.save!
variant_category
end
private
def create_or_update_variant!(external_id, params)
return Variant.create!(params.slice(*ALLOWED_ATTRIBUTES)) if external_id.blank?
variant = product.variants.find_by_external_id!(external_id)
variant.assign_attributes(params.slice(*ALLOWED_ATTRIBUTES))
if variant.apply_price_changes_to_existing_memberships_changed? && !variant.apply_price_changes_to_existing_memberships?
variant.subscription_plan_changes.for_product_price_change.alive.each(&:mark_deleted)
end
notify_members_of_price_change = variant.apply_price_changes_to_existing_memberships? && variant.subscription_price_change_effective_date_changed?
variant.save!
if notify_members_of_price_change
ScheduleMembershipPriceUpdatesJob.perform_async(variant.id)
elsif variant.flags_previously_changed? || variant.subscription_price_change_effective_date_previously_changed?
Bugsnag.notify("Not notifying subscribers of membership price change - tier: #{variant.id}; apply_price_changes_to_existing_memberships: #{variant.apply_price_changes_to_existing_memberships?}; subscription_price_change_effective_date: #{variant.subscription_price_change_effective_date}")
end
variant
end
def has_variant_recurrences?
@has_variant_recurrences ||= category_params[:options].map { |variant| variant[:recurrence_price_values] }.any?
end
def save_recurring_prices!(variant, option)
if option[:recurrence_price_values].present?
variant.save_recurring_prices!(option[:recurrence_price_values].to_h)
end
end
def save_integrations(variant, option)
enabled_integrations = []
Integration::ALL_NAMES.each do |name|
integration = product.find_integration_by_name(name)
# TODO: :product_edit_react cleanup
if (option.dig(:integrations, name) == "1" || option.dig(:integrations, name) == true) && integration.present?
enabled_integrations << integration
end
end
deleted_integrations = variant.active_integrations - enabled_integrations
variant.live_base_variant_integrations.where(integration: deleted_integrations).map(&:mark_deleted!)
variant.active_integrations << enabled_integrations - variant.active_integrations
end
def save_rich_content(variant, option)
variant_rich_contents = option[:rich_content].is_a?(Array) ? option[:rich_content] : JSON.parse(option[:rich_content].presence || "[]", symbolize_names: true) || []
rich_contents_to_keep = []
existing_rich_contents = variant.alive_rich_contents.to_a
variant_rich_contents.each.with_index do |variant_rich_content, index|
rich_content = existing_rich_contents.find { |c| c.external_id == variant_rich_content[:id] } || variant.alive_rich_contents.build
variant_rich_content[:description] = SaveContentUpsellsService.new(
seller: variant.user,
content: variant_rich_content[:description] || variant_rich_content[:content],
old_content: rich_content.description || []
).from_rich_content
rich_content.update!(title: variant_rich_content[:title].presence, description: variant_rich_content[:description].presence || [], position: index)
rich_contents_to_keep << rich_content
end
(existing_rich_contents - rich_contents_to_keep).map(&:mark_deleted!)
end
# For tiered memberships that have per-tier pricing, validates that:
# 1. Any tiers that have "pay-what-you-want" pricing enabled have
# recurring price data and suggested prices are high enough
# 2. All tiers must have pricing info for the product's default recurrence
# 3. All tiers have the same set of recurrence options selected. (Currently
# we do not allow, e.g., Tier 1 to have monthly & yearly plans and Tier 2
# only to have yearly plans)
def validate_variant_recurrences!(variants)
return unless is_tiered_membership && has_variant_recurrences?
variants.each_with_index do |variant, index|
if variant[:customizable_price]
# error if "pay what you want" enabled but missing recurrence_price_values
if !variant[:recurrence_price_values].present?
errors.add(:base, "Please provide suggested payment options.")
raise Link::LinkInvalid, "Please provide suggested payment options."
end
# error if "pay what you want" enabled but suggested price is too low
variant[:recurrence_price_values].each do |recurrence, price_info|
if price_info[:suggested_price_cents].present? && (price_info[:price_cents].to_i > price_info[:suggested_price_cents].to_i)
errors.add(:base, "The suggested price you entered was too low.")
raise Link::LinkInvalid, "The suggested price you entered was too low."
end
end
end
# error if missing pricing info for the product's default recurrence
if product.subscription_duration.present? && (
!variant[:recurrence_price_values][product.subscription_duration.to_s].present? ||
!variant[:recurrence_price_values][product.subscription_duration.to_s][:enabled]
)
errors.add(:base, "Please provide a price for the default payment option.")
raise Link::LinkInvalid, "Please provide a price for the default payment option."
end
end
# error if variants have different recurrence options:
# 1. Extract variant recurrence selections:
# Ex. [["monthly", "yearly"], ["monthly"]]
enabled_recurrences_for_variants = variants.map do |variant|
variant[:recurrence_price_values].select { |k, v| v[:enabled] }.keys.sort
end
# 2. Ensure that they match
# Ex. ["monthly", "yearly"] != ["monthly"] raises error
enabled_recurrences_for_variants.each_with_index do |recurrences, index|
next_recurrences = enabled_recurrences_for_variants[index + 1]
if next_recurrences && recurrences != next_recurrences
errors.add(:base, "All tiers must have the same set of payment options.")
raise Link::LinkInvalid, "All tiers must have the same set of payment options."
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/save_post_purchase_custom_fields_service.rb | app/services/product/save_post_purchase_custom_fields_service.rb | # frozen_string_literal: true
class Product::SavePostPurchaseCustomFieldsService
NODE_TYPE_TO_FIELD_TYPE_MAPPING = CustomField::FIELD_TYPE_TO_NODE_TYPE_MAPPING.invert
def initialize(product)
@product = product
end
def perform
if @product.alive_variants.exists? && @product.not_has_same_rich_content_for_all_variants?
update_for_rich_contents(@product.alive_variants.map { _1.rich_contents.alive }.flatten)
else
update_for_rich_contents(@product.rich_contents.alive)
end
end
private
def update_for_rich_contents(rich_contents)
existing = @product.custom_fields.is_post_purchase
to_keep = []
rich_contents.each do |rich_content|
rich_content.custom_field_nodes.each do |node|
node["attrs"] ||= {}
field = (existing.find { _1.external_id == node["attrs"]["id"] }) || @product.custom_fields.build
field.update!(
seller: @product.user,
products: [@product],
name: node["attrs"]["label"],
field_type: NODE_TYPE_TO_FIELD_TYPE_MAPPING[node["type"]],
is_post_purchase: true
)
node["attrs"]["id"] = field.external_id
to_keep << field
end
rich_content.save!
end
(existing - to_keep).each(&:destroy!)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/save_integrations_service.rb | app/services/product/save_integrations_service.rb | # frozen_string_literal: true
class Product::SaveIntegrationsService
attr_reader :product, :integration_params
def self.perform(*args)
new(*args).perform
end
def initialize(product, integration_params = {})
@product = product
@integration_params = integration_params
end
def perform
enabled_integrations = []
if integration_params
Integration::ALL_NAMES.each do |name|
params_for_type = integration_params.dig(name)
if params_for_type
integration = product.find_integration_by_name(name)
integration_class = Integration.class_for(name)
integration = integration_class.new if integration.blank?
# TODO: :product_edit_react cleanup
integration_details = params_for_type.delete(:integration_details) || {}
integration.assign_attributes(
**params_for_type.slice(
*integration_class.connection_settings,
*integration_class::INTEGRATION_DETAILS,
),
**integration_details.slice(*integration_class::INTEGRATION_DETAILS)
)
integration.save!
enabled_integrations << integration
end
end
end
other_products_by_user = Link.where(user_id: product.user_id).alive.where.not(id: product.id).pluck(:id)
integrations_on_other_products = Integration.joins(:product_integration).where("product_integration.product_id" => other_products_by_user, "product_integration.deleted_at" => nil)
deleted_integrations = product.active_integrations - enabled_integrations
deletion_successful = product.live_product_integrations.where(integration: deleted_integrations).reduce(true) do |success, product_integration|
integration = product_integration.integration
same_connection_exists = integrations_on_other_products.find { |other_integration| integration.same_connection?(other_integration) }
disconnection_successful = same_connection_exists ? true : integration.disconnect!
if disconnection_successful
product_integration.mark_deleted
success
else
product.errors.add(:base, "Could not disconnect the #{integration.name.tr("_", " ")} integration, please try again.")
false
end
end
raise Link::LinkInvalid unless deletion_successful
product.active_integrations << enabled_integrations - product.active_integrations
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/bulk_update_support_email_service.rb | app/services/product/bulk_update_support_email_service.rb | # frozen_string_literal: true
class Product::BulkUpdateSupportEmailService
# @param entries [Array<Hash>]
# @option entries [String] :email
# @option entries [Array<String>] :product_ids
def initialize(user, entries)
@user = user
@entries = reject_blank_entries(entries)
end
def perform
return unless user.product_level_support_emails_enabled?
validate_entries!
ActiveRecord::Base.transaction do
clear_existing_support_emails!
set_new_support_emails!
end
end
private
attr_reader :user, :entries
def reject_blank_entries(entries)
Array.wrap(entries)
.reject { |entry| entry[:email]&.blank? || entry[:product_ids]&.blank? }
end
def affected_product_ids
@_affected_product_ids ||= entries.flat_map { |entry| entry[:product_ids] }
end
def validate_entries!
entries.each { |entry| validate_email!(entry[:email]) }
end
def validate_email!(email)
ReplicateSupportEmailValidationsOnLink.new(support_email: email).validate!
end
def clear_existing_support_emails!
@user.products
.where.not(id: affected_product_ids.map { Link.from_external_id(it) })
.where.not(support_email: nil)
.update_all(support_email: nil)
end
def set_new_support_emails!
entries.each do |entry|
user.products
.by_external_ids(entry[:product_ids])
.update_all(support_email: entry[:email])
end
end
class ReplicateSupportEmailValidationsOnLink
include ActiveModel::API
attr_accessor :support_email
validates :support_email, email_format: true, not_reserved_email_domain: true, allow_nil: true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/product/skus_updater_service.rb | app/services/product/skus_updater_service.rb | # frozen_string_literal: true
class Product::SkusUpdaterService
include CurrencyHelper
attr_reader :product, :skus_params
delegate :skus, :variant_categories, :price_currency_type, to: :product
def initialize(product:, skus_params: [])
@product = product
@skus_params = skus_params
end
def perform
return skus.not_is_default_sku.alive.map(&:mark_deleted!) if variant_categories.alive.empty?
previous_skus = skus.alive.to_a
skus_to_keep = skus.is_default_sku.to_a
variants_per_category = variant_categories.alive.map { |cat| cat.alive_variants.to_a }
variants_per_sku = variants_per_category.size > 1 ? variants_per_category.reduce(&:product) : variants_per_category.first.product
variants_per_sku.map do |variants|
variants.flatten!
sku_name = variants.map(&:name).join(" - ")
sku = variants.map(&:alive_skus).inject(:&).first
if sku&.alive? && sku.variants.sort == variants.sort
sku.update!(name: sku_name) if sku.name != sku_name
skus_to_keep << sku
else
sku = skus.build(name: sku_name)
sku.variants = variants
sku.save!
end
end
update_from_params!
(previous_skus - skus_to_keep).map(&:mark_deleted!)
end
private
def update_from_params!
skus_params.each do |sku_params|
begin
sku = skus.find_by_external_id!(sku_params[:id])
rescue ActiveRecord::RecordNotFound
product.errors.add(:base, "Please provide valid IDs for all SKUs.")
raise Link::LinkInvalid
end
price_difference_cents = string_to_price_cents(price_currency_type, sku_params[:price_difference])
max_purchase_count = sku_params[:max_purchase_count]
custom_sku = sku_params[:custom_sku] || sku.custom_sku
if sku.price_difference_cents != price_difference_cents || sku.max_purchase_count != max_purchase_count || sku.custom_sku != custom_sku
sku.update!(
price_difference_cents:,
max_purchase_count:,
custom_sku:,
)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/ssl_certificates/lets_encrypt.rb | app/services/ssl_certificates/lets_encrypt.rb | # frozen_string_literal: true
module SslCertificates
class LetsEncrypt < Base
CHALLENGE_TTL = 1.hour.to_i
attr_reader :domain, :certificate_private_key
def initialize(domain)
super()
@domain = domain
@certificate_private_key = OpenSSL::PKey::RSA.new(2048)
end
def process
order, http_challenge = order_certificate
prepare_http_challenge(http_challenge)
request_validation(http_challenge)
poll_validation_status(http_challenge)
begin
certificate = finalize_with_csr(order, http_challenge)
upload_certificate_to_s3(certificate, certificate_private_key)
rescue => e
log_message(domain, "SSL Certificate cannot be issued. Error: #{e.message}")
return false
ensure
delete_http_challenge(http_challenge)
end
true
end
private
def upload_certificate_to_s3(certificate, certificate_private_key)
cert_path = ssl_file_path(domain, "cert")
write_to_s3(cert_path, certificate.to_s)
private_key_path = ssl_file_path(domain, "key")
write_to_s3(private_key_path, certificate_private_key.to_s)
end
def finalize_with_csr(order, http_challenge)
csr = Acme::Client::CertificateRequest.new(private_key: certificate_private_key,
subject: { common_name: domain })
order.finalize(csr:)
max_retries.times do
break unless order.status == "processing"
sleep(sleep_duration)
http_challenge.reload
end
order.certificate
end
def poll_validation_status(http_challenge)
max_retries.times do
break unless http_challenge.status == "pending"
sleep(sleep_duration)
http_challenge.reload
end
end
def request_validation(http_challenge)
http_challenge.request_validation
end
def prepare_http_challenge(http_challenge)
token = http_challenge.token
file_content = http_challenge.file_content
$redis.setex(RedisKey.acme_challenge(token), CHALLENGE_TTL, file_content)
end
def delete_http_challenge(http_challenge)
token = http_challenge.token
$redis.del(RedisKey.acme_challenge(token))
end
def order_certificate
order = client.new_order(identifiers: [domain])
authorization = order.authorizations.first
[order, authorization.http]
end
def client
client = Acme::Client.new(private_key: account_private_key, directory: acme_url)
begin
cache_key = Digest::SHA256.hexdigest("#{account_private_key}-#{acme_url}")
Rails.cache.fetch("acme_account_status_#{cache_key}") { client.account.present? }
rescue Acme::Client::Error::AccountDoesNotExist
Rails.logger.info "Creating new ACME account - #{account_email}"
client.new_account(contact: "mailto:#{account_email}", terms_of_service_agreed: true)
end
client
end
def account_private_key
OpenSSL::PKey::RSA.new(ENV["LETS_ENCRYPT_ACCOUNT_PRIVATE_KEY"])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/ssl_certificates/renew.rb | app/services/ssl_certificates/renew.rb | # frozen_string_literal: true
module SslCertificates
class Renew < Base
def process
custom_domains = CustomDomain.alive.certificate_absent_or_older_than(renew_in)
custom_domains.each do |custom_domain|
custom_domain.generate_ssl_certificate
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/ssl_certificates/generate.rb | app/services/ssl_certificates/generate.rb | # frozen_string_literal: true
module SslCertificates
class Generate < Base
attr_reader :custom_domain
include ActionView::Helpers::DateHelper
def initialize(custom_domain)
super()
@custom_domain = custom_domain
@domain_verification_service = CustomDomainVerificationService.new(domain: custom_domain.domain)
end
def process
can_order_certificates, error_message = can_order_certificates?
if can_order_certificates
order_certificates
else
log_message(custom_domain.domain, error_message)
end
end
private
attr_reader :domain_verification_service
def order_certificates
domains_pointed_to_gumroad = domain_verification_service.domains_pointed_to_gumroad
all_certificates_generated = true
domains_pointed_to_gumroad.each do |domain|
# `&=` will set all_certificates_generated to false if generate_certificate()
# returns false for any of the domains.
all_certificates_generated &= generate_certificate(domain)
end
if all_certificates_generated
custom_domain.set_ssl_certificate_issued_at!
domains_pointed_to_gumroad.each { |domain| log_message(domain, "Issued SSL certificate.") }
else
# Reset ssl_certificate_issued_at
custom_domain.reset_ssl_certificate_issued_at!
# SSL certificate generation failed. Skip retrying for 1 day.
Rails.cache.write(domain_check_cache_key, false, expires_in: invalid_domain_cache_expires_in)
log_message(custom_domain.domain, "LetsEncrypt order failed. Next retry in #{time_ago_in_words(invalid_domain_cache_expires_in.from_now)}.")
end
end
def domain_check_cache_key
"domain_check_#{custom_domain.domain}"
end
def generate_certificate(domain)
certificate_authority.new(domain).process
end
def hourly_rate_limit_reached?
# Check if we have hit the rate limit.
# We don't have to add `.alive` scope here because we should count the deleted domain
# if a certificate was issued for it.
CustomDomain.certificates_younger_than(rate_limit_hours).count > rate_limit
end
def can_order_certificates?
return false, "Has valid certificate" if custom_domain.has_valid_certificate?(renew_in)
return false, "Hourly limit reached" if hourly_rate_limit_reached?
return false, "Invalid domain" unless custom_domain.valid?
Rails.cache.fetch(domain_check_cache_key, expires_in: invalid_domain_cache_expires_in) do
if domain_verification_service.points_to_gumroad?
return true
else
return false, "No domains pointed to Gumroad"
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/ssl_certificates/base.rb | app/services/ssl_certificates/base.rb | # frozen_string_literal: true
module SslCertificates
class Base
CONFIG_FILE = Rails.root.join("config", "ssl_certificates.yml.erb")
SECRETS_S3_BUCKET = "gumroad-secrets"
attr_reader :renew_in, :rate_limit, :acme_url, :sleep_duration, :rate_limit_hours,
:account_email, :max_retries, :ssl_env, :invalid_domain_cache_expires_in
def initialize
load_config
end
def self.supported_environment?
Rails.env.production? || (Rails.env.staging? && !ENV["BRANCH_DEPLOYMENT"])
end
def ssl_file_path(domain, filename)
"custom-domains-ssl/#{ssl_env}/#{domain}/ssl/#{filename}"
end
private
def certificate_authority
LetsEncrypt
end
def log_message(domain, message)
Rails.logger.info "[SSL Certificate Generator][#{domain}] #{message}"
end
def write_to_s3(key, content)
obj = s3_client.bucket(SECRETS_S3_BUCKET).object(key)
obj.put(body: content)
end
def delete_from_s3(key)
s3_client.bucket(SECRETS_S3_BUCKET).object(key).delete
end
def s3_client
@_s3_client ||= Aws::S3::Resource.new(credentials: Aws::InstanceProfileCredentials.new)
end
def convert_duration_to_seconds(duration)
duration.seconds
end
def load_config
config_erb = ERB.new(File.read(CONFIG_FILE)).result(binding)
config = YAML.load(config_erb, aliases: true).fetch(Rails.env)
@account_email = config["account_email"]
@acme_url = config["acme_url"]
@invalid_domain_cache_expires_in = convert_duration_to_seconds(config["invalid_domain_cache_expires_in"])
@max_retries = config["max_retries"]
@rate_limit = config["rate_limit"]
@rate_limit_hours = convert_duration_to_seconds(config["rate_limit_hours"])
@renew_in = convert_duration_to_seconds(config["renew_in"])
@sleep_duration = convert_duration_to_seconds(config["sleep_duration"])
@ssl_env = config["ssl_env"]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/follower/create_service.rb | app/services/follower/create_service.rb | # frozen_string_literal: true
class Follower::CreateService
delegate :followers, to: :followed_user
def self.perform(**args)
new(**args).perform
end
def initialize(followed_user:, follower_email:, follower_attributes: {}, logged_in_user: nil)
@followed_user = followed_user
@follower_email = follower_email
@follower_attributes = follower_attributes
@logged_in_user = logged_in_user
end
def perform
return if followed_user.blank? || follower_email.blank?
@follower = followers.find_by(email: follower_email)
if @follower.present?
reactivate_follower
else
create_new_follower
end
confirm_follower
@follower
end
private
attr_reader :followed_user, :follower_email, :follower_attributes, :logged_in_user
def reactivate_follower
@follower.mark_undeleted!
# some users start following and then create an account so look for [email, followed_id] index and update the follower_user_id
@follower.update(follower_attributes)
end
def create_new_follower
new_follower_attributes = follower_attributes.merge(email: follower_email)
@follower = followers.build(new_follower_attributes)
@follower.created_at = follower_attributes[:created_at] if follower_attributes.key?(:created_at)
begin
@follower.save!
rescue ActiveRecord::RecordNotUnique
ActiveRecord::Base.connection.stick_to_primary!
@follower = followers.find_by(email: follower_email)
reactivate_follower
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error("Cannot add follower to the database. Exception: #{e.message}")
Rails.logger.error(e.backtrace.join("\n"))
end
end
def confirm_follower
return false unless @follower.persisted? && @follower.valid?
if @follower.imported_from_csv? || active_session_with_verified_email?
@follower.confirm!
else
@follower.send_confirmation_email
end
end
def active_session_with_verified_email?
logged_in_user&.confirmed? && logged_in_user.email == follower_email
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/dispute_evidence/generate_uncategorized_text_service.rb | app/services/dispute_evidence/generate_uncategorized_text_service.rb | # frozen_string_literal: true
class DisputeEvidence::GenerateUncategorizedTextService
def self.perform(purchase)
new(purchase).perform
end
include ActionView::Helpers::NumberHelper
attr_reader :purchase
def initialize(purchase)
@purchase = purchase
end
def perform
rows = [
customer_location_text,
billing_zip_text,
previous_purchases_rows
].compact
rows.flatten.join("\n")
end
private
def customer_location_text
return if purchase.ip_state.blank?
"Device location: #{purchase.ip_state}, #{purchase.ip_country}"
end
def billing_zip_text
return if purchase.credit_card_zipcode.blank?
"Billing postal code: #{purchase.credit_card_zipcode}"
end
# Evidence of one or more non-disputed payments on the same card
def previous_purchases_rows
previous_purchases = find_previous_purchases
return if previous_purchases.none?
rows = []
rows << "\nPrevious undisputed #{"purchase".pluralize(previous_purchases.count)} on Gumroad:"
previous_purchases.each do |other_purchase|
rows << previous_purchases_text(other_purchase)
end
rows
end
def previous_purchases_text(other_purchase)
device_location = build_device_location(other_purchase)
[
other_purchase.created_at,
MoneyFormatter.format(other_purchase.total_transaction_cents, :usd),
other_purchase.full_name&.strip,
other_purchase.email,
("Billing postal code: #{other_purchase.credit_card_zipcode}" if other_purchase.credit_card_zipcode.present?),
("Device location: #{device_location}" if device_location.present?),
].compact.join(", ")
end
def build_device_location(purchase)
[purchase.ip_address, purchase.ip_state, purchase.ip_country].compact.join(", ").presence
end
def find_previous_purchases
Purchase.successful
.not_fully_refunded
.not_chargedback
.where(stripe_fingerprint: purchase.stripe_fingerprint)
.where.not(id: purchase.id)
.order(created_at: :desc)
.limit(10)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/dispute_evidence/generate_receipt_image_service.rb | app/services/dispute_evidence/generate_receipt_image_service.rb | # frozen_string_literal: true
class DisputeEvidence::GenerateReceiptImageService
def self.perform(purchase)
new(purchase).perform
end
def initialize(purchase)
@purchase = purchase
end
def perform
binary_data = generate_screenshot
unless binary_data
Bugsnag.notify("DisputeEvidence::GenerateRefundPolicyImageService: Could not generate screenshot for purchase ID #{purchase.id}")
return
end
optimize_image(binary_data)
end
private
CHROME_ARGS = [
"headless",
"no-sandbox",
"disable-setuid-sandbox",
"disable-dev-shm-usage",
"user-data-dir=/tmp/chrome",
"disable-scrollbars"
].freeze
BREAKPOINT_LG = 1024
IMAGE_RESIZE_FACTOR = 2
IMAGE_QUALITY = 80
attr_reader :purchase
attr_accessor :width
def generate_screenshot
options = Selenium::WebDriver::Chrome::Options.new(args: CHROME_ARGS)
driver = Selenium::WebDriver.for(:chrome, options:)
html = generate_html(purchase)
encoded_content = Addressable::URI.encode_component(html, Addressable::URI::CharacterClasses::QUERY)
driver.navigate.to "data:text/html;charset=UTF-8,#{encoded_content}"
# Use a fixed width in order to have a consistent way to determine if is a retina display screenshot
@width = BREAKPOINT_LG
height = driver.execute_script(js_max_height_dimension)
driver.manage.window.size = Selenium::WebDriver::Dimension.new(width, height)
driver.screenshot_as(:png)
ensure
driver.quit if driver.present?
end
def js_max_height_dimension
%{
return Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.clientHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
}
end
def generate_html(purchase)
mail = CustomerMailer.receipt(purchase.id)
mail_body = Nokogiri::HTML.parse(mail.body.raw_source)
mail_info = %{
<div style="padding: 20px 20px">
<p><strong>Email receipt sent at:</strong> #{purchase.created_at}</p>
<p><strong>From:</strong> #{mail.from.first}</p>
<p><strong>To:</strong> #{mail.to.first}</p>
<p><strong>Subject:</strong> #{mail.subject}</p>
</div>
<hr>
}
mail_body.at("body").prepend_child Nokogiri::HTML::DocumentFragment.parse(mail_info)
mail_body.to_html
end
def optimize_image(binary_data)
image = MiniMagick::Image.read(binary_data)
image.resize("#{image.width / IMAGE_RESIZE_FACTOR}x") if retina_display_screenshot?(image)
image.format("jpg").quality(IMAGE_QUALITY).strip
image.to_blob
end
def retina_display_screenshot?(image)
image.width == width * IMAGE_RESIZE_FACTOR
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/dispute_evidence/create_from_dispute_service.rb | app/services/dispute_evidence/create_from_dispute_service.rb | # frozen_string_literal: true
# Create a dispute_evidence record that will be submitted to Stripe
# Note that all files associated must not exceed 5MB
# https://support.stripe.com/questions/evidence-submission-troubleshooting-faq
#
class DisputeEvidence::CreateFromDisputeService
include ProductsHelper
def initialize(dispute)
@dispute = dispute
@purchase = dispute.disputable.purchase_for_dispute_evidence
end
def perform!
product = purchase.link.paper_trail.version_at(purchase.created_at) || purchase.link
shipment = purchase.shipment
refund_policy_fine_print_view_events = find_refund_policy_fine_print_view_events(purchase)
dispute_evidence = dispute.build_dispute_evidence
dispute_evidence.purchased_at = purchase.created_at
dispute_evidence.customer_purchase_ip = purchase.ip_address
dispute_evidence.customer_email = purchase.email
dispute_evidence.customer_name = purchase.full_name&.strip
dispute_evidence.billing_address = build_billing_address(purchase)
if shipment.present?
dispute_evidence.shipping_address = dispute_evidence.billing_address
dispute_evidence.shipped_at = shipment.shipped_at
dispute_evidence.shipping_carrier = shipment.carrier
dispute_evidence.shipping_tracking_number = shipment.tracking_number
end
dispute_evidence.product_description = generate_product_description(product:, purchase:)
dispute_evidence.uncategorized_text = DisputeEvidence::GenerateUncategorizedTextService.perform(purchase)
dispute_evidence.access_activity_log = DisputeEvidence::GenerateAccessActivityLogsService.perform(purchase)
attach_receipt_image(dispute_evidence, purchase)
dispute_evidence.policy_disclosure = generate_refund_policy_disclosure(purchase, refund_policy_fine_print_view_events)
attach_refund_policy_image(dispute_evidence, purchase, open_fine_print_modal: refund_policy_fine_print_view_events.any?)
dispute_evidence.save!
if dispute_evidence.customer_communication_file_max_size < DisputeEvidence::MINIMUM_RECOMMENDED_CUSTOMER_COMMUNICATION_FILE_SIZE
Bugsnag.notify(
"DisputeEvidence::CreateFromDisputeService - Allowed file size on dispute evidence #{dispute_evidence.id} for " \
"customer_communication_file is too low: " + number_to_human_size(dispute_evidence.customer_communication_file_max_size)
)
end
dispute_evidence
end
private
attr_reader :dispute, :purchase
def build_billing_address(purchase)
fields = %w(street_address city state zip_code country)
fields.map { |field| purchase.send(field) }.compact.join(", ")
end
def generate_product_description(product:, purchase:)
type = product.native_type || Link::NATIVE_TYPE_DIGITAL
rows = []
rows << "Product name: #{product.name}"
rows << "Product as seen when purchased: #{Rails.application.routes.url_helpers.purchase_product_url(purchase.external_id, host: DOMAIN, protocol: PROTOCOL)}"
rows << "Product type: #{product.is_physical? ? "physical product" : type}"
rows << "Product variant: #{variant_names_displayable(purchase.variant_names)}" if purchase.variant_names.present?
rows << "Quantity purchased: #{purchase.quantity}" if purchase.quantity > 1
rows << "Receipt: #{purchase.receipt_url}"
rows << "Live product: #{purchase.link.long_url}"
rows.join("\n")
end
def attach_receipt_image(dispute_evidence, purchase)
image = DisputeEvidence::GenerateReceiptImageService.perform(purchase)
unless image
Bugsnag.notify("CreateFromDisputeService: Could not generate receipt_image for purchase ID #{purchase.id}")
return
end
dispute_evidence.receipt_image.attach(
io: StringIO.new(image),
filename: "receipt_image.jpg",
content_type: "image/jpeg"
)
end
def generate_refund_policy_disclosure(purchase, events)
return if events.none?
"The refund policy modal has been viewed by the customer #{events.count} #{"time".pluralize(events.count)}" \
" before the purchase was made at #{purchase.created_at}.\n" \
"Timestamp information of the #{"view".pluralize(events.count)}: #{events.map(&:created_at).join(", ")}\n\n" \
"Internal browser GUID for reference: #{purchase.browser_guid}"
end
def attach_refund_policy_image(dispute_evidence, purchase, open_fine_print_modal:)
return unless purchase.purchase_refund_policy.present?
url = Rails.application.routes.url_helpers.purchase_product_url(
purchase.external_id,
host: DOMAIN,
protocol: PROTOCOL,
anchor: open_fine_print_modal ? "refund-policy" : nil
)
binary_data = DisputeEvidence::GenerateRefundPolicyImageService.perform(
url:,
mobile_purchase: mobile_purchase?,
open_fine_print_modal:,
max_size_allowed: dispute_evidence.policy_image_max_size
)
dispute_evidence.policy_image.attach(
io: StringIO.new(binary_data),
filename: "refund_policy.jpg",
content_type: "image/jpeg"
)
rescue DisputeEvidence::GenerateRefundPolicyImageService::ImageTooLargeError
Bugsnag.notify("DisputeEvidence::CreateFromDisputeService (purchase #{purchase.id}): Refund policy image not attached because was too large")
end
def mobile_purchase?
purchase.is_mobile?
end
def find_refund_policy_fine_print_view_events(purchase)
@_events ||= Event.where(link_id: purchase.link_id)
.where(browser_guid: purchase.browser_guid)
.where("created_at < ?", purchase.created_at)
.where(event_name: Event::NAME_PRODUCT_REFUND_POLICY_FINE_PRINT_VIEW)
.order(id: :asc)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/dispute_evidence/generate_refund_policy_image_service.rb | app/services/dispute_evidence/generate_refund_policy_image_service.rb | # frozen_string_literal: true
class DisputeEvidence::GenerateRefundPolicyImageService
class ImageTooLargeError < StandardError; end
def self.perform(url:, mobile_purchase:, open_fine_print_modal:, max_size_allowed:)
new(url, mobile_purchase:, open_fine_print_modal:, max_size_allowed:).perform
end
def initialize(url, mobile_purchase:, open_fine_print_modal:, max_size_allowed:)
@url = url
@open_fine_print_modal = open_fine_print_modal
@max_size_allowed = max_size_allowed
@width = mobile_purchase ? BREAKPOINT_SM : BREAKPOINT_LG
end
def perform
binary_data = generate_screenshot
unless binary_data
Bugsnag.notify("DisputeEvidence::GenerateRefundPolicyImageService: Could not generate screenshot for url #{url}")
return
end
optimized_binary_data = optimize_image(binary_data)
image = MiniMagick::Image.read(binary_data)
raise ImageTooLargeError if image.size > max_size_allowed
optimized_binary_data
end
private
CHROME_ARGS = [
"headless",
"no-sandbox",
"disable-setuid-sandbox",
"disable-dev-shm-usage",
"user-data-dir=/tmp/chrome",
"disable-scrollbars"
].freeze
# Should match $breakpoints definitions from app/javascript/stylesheets/_definitions.scss
BREAKPOINT_SM = 640
BREAKPOINT_LG = 1024
IMAGE_RESIZE_FACTOR = 2
IMAGE_QUALITY = 80
attr_reader :url, :width, :open_fine_print_modal, :max_size_allowed
def generate_screenshot
options = Selenium::WebDriver::Chrome::Options.new(args: CHROME_ARGS)
driver = Selenium::WebDriver.for(:chrome, options:)
# Height will be adjusted after the page is loaded
driver.manage.window.size = Selenium::WebDriver::Dimension.new(width, width)
driver.navigate.to url
# Ensures the page is fully loaded, especially when we want to render with the refund policy modal open.
wait = Selenium::WebDriver::Wait.new(timeout: 10)
wait.until { driver.execute_script("return document.readyState") == "complete" }
height = calculate_height(driver, open_fine_print_modal:)
driver.manage.window.size = Selenium::WebDriver::Dimension.new(width, height)
driver.screenshot_as(:png)
ensure
driver.quit if driver.present?
end
def calculate_height(driver, open_fine_print_modal:)
document_height = driver.execute_script(js_max_height_dimension)
if open_fine_print_modal
modal_height = driver.execute_script(%{ return document.querySelector("dialog").scrollHeight; })
[modal_height, document_height].max
else
# We need to calculate the height of the content, plus the padding added by the parent element
content_height = driver.execute_script(%{ return document.querySelector("article").parentElement.scrollHeight; })
[content_height, document_height].max
end
end
def js_max_height_dimension
%{
return Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.clientHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight,
);
}
end
def optimize_image(binary_data)
image = MiniMagick::Image.read(binary_data)
image.resize("#{image.width / IMAGE_RESIZE_FACTOR}x") if retina_display_screenshot?(image)
image.format("jpg").quality(IMAGE_QUALITY).strip
image.to_blob
end
def retina_display_screenshot?(image)
image.width == width * IMAGE_RESIZE_FACTOR
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/dispute_evidence/generate_access_activity_logs_service.rb | app/services/dispute_evidence/generate_access_activity_logs_service.rb | # frozen_string_literal: true
class DisputeEvidence::GenerateAccessActivityLogsService
def self.perform(purchase)
new(purchase).perform
end
include ActionView::Helpers::NumberHelper
def initialize(purchase)
@purchase = purchase
@url_redirect = purchase.url_redirect
end
def perform
[
email_activity,
rental_activity,
usage_activity,
].compact.join("\n\n").presence
end
private
attr_reader :purchase, :url_redirect
def rental_activity
return unless url_redirect.present? && url_redirect.rental_first_viewed_at.present?
"The rented content was first viewed at #{url_redirect.rental_first_viewed_at}."
end
def usage_activity
if consumption_events.any?
generate_from_consumption_events
elsif url_redirect.present? && url_redirect.uses.to_i.positive?
generate_from_url_redirect
else
nil
end
end
def consumption_events
@_consumption_events ||= purchase.consumption_events.order(:consumed_at, :id)
end
def generate_from_url_redirect
"The customer accessed the product #{url_redirect.uses} #{"time".pluralize(url_redirect.uses)}."
end
LOG_RECORDS_LIMIT = 10
def generate_from_consumption_events
[
consumption_events_intro,
consumption_event_row_attributes.join(","),
consumption_event_rows
].flatten.join("\n")
end
def consumption_event_row_attributes
%w(consumed_at event_type platform ip_address)
end
def consumption_event_rows
consumption_events.first(LOG_RECORDS_LIMIT).map do
_1.slice(*consumption_event_row_attributes).values.join(",")
end
end
def consumption_events_intro
count = consumption_events.count
content = "The customer accessed the product #{count} #{"time".pluralize(count)}."
if count > LOG_RECORDS_LIMIT
content << " Most recent #{LOG_RECORDS_LIMIT} log records:"
end
content << "\n"
end
def email_activity
receipt_email_info = purchase.receipt_email_info
return unless receipt_email_info.present? && receipt_email_info.sent_at.present?
content = "The receipt email was sent at #{receipt_email_info.sent_at}"
content << ", delivered at #{receipt_email_info.delivered_at}" if receipt_email_info.delivered_at.present?
content << ", opened at #{receipt_email_info.opened_at}" if receipt_email_info.opened_at.present?
content << "."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/pdf_stamping_service/upload_to_s3.rb | app/services/pdf_stamping_service/upload_to_s3.rb | # frozen_string_literal: true
# Upload the stamped PDF to S3
module PdfStampingService::UploadToS3
extend self
def perform!(product_file:, stamped_pdf_path:)
guid = SecureRandom.hex
path = "attachments/#{guid}/original/#{File.basename(product_file.s3_url)}"
Aws::S3::Resource.new.bucket(S3_BUCKET).object(path).upload_file(
stamped_pdf_path,
content_type: "application/pdf"
)
"#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{path}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/pdf_stamping_service/stamp_for_purchase.rb | app/services/pdf_stamping_service/stamp_for_purchase.rb | # frozen_string_literal: true
module PdfStampingService::StampForPurchase
extend self
def perform!(purchase)
product = purchase.link
return unless product.has_stampable_pdfs?
url_redirect = UrlRedirect.find(purchase.url_redirect.id)
product_files_to_stamp = find_products_to_stamp(product, url_redirect)
results = Set.new
product_files_to_stamp.each do |product_file|
results << process_product_file(url_redirect:, product_file:, watermark_text: purchase.email)
end
failed_results = results.reject(&:success?)
if failed_results.none?
url_redirect.update!(is_done_pdf_stamping: true)
true
else
debug_info = failed_results.map do |result|
"File #{result.product_file_id}: #{result.error[:class]}: #{result.error[:message]}"
end.join("\n")
raise PdfStampingService::Error, "Failed to stamp #{failed_results.size} file(s) for purchase #{purchase.id} - #{debug_info}"
end
end
private
def find_products_to_stamp(product, url_redirect)
product.product_files
.alive
.pdf
.pdf_stamp_enabled
.where.not(id: url_redirect.alive_stamped_pdfs.pluck(:product_file_id))
end
def process_product_file(url_redirect:, product_file:, watermark_text:)
stamped_pdf_url = stamp_and_upload!(product_file:, watermark_text:)
url_redirect.stamped_pdfs.create!(product_file:, url: stamped_pdf_url)
OpenStruct.new(success?: true)
rescue *PdfStampingService::ERRORS_TO_RESCUE => error
OpenStruct.new(
success?: false,
product_file_id: product_file.id,
error: {
class: error.class.name,
message: error.message
}
)
end
def stamp_and_upload!(product_file:, watermark_text:)
return if product_file.cannot_be_stamped?
stamped_pdf_path = PdfStampingService::Stamp.perform!(product_file:, watermark_text:)
PdfStampingService::UploadToS3.perform!(product_file:, stamped_pdf_path:)
ensure
File.unlink(stamped_pdf_path) if File.exist?(stamped_pdf_path.to_s)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/pdf_stamping_service/stamp.rb | app/services/pdf_stamping_service/stamp.rb | # frozen_string_literal: true
module PdfStampingService::Stamp
class Error < StandardError; end
extend self
def can_stamp_file?(product_file:)
stamped_pdf_path = perform!(product_file:, watermark_text: "noop@gumroad.com")
true # We don't actually do anything with the file, we just wanted to check that we could create it.
rescue *PdfStampingService::ERRORS_TO_RESCUE => e
Rails.logger.info("[#{name}.#{__method__}] Failed stamping #{product_file.id}: #{e.class} => #{e.message}")
false
ensure
File.unlink(stamped_pdf_path) if File.exist?(stamped_pdf_path.to_s)
end
def perform!(product_file:, watermark_text:)
product_file.download_original do |original_pdf|
original_pdf_path = original_pdf.path
original_pdf_path_shellescaped = Shellwords.shellescape(original_pdf_path)
watermark_pdf_path = create_watermark_pdf!(original_pdf_path:, watermark_text:)
watermark_pdf_path_shellescaped = Shellwords.shellescape(watermark_pdf_path)
stamped_pdf_file_name = build_stamped_pdf_file_name(product_file)
stamped_pdf_path = "#{Dir.tmpdir}/#{stamped_pdf_file_name}"
stamped_pdf_path_shellescaped = Shellwords.shellescape(stamped_pdf_path)
apply_watermark!(
original_pdf_path_shellescaped,
watermark_pdf_path_shellescaped,
stamped_pdf_path_shellescaped
)
stamped_pdf_path
ensure
File.unlink(watermark_pdf_path) if File.exist?(watermark_pdf_path.to_s)
end
end
private
def build_stamped_pdf_file_name(product_file)
extname = File.extname(product_file.s3_url)
basename = File.basename(product_file.s3_url, extname)
random_marker = SecureRandom.hex
stamped_pdf_file_name = "#{basename}_#{random_marker}#{extname}"
if stamped_pdf_file_name.bytesize > MAX_FILE_NAME_BYTESIZE
truncated_basename_bytesize = MAX_FILE_NAME_BYTESIZE - extname.bytesize - random_marker.bytesize - 1 # 1 added underscore
truncated_basename = basename.truncate_bytes(truncated_basename_bytesize, omission: nil)
stamped_pdf_file_name = "#{truncated_basename}_#{random_marker}#{extname}"
end
stamped_pdf_file_name
end
def create_watermark_pdf!(original_pdf_path:, watermark_text:)
# Get the dimensions of original pdf's first page
reader = PDF::Reader.new(original_pdf_path)
begin
first_page = reader.page(1)
rescue NoMethodError
raise PDF::Reader::MalformedPDFError
end
media_box = first_page.attributes[:MediaBox]
# Sometimes we see corrupt PDFs without the mandated MediaBox attribute which causes an error, so assume
# that PDF is 8.5x11 portrait and place stamp at "bottom right". If PDF is landscape, it is a little centered.
if media_box.is_a?(Array)
width = media_box[2] - media_box[0]
height = media_box[3] - media_box[1]
else
# width and height of 8.5x11 portrait page
width = 612.0
height = 792.0
end
# The origin is at the bottom-left
watermark_x = width - 356
watermark_y = 50
watermark_pdf_path = "#{Dir.tmpdir}/watermark_#{SecureRandom.hex}_#{Digest::SHA1.hexdigest(watermark_text)}.pdf"
pdf = Prawn::Document.new(page_size: [width, height], margin: 0)
# TODO(s3ththompson): Remove subset: false once https://github.com/prawnpdf/prawn/issues/1361 is fixed
pdf.font_families.update(
"ABC Favorit" => {
normal: { file: Rails.root.join("app", "assets", "fonts", "ABCFavorit", "ttf", "ABCFavorit-Regular.ttf"), subset: false },
italic: { file: Rails.root.join("app", "assets", "fonts", "ABCFavorit", "ttf", "ABCFavorit-RegularItalic.ttf"), subset: false },
bold: { file: Rails.root.join("app", "assets", "fonts", "ABCFavorit", "ttf", "ABCFavorit-Bold.ttf"), subset: false },
bold_italic: { file: Rails.root.join("app", "assets", "fonts", "ABCFavorit", "ttf", "ABCFavorit-BoldItalic.ttf"), subset: false }
}
)
pdf.fill_color "C1C1C1"
pdf.font("ABC Favorit", style: :bold)
pdf.text_box("Sold to", at: [watermark_x, watermark_y], width: 300, align: :right, size: 11, fallback_fonts: %w[Helvetica])
pdf.fill_color "C1C1C1"
pdf.font("ABC Favorit", style: :normal)
pdf.text_box(watermark_text, at: [watermark_x, watermark_y - 14], width: 300, align: :right, size: 11, fallback_fonts: %w[Helvetica])
pdf.image("#{Rails.root}/app/assets/images/pdf_stamp.png", at: [watermark_x + 305, watermark_y], width: 24)
# pdftk stamps all pages by default, repeating the last page of the stamp until the end of the original pdf.
pdf.render_file(watermark_pdf_path)
watermark_pdf_path
end
def apply_watermark!(original_pdf_path_shellescaped, watermark_pdf_path_shellescaped, stamped_pdf_path_shellescaped)
command = "pdftk #{original_pdf_path_shellescaped} multistamp #{watermark_pdf_path_shellescaped} output #{stamped_pdf_path_shellescaped}"
stdout, stderr, status = Open3.capture3(command)
return if status.success?
Rails.logger.error("[#{name}.#{__method__}] Failed to execute command: #{command}")
Rails.logger.error("[#{name}.#{__method__}] STDOUT: #{stdout}")
Rails.logger.error("[#{name}.#{__method__}] STDERR: #{stderr}")
error_message = parse_error_message(stdout, stderr)
raise Error, "Error generating stamped PDF: #{error_message}"
end
def parse_error_message(stdout, stderr)
if stderr.include?("unknown.encryption.type")
"PDF is encrypted."
else
stderr.split("\n").first
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/admin/unreviewed_users_service.rb | app/services/admin/unreviewed_users_service.rb | # frozen_string_literal: true
class Admin::UnreviewedUsersService
MINIMUM_BALANCE_CENTS = 1000
DEFAULT_CUTOFF_DATE = "2024-01-01"
MAX_CACHED_USERS = 1000
def cutoff_date
@cutoff_date ||= self.class.cutoff_date
end
def self.cutoff_date
date_str = $redis.get(RedisKey.unreviewed_users_cutoff_date) || DEFAULT_CUTOFF_DATE
Date.parse(date_str)
end
def count
base_scope.count.size
end
def users_with_unpaid_balance(limit: nil)
scope = base_scope
.order(Arel.sql("SUM(balances.amount_cents) DESC"))
.select("users.*, SUM(balances.amount_cents) AS total_balance_cents")
limit ? scope.limit(limit) : scope
end
def self.cached_users_data
data = $redis.get(RedisKey.unreviewed_users_data)
return nil unless data
JSON.parse(data, symbolize_names: true)
end
def self.cache_users_data!
service = new
users = service.users_with_unpaid_balance(limit: MAX_CACHED_USERS)
users_data = users.map do |user|
Admin::UnreviewedUserPresenter.new(user).props
end
cache_payload = {
users: users_data,
total_count: service.count,
cutoff_date: service.cutoff_date.to_s,
cached_at: Time.current.iso8601
}
$redis.set(RedisKey.unreviewed_users_data, cache_payload.to_json)
cache_payload
end
private
def base_scope
User
.joins(:balances)
.where(user_risk_state: "not_reviewed")
.where("users.created_at >= ?", cutoff_date)
.merge(Balance.unpaid)
.group("users.id")
.having("SUM(balances.amount_cents) > ?", MINIMUM_BALANCE_CENTS)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/following.rb | app/services/creator_analytics/following.rb | # frozen_string_literal: true
class CreatorAnalytics::Following
include ConfirmedFollowerEvent::Events
attr_reader :user
def initialize(user)
@user = user
end
def by_date(start_date:, end_date:)
dates = (start_date .. end_date).to_a
today_in_time_zone = Time.current.in_time_zone(user.timezone).to_date
stored_first_follower_date = first_follower_date
counts_data = stored_first_follower_date ? counts(dates) : zero_counts(dates)
{
dates: D3.date_domain(dates),
start_date: D3.formatted_date(start_date, today_date: today_in_time_zone),
end_date: D3.formatted_date(end_date, today_date: today_in_time_zone),
by_date: counts_data,
first_follower_date: (D3.formatted_date(stored_first_follower_date, today_date: today_in_time_zone) if stored_first_follower_date),
new_followers: counts_data.fetch(:new_followers).sum - counts_data.fetch(:followers_removed).sum,
}
end
# This method is used for displaying the running total of followers.
# net_total = added - removed
def net_total(before_date: nil)
must = [{ range: { timestamp: { time_zone: user.timezone_id, lt: before_date.to_s } } }] if before_date
aggs = ADDED_AND_REMOVED.index_with do |name|
{ filter: { term: { name: } }, aggs: { count: { value_count: { field: "name" } } } }
end
body = {
query: { bool: { filter: [{ term: { followed_user_id: user.id } }], must: } },
aggs:,
size: 0
}
aggregations = ConfirmedFollowerEvent.search(body).aggregations
added_count, removed_count = ADDED_AND_REMOVED.map do |name|
aggregations.dig(name, :count, :value) || 0
end
added_count - removed_count
end
def first_follower_date
body = {
query: { bool: { filter: [{ term: { followed_user_id: user.id } }] } },
sort: [{ timestamp: { order: :asc } }],
_source: [:timestamp],
size: 1
}
result = ConfirmedFollowerEvent.search(body).results.first
return if result.nil?
Time.parse(result._source.timestamp).in_time_zone(user.timezone).to_date
end
private
# Returns hash of arrays for followers added, removed, and running net total from the start, for each day.
def counts(dates)
start_date, end_date = dates.first, dates.last
names_aggs = ADDED_AND_REMOVED.index_with do |name|
{ filter: { term: { name: } }, aggs: { count: { value_count: { field: "name" } } } }
end
body = {
query: {
bool: {
filter: [{ term: { followed_user_id: user.id } }],
must: [{ range: { timestamp: { time_zone: user.timezone_id, gte: start_date.to_s, lte: end_date.to_s } } }]
}
},
aggs: {
dates: {
date_histogram: { time_zone: user.timezone_id, field: "timestamp", calendar_interval: "day" },
aggs: names_aggs
}
},
size: 0
}
aggs_by_date = ConfirmedFollowerEvent.search(body).aggregations.dates.buckets.each_with_object({}) do |bucket, hash|
hash[Date.parse(bucket["key_as_string"])] = ADDED_AND_REMOVED.index_with do |name|
bucket.dig(name, :count, :value) || 0
end
end
net_total_before_start_date = net_total(before_date: start_date)
result = { new_followers: [], followers_removed: [], totals: [] }
(start_date .. end_date).each do |date|
result[:new_followers] << (aggs_by_date.dig(date, ADDED) || 0)
result[:followers_removed] << (aggs_by_date.dig(date, REMOVED) || 0)
result[:totals] << ((result[:totals].last || net_total_before_start_date) + result[:new_followers].last - result[:followers_removed].last)
end
result
end
# same as `#counts`, but with zero for every day
def zero_counts(dates)
zeros = [0] * dates.size
{ new_followers: zeros, followers_removed: zeros, totals: zeros }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/product_page_views.rb | app/services/creator_analytics/product_page_views.rb | # frozen_string_literal: true
class CreatorAnalytics::ProductPageViews
def initialize(user:, products:, dates:)
@user = user
@products = products
@dates = dates
@query = {
bool: {
filter: [{ terms: { product_id: @products.map(&:id) } }],
must: [{ range: { timestamp: { time_zone: @user.timezone_id, gte: @dates.first.to_s, lte: @dates.last.to_s } } }]
}
}
end
def by_product_and_date
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ date: { date_histogram: { time_zone: @user.timezone_id, field: "timestamp", calendar_interval: "day", format: "yyyy-MM-dd" } } }
]
paginate(sources:).each_with_object({}) do |bucket, result|
key = [
bucket["key"]["product_id"],
bucket["key"]["date"]
]
result[key] = bucket["doc_count"]
end
end
def by_product_and_country_and_state
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ country: { terms: { field: "country", missing_bucket: true } } },
{ state: { terms: { field: "state", missing_bucket: true } } }
]
paginate(sources:).each_with_object({}) do |bucket, result|
key = [
bucket["key"]["product_id"],
bucket["key"]["country"].presence,
bucket["key"]["state"].presence,
]
result[key] = bucket["doc_count"]
end
end
def by_product_and_referrer_and_date
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ referrer_domain: { terms: { field: "referrer_domain" } } },
{ date: { date_histogram: { time_zone: @user.timezone_id, field: "timestamp", calendar_interval: "day", format: "yyyy-MM-dd" } } }
]
paginate(sources:).each_with_object(Hash.new(0)) do |bucket, hash|
key = [
bucket["key"]["product_id"],
bucket["key"]["referrer_domain"],
bucket["key"]["date"],
]
hash[key] = bucket["doc_count"]
end
end
private
def paginate(sources:)
after_key = nil
body = build_body(sources)
buckets = []
loop do
body[:aggs][:composite_agg][:composite][:after] = after_key if after_key
response_agg = ProductPageView.search(body).aggregations.composite_agg
buckets += response_agg.buckets
break if response_agg.buckets.size < ES_MAX_BUCKET_SIZE
after_key = response_agg["after_key"]
end
buckets
end
def build_body(sources)
{
query: @query,
size: 0,
aggs: { composite_agg: { composite: { size: ES_MAX_BUCKET_SIZE, sources: } } }
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/web.rb | app/services/creator_analytics/web.rb | # frozen_string_literal: true
class CreatorAnalytics::Web
def initialize(user:, dates:)
@user = user
@dates = dates
end
def by_date
views_data = product_page_views.by_product_and_date
sales_data = sales.by_product_and_date
result = result_metadata
result[:by_date] = { views: {}, sales: {}, totals: {} }
%i[views sales totals].each do |type|
product_permalinks.each do |product_id, product_permalink|
result[:by_date][type][product_permalink] = dates_strings.map do |date|
case type
when :views then views_data[[product_id, date]]
when :sales then sales_data.dig([product_id, date], :count)
when :totals then sales_data.dig([product_id, date], :total)
end || 0
end
end
end
result
end
def by_state
views_data = product_page_views.by_product_and_country_and_state
sales_data = sales.by_product_and_country_and_state
result = { by_state: { views: {}, sales: {}, totals: {} } }
usa = "United States"
%i[views sales totals].each do |type|
product_permalinks.each do |product_id, product_permalink|
result[:by_state][type][product_permalink] = { usa => [0] * STATES_SUPPORTED_BY_ANALYTICS.size }
end
end
views_data.each do |(product_id, country, state), count|
product_permalink = product_permalinks[product_id]
if country == usa
state_index = STATES_SUPPORTED_BY_ANALYTICS.index(state)
state_index = STATES_SUPPORTED_BY_ANALYTICS.index(STATE_OTHER) if state_index.blank?
result[:by_state][:views][product_permalink][country][state_index] += count
else
result[:by_state][:views][product_permalink][country] ||= 0
result[:by_state][:views][product_permalink][country] += count
end
end
sales_data.each do |(product_id, country, state), values|
product_permalink = product_permalinks[product_id]
if country == usa
state_index = STATES_SUPPORTED_BY_ANALYTICS.index(state)
state_index = STATES_SUPPORTED_BY_ANALYTICS.index(STATE_OTHER) if state_index.blank?
result[:by_state][:sales][product_permalink][country][state_index] += values[:count]
result[:by_state][:totals][product_permalink][country][state_index] += values[:total]
else
result[:by_state][:sales][product_permalink][country] ||= 0
result[:by_state][:sales][product_permalink][country] += values[:count]
result[:by_state][:totals][product_permalink][country] ||= 0
result[:by_state][:totals][product_permalink][country] += values[:total]
end
end
result
end
def by_referral
views_data = product_page_views.by_product_and_referrer_and_date
sales_data = sales.by_product_and_referrer_and_date
result = result_metadata
result[:by_referral] = { views: {}, sales: {}, totals: {} }
views_data.each do |(product_id, referrer, date), count|
product_permalink = product_permalinks[product_id]
referrer_name = referrer_domain_to_name(referrer)
result[:by_referral][:views][product_permalink] ||= {}
result[:by_referral][:views][product_permalink][referrer_name] ||= [0] * dates_strings.size
result[:by_referral][:views][product_permalink][referrer_name][dates_strings.index(date)] = count
end
sales_data.each do |(product_id, referrer, date), values|
product_permalink = product_permalinks[product_id]
referrer_name = referrer_domain_to_name(referrer)
result[:by_referral][:sales][product_permalink] ||= {}
result[:by_referral][:sales][product_permalink][referrer_name] ||= [0] * dates_strings.size
result[:by_referral][:sales][product_permalink][referrer_name][dates_strings.index(date)] = values[:count]
result[:by_referral][:totals][product_permalink] ||= {}
result[:by_referral][:totals][product_permalink][referrer_name] ||= [0] * dates_strings.size
result[:by_referral][:totals][product_permalink][referrer_name][dates_strings.index(date)] = values[:total]
end
result
end
private
def result_metadata
metadata = {
dates_and_months: D3.date_month_domain(@dates),
start_date: D3.formatted_date(@dates.first),
end_date: D3.formatted_date(@dates.last),
}
first_sale_created_at = @user.first_sale_created_at_for_analytics
metadata[:first_sale_date] = D3.formatted_date_with_timezone(first_sale_created_at, @user.timezone) if first_sale_created_at
metadata
end
def product_page_views
CreatorAnalytics::ProductPageViews.new(user: @user, products:, dates: @dates)
end
def sales
CreatorAnalytics::Sales.new(user: @user, products:, dates: @dates)
end
def products
@_products ||= @user.products_for_creator_analytics.load
end
def product_permalinks
@_product_id_to_permalink ||= products.to_h { |product| [product.id, product.unique_permalink] }
end
def dates_strings
@_dates_strings ||= @dates.map(&:to_s)
end
def referrer_domain_to_name(referrer_domain)
return "direct" if referrer_domain.blank?
return "Recommended by Gumroad" if referrer_domain == REFERRER_DOMAIN_FOR_GUMROAD_RECOMMENDED_PRODUCTS
COMMON_REFERRERS_NAMES[referrer_domain] || referrer_domain
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/sales.rb | app/services/creator_analytics/sales.rb | # frozen_string_literal: true
class CreatorAnalytics::Sales
SEARCH_OPTIONS = Purchase::CHARGED_SALES_SEARCH_OPTIONS.merge(
exclude_refunded: false,
exclude_unreversed_chargedback: false,
)
def initialize(user:, products:, dates:)
@user = user
@products = products
@dates = dates
@query = PurchaseSearchService.new(SEARCH_OPTIONS).body[:query]
@query[:bool][:filter] << { terms: { product_id: @products.map(&:id) } }
@query[:bool][:must] << { range: { created_at: { time_zone: @user.timezone_id, gte: @dates.first.to_s, lte: @dates.last.to_s } } }
end
def by_product_and_date
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ date: { date_histogram: { time_zone: @user.timezone_id, field: "created_at", calendar_interval: "day", format: "yyyy-MM-dd" } } }
]
paginate(sources:).each_with_object({}) do |bucket, result|
key = [
bucket["key"]["product_id"],
bucket["key"]["date"]
]
result[key] = { count: bucket["doc_count"], total: bucket["total"]["value"].to_i }
end
end
def by_product_and_country_and_state
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ country: { terms: { field: "ip_country", missing_bucket: true } } },
{ state: { terms: { field: "ip_state", missing_bucket: true } } }
]
paginate(sources:).each_with_object({}) do |bucket, result|
key = [
bucket["key"]["product_id"],
bucket["key"]["country"].presence,
bucket["key"]["state"].presence,
]
result[key] = { count: bucket["doc_count"], total: bucket["total"]["value"].to_i }
end
end
def by_product_and_referrer_and_date
sources = [
{ product_id: { terms: { field: "product_id" } } },
{ referrer_domain: { terms: { field: "referrer_domain" } } },
{ date: { date_histogram: { time_zone: @user.timezone_id, field: "created_at", calendar_interval: "day", format: "yyyy-MM-dd" } } }
]
paginate(sources:).each_with_object(Hash.new(0)) do |bucket, hash|
key = [
bucket["key"]["product_id"],
bucket["key"]["referrer_domain"],
bucket["key"]["date"],
]
hash[key] = { count: bucket["doc_count"], total: bucket["total"]["value"].to_i }
end
end
private
def paginate(sources:)
after_key = nil
body = build_body(sources)
buckets = []
loop do
body[:aggs][:composite_agg][:composite][:after] = after_key if after_key
response_agg = Purchase.search(body).aggregations.composite_agg
buckets += response_agg.buckets
break if response_agg.buckets.size < ES_MAX_BUCKET_SIZE
after_key = response_agg["after_key"]
end
buckets
end
def build_body(sources)
{
query: @query,
size: 0,
aggs: {
composite_agg: {
composite: { size: ES_MAX_BUCKET_SIZE, sources: },
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
amount_refunded_cents_total: { sum: { field: "amount_refunded_cents" } },
chargedback_agg: {
filter: { term: { not_chargedback_or_chargedback_reversed: false } },
aggs: {
price_cents_total: { sum: { field: "price_cents" } },
}
},
total: {
bucket_script: {
buckets_path: {
price_cents_total: "price_cents_total",
amount_refunded_cents_total: "amount_refunded_cents_total",
chargedback_price_cents_total: "chargedback_agg>price_cents_total",
},
script: "params.price_cents_total - params.amount_refunded_cents_total - params.chargedback_price_cents_total"
}
}
}
}
}
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/caching_proxy.rb | app/services/creator_analytics/caching_proxy.rb | # frozen_string_literal: true
class CreatorAnalytics::CachingProxy
include Formatters::Helpers
include Formatters::ByDate
include Formatters::ByState
include Formatters::ByReferral
def initialize(user)
@user = user
end
# Proxy for cached values of CreatorAnalytics::Web#by_(date|state|referral)
# - Gets the cached values for all dates in one SELECT operation
# - If some are missing, run original several-day-spanning method of the missing ranges
# - Returns the merged data, optionally grouped by "month"
def data_for_dates(start_date, end_date, by: :date, options: {})
dates = requested_dates(start_date, end_date)
data = if use_cache?
data_for_dates = fetch_data_for_dates(dates, by:)
compiled_data = compile_data_for_dates_and_fill_missing(data_for_dates, by:)
public_send("merge_data_by_#{by}", compiled_data, dates)
else
analytics_data(dates.first, dates.last, by:)
end
data = public_send("group_#{by}_data_by_#{options[:group_by]}", data, options) if by.in?([:date, :referral]) && options[:group_by].to_s.in?(["day", "month"])
data
end
# Generates cached data for all possible dates for a seller
def generate_cache
return if @user.suspended?
first_sale_created_at = @user.first_sale_created_at_for_analytics
return if first_sale_created_at.nil?
first_sale_date = first_sale_created_at.in_time_zone(@user.timezone).to_date
# We fetch data for all dates up to the last date that `fetch_data` will cache.
dates = (first_sale_date .. last_date_to_cache).to_a
ActiveRecord::Base.connection.cache do
[:date, :state, :referral].each do |type|
Makara::Context.release_all
uncached_dates(dates, by: type).each do |date|
Makara::Context.release_all
fetch_data(date, by: type)
end
end
end
end
# Regenerate cached data for a date, useful when a purchase from a past day was refunded
def overwrite_cache(date, by: :date)
return if date < PRODUCT_EVENT_TRACKING_STARTED_DATE
return if date > last_date_to_cache
return unless use_cache?
ComputedSalesAnalyticsDay.upsert_data_from_key(
cache_key_for_data(date, by:),
analytics_data(date, date, by:)
)
end
private
def use_cache?
@_use_cache = LargeSeller.where(user: @user).exists?
end
def cache_key_for_data(date, by: :date)
"#{user_cache_key}_by_#{by}_for_#{date}"
end
# Today, from the user's timezone point of view
def today_date
Time.now.in_time_zone(@user.timezone).to_date
end
def last_date_to_cache
today_date - 2.days
end
# If the way analytics are calculated changed (e.g. an underlying method is changed),
# or the underlying data (purchases, events) has been unusually modified (e.g. directly via SQL),
# we may want to recalculate all cached analytics.
# The simplest way of doing so is to bump the analytics cache version:
# key = RedisKey.seller_analytics_cache_version; $redis.set(key, $redis.get(key) + 1)
# You'll probably then want to generate the cache for large sellers (see `generate_cache`).
def user_cache_key
return @_user_cache_key if @_user_cache_key
version = $redis.get(RedisKey.seller_analytics_cache_version) || 0
@_user_cache_key = "seller_analytics_v#{version}_user_#{@user.id}_#{@user.timezone}"
end
# Returns array of dates missing from the cache
def uncached_dates(dates, by: :date)
dates_to_keys = dates.index_with { |date| cache_key_for_data(date, by:) }
existing_keys = ComputedSalesAnalyticsDay.where(key: dates_to_keys.values).pluck(:key)
missing_keys = dates_to_keys.values - existing_keys
dates_to_keys.invert.values_at(*missing_keys)
end
# Direct proxy for CreatorAnalytics::Web
def analytics_data(start_date, end_date, by: :date)
CreatorAnalytics::Web.new(user: @user, dates: (start_date .. end_date).to_a).public_send("by_#{by}")
end
# Fetches and caches the analytics data for one specific date
def fetch_data(date, by: :date)
# Invalidating the cache for Today's analytics is complex,
# so we're currently not caching Today's data at all.
# We're also not caching "yesterday" because we're internally not acknowledging DST when querying
# via Elasticsearch, and being off by an hour can result in caching incomplete stats.
return analytics_data(date, date, by:) if date > last_date_to_cache
ComputedSalesAnalyticsDay.fetch_data_from_key(cache_key_for_data(date, by:)) do
analytics_data(date, date, by:)
end
end
# Constrains the date range coming from the web browser
# - It can't start after Today or before the user creation date
# - It can't end after Today
# - It will always return at least one day
def requested_dates(start_date, end_date)
user_created_date = @user.created_at.in_time_zone(@user.timezone).to_date
constrained_start = start_date.clamp(user_created_date, today_date)
constrained_end = end_date.clamp(constrained_start, today_date)
(constrained_start .. constrained_end).to_a
end
# Takes an array of dates, returns a hash with matching stored data, or nil if missing.
def fetch_data_for_dates(dates, by: :date)
keys_to_dates = dates.index_by { |date| cache_key_for_data(date, by:) }
existing_data_with_keys = ComputedSalesAnalyticsDay.read_data_from_keys(keys_to_dates.keys)
existing_data_with_keys.transform_keys { |key| keys_to_dates[key] }
end
# Takes an hash of { date => (data | nil), }, returns an array of data for all days.
def compile_data_for_dates_and_fill_missing(data_for_dates, by: :date)
missing_date_ranges = find_missing_date_ranges(data_for_dates)
data_for_dates.flat_map do |date, day_data|
next day_data if day_data
missing_range = missing_date_ranges.find { |range| range.begin == date }
analytics_data(missing_range.begin, missing_range.end, by:) if missing_range
end.compact.map(&:with_indifferent_access)
end
# Returns contiguous missing dates as ranges.
# In: { date => (data or nil), ... }
# Out: [ (from .. to), ... ]
def find_missing_date_ranges(data)
hash_result = data.each_with_object({}) do |(date, value), hash|
next if value
hash[ hash.key(date - 1) || date ] = date
end
hash_result.map { |array| Range.new(*array) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/caching_proxy/formatters/by_referral.rb | app/services/creator_analytics/caching_proxy/formatters/by_referral.rb | # frozen_string_literal: true
module CreatorAnalytics::CachingProxy::Formatters::ByReferral
# See #merge_data_by_date
def merge_data_by_referral(days_data, dates)
data = { by_referral: { views: {}, sales: {}, totals: {} } }
# We compile all products first,
# because some products may not have existed in previous days' cached data.
permalinks = days_data.flat_map do |day_data|
day_data[:by_referral].values.map(&:keys)
end.flatten.uniq
# Compile referrers by type and product
referrers = {}
%i[views sales totals].each do |type|
referrers[type] ||= {}
permalinks.each do |permalink|
referrers[type][permalink] ||= []
days_data.each do |day_data|
referrers[type][permalink] += day_data.dig(:by_referral, type, permalink)&.keys || []
end
referrers[type][permalink].uniq!
end
end
permalinks.each do |permalink|
total_day_index = 0
days_data.each do |day_data|
%i[views sales totals].each do |type|
data[:by_referral][type][permalink] ||= {}
referrers[type][permalink].each do |referrer|
data[:by_referral][type][permalink][referrer] ||= [0] * dates.size
data[:by_referral][type][permalink][referrer][total_day_index .. (total_day_index + day_data[:dates_and_months].size - 1)] = (day_data.dig(:by_referral, type, permalink, referrer) || ([0] * day_data[:dates_and_months].size))
end
end
total_day_index += day_data[:dates_and_months].size
end
end
data[:dates_and_months] = D3.date_month_domain(dates.first .. dates.last)
data[:start_date] = D3.formatted_date(dates.first)
data[:end_date] = D3.formatted_date(dates.last)
first_sale_created_at = @user.first_sale_created_at_for_analytics
data[:first_sale_date] = D3.formatted_date_with_timezone(first_sale_created_at, @user.timezone) if first_sale_created_at
data
end
def group_referral_data_by_day(data, options = {})
{
dates: dates_and_months_to_days(data[:dates_and_months], without_years: options[:days_without_years]),
by_referral: data[:by_referral]
}
end
def group_referral_data_by_month(data, _options = {})
months_count = data[:dates_and_months].last[:month_index] + 1
permalinks = (data[:by_referral][:views].keys + data[:by_referral][:sales].keys + data[:by_referral][:totals].keys).uniq
products_seed_data = [:views, :sales, :totals].index_with do |type|
data[:by_referral][type].keys.index_with do |key|
data[:by_referral][type][key].transform_values do
[0] * months_count
end
end
end
new_data = {
dates: dates_and_months_to_months(data[:dates_and_months]),
by_referral: products_seed_data
}
data[:dates_and_months].each.with_index do |date_data, index|
%i[views sales totals].each do |type|
permalinks.each do |permalink|
(data[:by_referral][type][permalink] || {}).keys.each do |referrer|
new_data[:by_referral][type][permalink][referrer][date_data[:month_index]] += data[:by_referral][type][permalink][referrer][index]
end
end
end
end
new_data
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/caching_proxy/formatters/helpers.rb | app/services/creator_analytics/caching_proxy/formatters/helpers.rb | # frozen_string_literal: true
module CreatorAnalytics::CachingProxy::Formatters::Helpers
private
# When getting data from a mix of cached and uncached sources,
# `month_index` may not be sequential. This ensures it is the case.
def rebuild_month_index_values!(dates_and_months)
last_month = nil
month_index = -1
dates_and_months.each do |element|
if element[:month] != last_month
last_month = element[:month]
month_index = month_index + 1
end
element[:month_index] = month_index
end
end
def dates_and_months_to_days(dates_and_months, without_years: false)
dates_and_months.map do |date_data|
year = Date.parse(date_data[:month]).year
date = Date.parse("#{date_data[:date]} #{year}")
day_ordinal = date.day.ordinalize
new_format = without_years ? "%A, %B #{day_ordinal}" : "%A, %B #{day_ordinal} %Y"
date.strftime(new_format)
end
end
def dates_and_months_to_months(dates_and_months)
dates_and_months.map { |date_data| date_data[:month] }.uniq
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/caching_proxy/formatters/by_date.rb | app/services/creator_analytics/caching_proxy/formatters/by_date.rb | # frozen_string_literal: true
module CreatorAnalytics::CachingProxy::Formatters::ByDate
# Merges several `#by_date` results into singular data.
# Does not generate any queries of any kind.
# Example:
# day_1 = Web.new(dates: (monday .. monday).to_a).by_date
# day_2 = Web.new(dates: (tuesday .. tuesday).to_a).by_date
# day_3 = Web.new(dates: (wednesday .. wednesday).to_a).by_date
# merge_data_by_date([day_1, day_2, day_3]) == Web.new(dates: (monday .. wednesday).to_a).by_date
# Notes:
# - the days in `days_data` need to be consecutive, and already sorted
def merge_data_by_date(days_data, _dates = nil)
data = {
dates_and_months: [],
start_date: days_data.first.fetch(:start_date),
end_date: days_data.last.fetch(:end_date),
by_date: { views: {}, sales: {}, totals: {} }
}
days_data.each do |day_data|
data[:first_sale_date] = day_data[:first_sale_date] if !data.key?(:first_sale_date) && day_data[:first_sale_date]
data[:dates_and_months] += day_data[:dates_and_months]
end
rebuild_month_index_values!(data[:dates_and_months])
# We compile all products first,
# because some products may not have existed in previous days' cached data.
permalinks = days_data.flat_map do |day_data|
day_data[:by_date][:views].keys
end.uniq
permalinks.each do |permalink|
days_data.each do |day_data|
%i[views sales totals].each do |type|
data[:by_date][type][permalink] ||= []
if day_data[:by_date][type].key?(permalink)
data[:by_date][type][permalink] += day_data[:by_date][type][permalink]
else
data[:by_date][type][permalink] += [0] * day_data[:dates_and_months].size
end
end
end
end
data
end
def group_date_data_by_day(data, options = {})
{
dates: dates_and_months_to_days(data[:dates_and_months], without_years: options[:days_without_years]),
by_date: data[:by_date]
}
end
def group_date_data_by_month(data, _options = {})
months_count = data[:dates_and_months].last[:month_index] + 1
permalinks = data[:by_date][:views].keys
products_seed_data = permalinks.index_with { [0] * months_count }
new_data = {
dates: dates_and_months_to_months(data[:dates_and_months]),
by_date: [:views, :sales, :totals].index_with { products_seed_data.deep_dup }
}
data[:dates_and_months].each.with_index do |date_data, index|
%i[views sales totals].each do |type|
permalinks.each do |permalink|
new_data[:by_date][type][permalink][date_data[:month_index]] += data[:by_date][type][permalink][index]
end
end
end
new_data
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/creator_analytics/caching_proxy/formatters/by_state.rb | app/services/creator_analytics/caching_proxy/formatters/by_state.rb | # frozen_string_literal: true
module CreatorAnalytics::CachingProxy::Formatters::ByState
# See #merge_data_by_date
def merge_data_by_state(days_data, _dates = nil)
data = { by_state: { views: {}, sales: {}, totals: {} } }
permalinks = days_data.flat_map do |day_data|
day_data[:by_state].values.map(&:keys)
end.flatten.uniq
permalinks.each do |permalink|
days_data.each do |day_data|
%i[views sales totals].each do |type|
data[:by_state][type][permalink] ||= {}
(day_data[:by_state][type][permalink] || {}).each do |country, value|
if value.is_a?(Array)
if data[:by_state][type][permalink].key?(country)
value.each.with_index do |element, i|
data[:by_state][type][permalink][country][i] += element
end
else
data[:by_state][type][permalink][country] = value
end
else
data[:by_state][type][permalink][country] ||= 0
data[:by_state][type][permalink][country] += value
end
end
end
end
end
data
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/subscription/updater_service.rb | app/services/subscription/updater_service.rb | # frozen_string_literal: true
class Subscription::UpdaterService
include CurrencyHelper
attr_reader :subscription, :gumroad_guid, :params, :logged_in_user, :remote_ip
attr_accessor :original_purchase, :original_price, :new_purchase, :upgrade_purchase,
:overdue_for_charge, :is_resubscribing, :is_pending_cancellation,
:calculate_upgrade_cost_as_of, :prorated_discount_price_cents,
:card_data_handling_mode, :card_data_handling_error, :chargeable,
:api_notification_sent
def initialize(subscription:, params:, logged_in_user:, gumroad_guid:, remote_ip:)
@subscription = subscription
@params = params
@logged_in_user = logged_in_user
@gumroad_guid = gumroad_guid
@remote_ip = remote_ip
@api_notification_sent = false
[:price_range, :perceived_price_cents, :perceived_upgrade_price_cents, :quantity].each do |param|
params[param] = params[param].to_i if params[param]
end
if params[:contact_info].present?
params[:contact_info] = params[:contact_info].transform_values do |value|
value == "" ? nil : value
end
end
end
def perform
error_message = validate_params
return { success: false, error_message: } if error_message.present?
# Store existing, pre-updated values
self.original_purchase = subscription.original_purchase
self.original_price = subscription.price
self.overdue_for_charge = subscription.overdue_for_charge?
self.is_resubscribing = !subscription.alive?(include_pending_cancellation: false)
self.is_pending_cancellation = subscription.pending_cancellation?
self.calculate_upgrade_cost_as_of = Time.current.end_of_day
self.prorated_discount_price_cents = subscription.prorated_discount_price_cents(calculate_as_of: calculate_upgrade_cost_as_of)
if is_resubscribing && (subscription.cancelled_by_seller? || product.deleted?)
return { success: false, error_message: "This subscription cannot be restarted." }
end
if is_resubscribing && subscription.is_installment_plan? && subscription.charges_completed?
return { success: false, error_message: "This installment plan has already been completed and cannot be restarted." }
end
result = nil
terminated_or_scheduled_for_termination = subscription.termination_date.present?
begin
ActiveRecord::Base.transaction do
# Update subscription contact info
if params[:contact_info].present?
params[:contact_info][:country] = ISO3166::Country[params[:contact_info][:country]]&.common_name
original_purchase.is_updated_original_subscription_purchase = true
original_purchase.update!(params[:contact_info])
end
if !same_plan_and_price? || (is_resubscribing && overdue_for_charge)
subscription.update!(flat_fee_applicable: true) unless subscription.flat_fee_applicable?
end
# Update card if necessary
unless use_existing_card?
had_saved_card = subscription.credit_card.present?
# (a) Get chargeable. Return if error
error_message = get_chargeable
if error_message.present?
logger.info("SubscriptionUpdater: Error fetching chargeable for subscription #{subscription.external_id}: #{error_message} ; params: #{params}")
raise Subscription::UpdateFailed, error_message
end
# (b) Create new credit card. Return if error.
credit_card = CreditCard.create(chargeable, card_data_handling_mode, logged_in_user)
unless credit_card.errors.empty?
logger.info("SubscriptionUpdater: Error creating new credit card for subscription #{subscription.external_id}: #{credit_card.errors.full_messages} ; params: #{params}")
raise Subscription::UpdateFailed, credit_card.errors.messages[:base].first
end
# (c) Associate the new card with the subscription
update_subscription_credit_card!(credit_card)
# (d) Send email for giftee adding their first card
if !had_saved_card && subscription.gift? && !is_resubscribing
CustomerLowPriorityMailer.subscription_giftee_added_card(subscription.id).deliver_later
end
end
unless same_plan_and_price?
self.new_purchase = subscription.update_current_plan!( # here we have an error
new_variants: variants,
new_price: price,
new_quantity: params[:quantity],
perceived_price_cents: params[:price_range],
)
subscription.reload
end
if !same_plan_and_price? || overdue_for_charge
# Validate that prices matches what the user was shown for prorated upgrade
# price and ongoing subscription price. Skip this step if the plan is not
# changing.
validate_perceived_prices_match
# delete pending plan changes
subscription.subscription_plan_changes.alive.update_all(deleted_at: Time.current)
end
# Do not allow restarting a subscription unless
# the card used for charging the subscription is supported by the product creator.
# It's possible that the creator has disconnected their PayPal account,
# and if the subscription is using PayPal as the payment method, future charges will fail.
if is_resubscribing &&
!subscription.link.user.supports_card?(subscription.user&.credit_card&.as_json) &&
!subscription.link.user.supports_card?(subscription.credit_card.as_json)
raise Subscription::UpdateFailed, "There is a problem with creator's paypal account, please try again later (your card was not charged)."
end
if !apply_plan_change_immediately?
# If not an upgrade or changing plans during trial period, roll back changes
# made by `Subscription#update_current_plan!`
restore_original_purchase!
# If purchase is missing tier and user is not upgrading, associate default tier.
original_purchase.update!(variant_attributes: [product.default_tier]) if tiered_membership? && original_purchase.variant_attributes.empty?
end
# Restart subscription if necessary
subscription.resubscribe! if is_resubscribing
if (same_plan_and_price? || subscription.in_free_trial?) && !overdue_for_charge
send_subscription_updated_api_notification if apply_plan_change_immediately?
# return if not changing tier or price (and the user isn't resubscribing
# or changing plan during their free trial period) - no need to update
# these or charge the user.
result = { success: true, success_message: }
else
if downgrade?
if !apply_plan_change_immediately?
plan_change = record_plan_change!
ContactingCreatorMailer.subscription_downgraded(subscription.id, plan_change.id).deliver_later(queue: "critical")
end
send_subscription_updated_api_notification
end
# Charge user if necessary
if should_charge_user?
result = charge_user!
else
result = { success: true, success_message: }
end
end
end
rescue ActiveRecord::RecordInvalid, Subscription::UpdateFailed => e
logger.info("SubscriptionUpdater: Error updating subscription #{subscription.external_id}: #{e.message} ; params: #{params}")
result = { success: false, error_message: e.message }
end
subscription.update_flag!(:is_resubscription_pending_confirmation, true, true) if is_resubscribing && result[:requires_card_action]
if apply_plan_change_immediately? && !same_variants? && result[:success] && !result[:requires_card_action]
UpdateIntegrationsOnTierChangeWorker.perform_async(subscription.id)
end
subscription.send_restart_notifications! if is_resubscribing && result[:success] && !result[:requires_card_action] && terminated_or_scheduled_for_termination
result
end
private
def validate_params
return if !tiered_membership? || (variants.present? && price.present?)
"Please select a valid tier and payment option."
end
def validate_perceived_prices_match
unless new_price_cents == params[:perceived_price_cents] && amount_owed == params[:perceived_upgrade_price_cents]
logger.info("SubscriptionUpdater: Error updating subscription - perceived prices do not match: id: #{subscription.external_id} ; new_price_cents: #{new_price_cents} ; amount_owed: #{amount_owed} ; params: #{params}")
raise Subscription::UpdateFailed, "The price just changed! Refresh the page for the updated price."
end
end
def new_price_cents
new_purchase.present? ? new_purchase.displayed_price_cents : subscription.current_subscription_price_cents
end
def get_chargeable
self.card_data_handling_mode = CardParamsHelper.get_card_data_handling_mode(params)
self.card_data_handling_error = CardParamsHelper.check_for_errors(params)
self.chargeable = CardParamsHelper.build_chargeable(params.merge(product_permalink: subscription.link.unique_permalink))
# return error message if necessary
if card_data_handling_error.present?
logger.info("SubscriptionUpdater: Error building chargeable for subscription #{subscription.external_id}: #{card_data_handling_error.error_message} #{card_data_handling_error.card_error_code} ; params: #{params}")
Rails.logger.error("Card data handling error at update stored card: " \
"#{card_data_handling_error.error_message} #{card_data_handling_error.card_error_code}")
card_data_handling_error.is_card_error? ? PurchaseErrorCode.customer_error_message(card_data_handling_error.error_message) : "There is a temporary problem, please try again (your card was not charged)."
elsif !chargeable.present?
"We couldn't charge your card. Try again or use a different card."
end
end
def update_subscription_credit_card!(credit_card)
subscription.credit_card = credit_card
subscription.save!
end
def record_plan_change!
subscription.subscription_plan_changes.create!(
tier: new_tier,
recurrence: price.recurrence,
quantity: new_purchase.quantity,
perceived_price_cents: new_price_cents,
)
end
def restore_original_purchase!
if new_purchase.present?
license = new_purchase.license
license.update!(purchase_id: original_purchase.id) if license.present?
email_infos = new_purchase.email_infos
email_infos.each { |email| email.update!(purchase_id: original_purchase.id) }
Comment.where(purchase: new_purchase).update_all(purchase_id: original_purchase.id)
new_purchase.url_redirect.destroy! if new_purchase.url_redirect.present?
new_purchase.events.destroy_all
new_purchase.destroy!
Rails.logger.info("Destroyed purchase #{new_purchase.id}")
end
original_purchase.update_flag!(:is_archived_original_subscription_purchase, false, true)
subscription.last_payment_option.update!(price: original_price)
end
def charge_user!
purchase_params = {
browser_guid: gumroad_guid,
perceived_price_cents: amount_owed,
prorated_discount_price_cents:,
is_upgrade_purchase: upgrade?
}
unless use_existing_card?
purchase_params.merge!(
card_data_handling_mode:,
card_data_handling_error:,
chargeable:,
)
end
purchase_params.merge!(setup_future_charges: true) if subscription.credit_card_to_charge&.requires_mandate?
self.upgrade_purchase = subscription.charge!(
override_params: purchase_params,
from_failed_charge_email: ActiveModel::Type::Boolean.new.cast(params[:declined]),
off_session: !subscription.credit_card_to_charge&.requires_mandate?
)
subscription.unsubscribe_and_fail! if is_resubscribing && !(upgrade_purchase.successful? ||
(upgrade_purchase.in_progress? && upgrade_purchase.charge_intent&.requires_action?))
error_message = upgrade_purchase.errors.full_messages.first || upgrade_purchase.error_code
if error_message.nil? && (upgrade_purchase.successful? || upgrade_purchase.test_successful?)
send_subscription_updated_api_notification
subscription.original_purchase.schedule_workflows_for_variants(excluded_variants: original_purchase.variant_attributes) unless same_variants?
{
success: true,
next: logged_in_user && Rails.application.routes.url_helpers.library_purchase_url(upgrade_purchase.external_id, host: "#{PROTOCOL}://#{DOMAIN}"),
success_message:,
}
elsif upgrade_purchase.in_progress? && upgrade_purchase.charge_intent&.requires_action?
{
success: true,
requires_card_action: true,
client_secret: upgrade_purchase.charge_intent.client_secret,
purchase: {
id: upgrade_purchase.external_id,
stripe_connect_account_id: upgrade_purchase.merchant_account.is_a_stripe_connect_account? ? upgrade_purchase.merchant_account.charge_processor_merchant_id : nil
}
}
else
logger.info("SubscriptionUpdater: Error charging user for subscription #{subscription.external_id}: #{error_message} ; params: #{params}")
raise Subscription::UpdateFailed, error_message
end
end
def send_subscription_updated_api_notification
return if api_notification_sent
return unless tiered_membership?
return if same_plan_and_price?
unless new_purchase.present?
Bugsnag.notify("SubscriptionUpdater: new_purchase missing when sending API notification")
return
end
self.api_notification_sent = true
subscription.send_updated_notifification_webhook(
plan_change_type: downgrade? ? "downgrade" : "upgrade",
effective_as_of: (downgrade? && !apply_plan_change_immediately?) ? subscription.end_time_of_last_paid_period : new_purchase.created_at,
old_recurrence: original_recurrence,
new_recurrence: price.recurrence,
old_tier: original_purchase.tier || product.default_tier,
new_tier:,
old_price: original_purchase.displayed_price_cents,
new_price: new_purchase.displayed_price_cents,
old_quantity: original_purchase.quantity,
new_quantity: new_purchase.quantity,
)
end
def product
@product ||= subscription.link
end
def variants
@variants ||= (params[:variants] || []).map do |id|
product.base_variants.find_by_external_id(id)
end.compact
end
def new_tier
variants.first
end
def price
@price ||= product.prices.is_buy.find_by_external_id(params[:price_id])
end
def original_recurrence
original_price.recurrence
end
def should_charge_user?
amount_owed > 0
end
def use_existing_card?
ActiveModel::Type::Boolean.new.cast(params[:use_existing_card])
end
def amount_owed
return new_price_cents if overdue_for_charge || new_plan_is_free?
return 0 if subscription.in_free_trial? || !upgrade?
[new_price_cents - prorated_discount_price_cents, min_price_for(product.price_currency_type)].max
end
def downgrade?
!same_plan_and_price? && original_purchase.displayed_price_cents > new_price_cents
end
def upgrade?
!(downgrade? || same_plan_and_price?)
end
def same_plan_and_price?
same_plan? && (!pwyw? || same_pwyw_price?) && same_quantity?
end
def same_plan?
same_variants? && same_recurrence?
end
def apply_plan_change_immediately?
subscription.in_free_trial? || should_charge_user? || new_plan_is_free?
end
def same_variants?
variant_ids = variants.map(&:id)
if tiered_membership? && original_purchase.variant_attributes.empty?
# Handle older subscriptions whose original purchases don't have tiers associated.
# We should allow these to update to the default tier without being charged.
variant_ids == [product.default_tier.id]
else
variant_ids.sort == original_purchase.variant_attributes.to_a.map(&:id).sort
end
end
def same_recurrence?
!price.present? || original_recurrence == price.recurrence
end
def same_quantity?
original_purchase.quantity == params[:quantity]
end
def pwyw?
variants.any? { |v| v.customizable_price? }
end
def same_pwyw_price?
pwyw? && original_purchase.displayed_price_cents == params[:perceived_price_cents]
end
def tiered_membership?
subscription.link.is_tiered_membership
end
def new_plan_is_free?
new_price_cents == 0
end
def success_message
if is_resubscribing
"#{subscription_entity.capitalize} restarted"
elsif downgrade? && !apply_plan_change_immediately?
"Your #{subscription_entity} will be updated at the end of your current billing cycle."
else
"Your #{subscription_entity} has been updated."
end
end
def subscription_entity
subscription.is_installment_plan ? "installment plan" : "membership"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/charge/create_service.rb | app/services/charge/create_service.rb | # frozen_string_literal: true
class Charge::CreateService
attr_accessor :order, :seller, :merchant_account, :chargeable, :purchases, :amount_cents, :gumroad_amount_cents,
:setup_future_charges, :off_session, :statement_description, :charge, :mandate_options
def initialize(order:, seller:, merchant_account:, chargeable:,
purchases:, amount_cents:, gumroad_amount_cents:,
setup_future_charges:, off_session:,
statement_description:, mandate_options: nil)
@order = order
@seller = seller
@merchant_account = merchant_account
@chargeable = chargeable
@purchases = purchases
@amount_cents = amount_cents
@gumroad_amount_cents = gumroad_amount_cents
@setup_future_charges = setup_future_charges
@off_session = off_session
@statement_description = statement_description
@mandate_options = mandate_options
end
def perform
self.charge = order.charges.find_or_create_by!(seller:)
self.charge.update!(merchant_account:,
processor: merchant_account.charge_processor_id,
amount_cents:,
gumroad_amount_cents:,
payment_method_fingerprint: chargeable.fingerprint)
purchases.each do |purchase|
purchase.charge = charge
charge.credit_card ||= purchase.credit_card
purchase.save!
end
charge_intent = with_charge_processor_error_handler do
ChargeProcessor.create_payment_intent_or_charge!(merchant_account,
chargeable,
amount_cents,
gumroad_amount_cents,
"#{Charge::COMBINED_CHARGE_PREFIX}#{charge.external_id}",
"Gumroad Charge #{charge.external_id}",
statement_description:,
transfer_group: charge.id_with_prefix,
off_session:,
setup_future_charges:,
metadata: StripeMetadata.build_metadata_large_list(purchases.map(&:external_id), key: :purchases, separator: ","),
mandate_options:)
end
if charge_intent.present?
charge.charge_intent = charge_intent
charge.payment_method_fingerprint = chargeable.fingerprint
charge.stripe_payment_intent_id = charge_intent.id if charge_intent.is_a? StripeChargeIntent
charge.stripe_setup_intent_id = charge_intent.id if charge_intent.is_a? StripeSetupIntent
if charge_intent.succeeded?
charge.processor_transaction_id = charge_intent.charge.id
charge.processor_fee_cents = charge_intent.charge.fee
charge.processor_fee_currency = charge_intent.charge.fee_currency
end
charge.save!
end
charge
end
def with_charge_processor_error_handler
yield
rescue ChargeProcessorInvalidRequestError, ChargeProcessorUnavailableError => e
logger.error "Charge processor error: #{e.message} in charge: #{charge.external_id}"
purchases.each do |purchase|
purchase.errors.add :base, "There is a temporary problem, please try again (your card was not charged)."
purchase.error_code = charge_processor_unavailable_error
end
nil
rescue ChargeProcessorPayeeAccountRestrictedError => e
logger.error "Charge processor error: #{e.message} in charge: #{charge.external_id}"
purchases.each do |purchase|
purchase.errors.add :base, "There is a problem with creator's paypal account, please try again later (your card was not charged)."
purchase.stripe_error_code = PurchaseErrorCode::PAYPAL_MERCHANT_ACCOUNT_RESTRICTED
end
nil
rescue ChargeProcessorPayerCancelledBillingAgreementError => e
logger.error "Error while creating charge: #{e.message} in charge: #{charge.external_id}"
purchases.each do |purchase|
purchase.errors.add :base, "Customer has cancelled the billing agreement on PayPal."
purchase.stripe_error_code = PurchaseErrorCode::PAYPAL_PAYER_CANCELLED_BILLING_AGREEMENT
end
nil
rescue ChargeProcessorPaymentDeclinedByPayerAccountError => e
logger.error "Error while creating charge: #{e.message} in charge: #{charge.external_id}"
purchases.each do |purchase|
purchase.errors.add :base, "Customer PayPal account has declined the payment."
purchase.stripe_error_code = PurchaseErrorCode::PAYPAL_PAYER_ACCOUNT_DECLINED_PAYMENT
end
nil
rescue ChargeProcessorUnsupportedPaymentTypeError => e
logger.info "Charge processor error: Unsupported paypal payment method selected"
purchases.each do |purchase|
purchase.errors.add :base, "We weren't able to charge your PayPal account. Please select another method of payment."
purchase.stripe_error_code = e.error_code
purchase.stripe_transaction_id = e.charge_id
end
nil
rescue ChargeProcessorUnsupportedPaymentAccountError => e
logger.info "Charge processor error: PayPal account used is not supported"
purchases.each do |purchase|
purchase.errors.add :base, "Your PayPal account cannot be charged. Please select another method of payment."
purchase.stripe_error_code = e.error_code
purchase.stripe_transaction_id = e.charge_id
end
nil
rescue ChargeProcessorCardError => e
purchases.each do |purchase|
purchase.stripe_error_code = e.error_code
purchase.stripe_transaction_id = e.charge_id
purchase.was_zipcode_check_performed = true if e.error_code == "incorrect_zip"
purchase.errors.add :base, PurchaseErrorCode.customer_error_message(e.message)
end
logger.info "Charge processor error: #{e.message} in charge: #{charge.external_id}"
nil
rescue ChargeProcessorErrorRateLimit => e
purchases.each do |purchase|
purchase.errors.add :base, "There is a temporary problem, please try again (your card was not charged)."
purchase.error_code = charge_processor_unavailable_error
end
logger.error "Charge processor error: #{e.message} in charge: #{charge.external_id}"
raise e
rescue ChargeProcessorErrorGeneric => e
purchases.each do |purchase|
purchase.errors.add :base, "There is a temporary problem, please try again (your card was not charged)."
purchase.stripe_error_code = e.error_code
end
logger.error "Charge processor error: #{e.message} in charge: #{charge.external_id}"
nil
end
def charge_processor_unavailable_error
if charge.processor.blank? || charge.processor == StripeChargeProcessor.charge_processor_id
PurchaseErrorCode::STRIPE_UNAVAILABLE
else
PurchaseErrorCode::PAYPAL_UNAVAILABLE
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/early_fraud_warning/update_service.rb | app/services/early_fraud_warning/update_service.rb | # frozen_string_literal: true
class EarlyFraudWarning::UpdateService
class AlreadyResolvedError < StandardError; end
def initialize(record)
@record = record
@chargeable = record.chargeable
end
def perform!
# We want to preserve the record in its original state just before it was processed by us.
# In some cases (e.g. after refunding for fraud), there will be a webhook request sent, that would affect our
# reporting data, so we don't want to process those.
# Basically, once an EFW is resolved, it is locked, and we don't want any more updates to it.
raise AlreadyResolvedError if record.resolved?
efw_object = fetch_stripe_object(chargeable, record.processor_id)
record.update!(
purchase: (chargeable if chargeable.is_a?(Purchase)),
charge: (chargeable if chargeable.is_a?(Charge)),
dispute: chargeable.dispute,
refund: chargeable.refunds.first,
fraud_type: efw_object.fraud_type,
actionable: efw_object.actionable,
charge_risk_level: efw_object.charge.outcome.risk_level,
processor_created_at: Time.zone.at(efw_object.created),
)
end
private
attr_reader :chargeable, :record
# Retrieve the EFW object from Stripe to ensure we have the latest data
# (we have to fetch the charge object anyway, to get the risk level)
def fetch_stripe_object(chargeable, stripe_object_id)
if chargeable.charged_using_stripe_connect_account?
Stripe::Radar::EarlyFraudWarning.retrieve(
{ id: stripe_object_id, expand: %w(charge) },
{ stripe_account: chargeable.merchant_account.charge_processor_merchant_id }
)
else
Stripe::Radar::EarlyFraudWarning.retrieve({ id: stripe_object_id, expand: %w(charge) })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/recommended_products/checkout_service.rb | app/services/recommended_products/checkout_service.rb | # frozen_string_literal: true
class RecommendedProducts::CheckoutService < RecommendedProducts::BaseService
def self.fetch_for_cart(purchaser:, cart_product_ids:, recommender_model_name:, limit:, recommendation_type: nil)
new(
purchaser:,
cart_product_ids:,
recommender_model_name:,
recommended_by: RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION,
target: Product::Layout::PROFILE,
limit:,
recommendation_type:,
).result
end
def self.fetch_for_receipt(purchaser:, receipt_product_ids:, recommender_model_name:, limit:)
new(
purchaser:,
cart_product_ids: receipt_product_ids,
recommender_model_name:,
recommended_by: RecommendationType::GUMROAD_RECEIPT_RECOMMENDATION,
target: Product::Layout::PROFILE,
limit:,
).result
end
include SearchProducts
def result
recommended_products = fetch_recommended_products(for_seller_ids: affiliated_users.present? ? nil : cart_seller_ids)
recommended_products = recommended_products.includes(:direct_affiliates) if affiliated_users.present?
recommended_products = recommended_products.includes(:taxonomy, user: [:alive_bank_accounts]) if global_affiliate.present?
recommended_products = recommended_products.alive.not_archived
recommended_products = recommended_products.reject(&:rated_as_adult?) if affiliated_users.present? && Link.includes(:user).where(id: cart_product_ids).none?(&:rated_as_adult?)
product_infos = recommended_products.filter_map do |product|
direct_affiliate_id = affiliated_users.present? ? product.direct_affiliates.find { affiliated_users.ids.include?(_1.affiliate_user_id) }&.external_id_numeric : nil
if cart_seller_ids&.include?(product.user_id) || direct_affiliate_id.present? || (global_affiliate.present? && product.user.not_disable_global_affiliate? && product.recommendable?)
RecommendedProducts::ProductInfo.new(
product,
affiliate_id: direct_affiliate_id || global_affiliate&.external_id_numeric
)
end
end.take(limit)
if product_infos.length < limit && cart_seller_ids.present?
missing_results_count = limit - product_infos.length
search_result = search_products(
{
size: missing_results_count,
sort: ProductSortKey::FEATURED,
user_id: cart_seller_ids,
is_alive_on_profile: true,
exclude_ids: (exclude_product_ids + product_infos.map { _1.product.id }).uniq
}
)
products = search_result[:products].includes(ProductPresenter::ASSOCIATIONS_FOR_CARD)
product_infos += products.map { RecommendedProducts::ProductInfo.new(_1) }
end
build_result(product_infos:)
end
private
def cart_seller_ids
return [] if recommendation_type == User::RecommendationType::NO_RECOMMENDATIONS
@_seller_ids ||= begin
users = Link.joins(:user)
users = users.where.not(user: { recommendation_type: User::RecommendationType::NO_RECOMMENDATIONS }) if !recommendation_type
users
.where(id: cart_product_ids)
.select(:user_id)
.distinct
.pluck(:user_id)
end
end
def affiliated_users
@_affiliate_users ||= begin
recommendation_types = [
User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS,
User::RecommendationType::DIRECTLY_AFFILIATED_PRODUCTS
]
return User.none if cart_seller_ids.blank? || recommendation_type && !recommendation_types.include?(recommendation_type)
users = User.where(id: cart_seller_ids)
users = users.where(recommendation_type: recommendation_types) if !recommendation_type
users
end
end
def global_affiliate
@_global_affiliate ||= affiliated_users
.find { (recommendation_type || _1.recommendation_type) == User::RecommendationType::GUMROAD_AFFILIATES_PRODUCTS }
&.global_affiliate
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/recommended_products/product_info.rb | app/services/recommended_products/product_info.rb | # frozen_string_literal: true
class RecommendedProducts::ProductInfo
attr_accessor :recommended_by, :recommender_model_name, :target
attr_reader :product, :affiliate_id
def initialize(product, affiliate_id: nil)
@product = product
@affiliate_id = affiliate_id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/recommended_products/discover_service.rb | app/services/recommended_products/discover_service.rb | # frozen_string_literal: true
class RecommendedProducts::DiscoverService < RecommendedProducts::BaseService
def self.fetch(purchaser:, cart_product_ids:, recommender_model_name:)
new(
purchaser:,
cart_product_ids:,
recommender_model_name:,
recommended_by: RecommendationType::GUMROAD_PRODUCTS_FOR_YOU_RECOMMENDATION,
target: Product::Layout::DISCOVER,
limit: NUMBER_OF_RESULTS,
).product_infos
end
def product_infos
recommended_products = fetch_recommended_products(for_seller_ids: nil).alive.not_archived.includes(ProductPresenter::ASSOCIATIONS_FOR_CARD).reject(&:rated_as_adult?)
product_infos = recommended_products.map do
RecommendedProducts::ProductInfo.new(_1)
end.take(limit)
build_result(product_infos:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/recommended_products/base_service.rb | app/services/recommended_products/base_service.rb | # frozen_string_literal: true
class RecommendedProducts::BaseService
NUMBER_OF_RESULTS = 40
def initialize(purchaser:, cart_product_ids:, recommender_model_name:, recommended_by:, target:, limit:, recommendation_type: nil)
@purchaser = purchaser
@cart_product_ids = cart_product_ids
@recommender_model_name = recommender_model_name
@recommended_by = recommended_by
@target = target
@limit = limit
@recommendation_type = recommendation_type
end
def build_result(product_infos:)
product_infos.map do |product_info|
product_info.recommended_by = recommended_by
product_info.recommender_model_name = recommender_model_name
product_info.target = target
product_info
end
end
private
attr_reader :purchaser, :cart_product_ids, :recommender_model_name, :recommended_by, :target, :limit, :request, :recommendation_type
def fetch_recommended_products(for_seller_ids:)
associated_ids = find_associated_product_ids(limit: associated_product_ids_limit)
ids = if associated_ids.size >= 4
associated_ids.sample((associated_ids.size * 0.5).to_i)
else
associated_ids
end
RecommendedProductsService.fetch(
model: recommender_model_name,
ids:,
exclude_ids: exclude_product_ids,
user_ids: for_seller_ids,
number_of_results: NUMBER_OF_RESULTS,
)
end
def all_associated_product_ids
@_associated_product_ids ||= find_associated_product_ids
end
def find_associated_product_ids(limit: nil)
purchased_products = purchaser&.purchased_products&.order(succeeded_at: :desc)
if limit.present?
cart_product_ids.take(limit) | (purchased_products&.limit(limit)&.ids || [])
else
cart_product_ids | (purchased_products&.ids || [])
end
end
def exclude_product_ids
@_exclude_product_ids ||= \
all_associated_product_ids +
BundleProduct.alive.where(bundle_id: all_associated_product_ids).distinct.pluck(:product_id)
end
def associated_product_ids_limit
($redis.get(RedisKey.recommended_products_associated_product_ids_limit) || 100).to_i
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/collaborator/create_service.rb | app/services/collaborator/create_service.rb | # frozen_string_literal: true
class Collaborator::CreateService
def initialize(seller:, params:)
@seller = seller
@params = params
end
def process
collaborating_user = User.find_by(email: params[:email])
return { success: false, message: "The email address isn't associated with a Gumroad account." } if collaborating_user.nil?
if seller.collaborators.alive.exists?(affiliate_user: collaborating_user)
return { success: false, message: "The user is already a collaborator" }
end
collaborator = seller.collaborators.build(
affiliate_user: collaborating_user,
apply_to_all_products: params[:apply_to_all_products],
dont_show_as_co_creator: params[:dont_show_as_co_creator],
affiliate_basis_points: params[:percent_commission].presence&.to_i&.*(100),
)
collaborator.build_collaborator_invitation if require_approval?(seller:, collaborating_user:)
error = nil
params[:products].each do |product_params|
product = seller.products.find_by_external_id(product_params[:id])
unless product
error = "Product not found"
break
end
product_affiliate = collaborator.product_affiliates.build(product:)
percent_commission = params[:apply_to_all_products] ? params[:percent_commission] : product_params[:percent_commission]
product_affiliate.affiliate_basis_points = percent_commission.to_i * 100
product_affiliate.dont_show_as_co_creator = params[:apply_to_all_products] ?
collaborator.dont_show_as_co_creator :
product_params[:dont_show_as_co_creator]
end
return { success: false, message: error } if error.present?
if collaborator.save
deliver_email_for(collaborator)
{ success: true }
else
{ success: false, message: collaborator.errors.full_messages.first }
end
end
private
attr_reader :seller, :params
def require_approval?(seller:, collaborating_user:)
!collaborating_user.collaborators
.invitation_accepted
.alive
.exists?(affiliate_user: seller)
end
def deliver_email_for(collaborator)
if collaborator.collaborator_invitation.present?
AffiliateMailer.collaborator_invited(collaborator.id).deliver_later
else
AffiliateMailer.collaborator_creation(collaborator.id).deliver_later
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/collaborator/update_service.rb | app/services/collaborator/update_service.rb | # frozen_string_literal: true
class Collaborator::UpdateService
def initialize(seller:, collaborator_id:, params:)
@seller = seller
@collaborator = seller.collaborators.find_by_external_id!(collaborator_id)
@params = params
end
def process
default_basis_points = params[:percent_commission].presence&.to_i&.*(100)
collaborator.affiliate_basis_points = default_basis_points if default_basis_points.present?
collaborator.apply_to_all_products = params[:apply_to_all_products]
collaborator.dont_show_as_co_creator = params[:dont_show_as_co_creator]
enabled_product_ids = params[:products].map { _1[:id] }
collaborator.product_affiliates.map do |pa|
product_id = ObfuscateIds.encrypt(pa.link_id)
pa.destroy! unless enabled_product_ids.include?(product_id)
end
collaborator.product_affiliates = params[:products].map do |product_params|
product = seller.products.find_by_external_id!(product_params[:id])
product_affiliate = collaborator.product_affiliates.find_or_initialize_by(product:)
product_affiliate.dont_show_as_co_creator = collaborator.apply_to_all_products ?
collaborator.dont_show_as_co_creator :
product_params[:dont_show_as_co_creator]
percent_commission = collaborator.apply_to_all_products ? collaborator.affiliate_percentage : product_params[:percent_commission]
product_affiliate.affiliate_basis_points = percent_commission.to_i * 100
product_affiliate
end
if collaborator.save
AffiliateMailer.collaborator_update(collaborator.id).deliver_later
{ success: true }
else
{ success: false, message: collaborator.errors.full_messages.first }
end
end
private
attr_reader :seller, :collaborator, :params
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/order/charge_service.rb | app/services/order/charge_service.rb | # frozen_string_literal: true
class Order::ChargeService
include Events, Order::ResponseHelpers
attr_accessor :order, :params, :charge_intent, :setup_intent, :charge_responses
def initialize(order:, params:)
@order = order
@params = params
@charge_responses = {}
end
def perform
# We need to make off session charges if there are products from more than one seller
# In such case we create a reusable payment method before initiating the order from front-end
off_session = order.purchases.non_free.pluck(:seller_id).uniq.count > 1
# All remaining purchases need to be charged that are still in progress
# Create a combined charge for all purchases belonging to the same seller
# i.e. one charge per seller
purchases_by_seller = order.purchases.group_by(&:seller_id)
purchases_by_seller.each do |seller_id, seller_purchases|
charge = order.charges.create!(seller_id:)
seller_purchases.each do |purchase|
purchase.charge = charge
purchase.save!
# Mark free or test purchase as successful as it does not require any further processing
mark_successful_if_free_or_test_purchase(purchase)
end
non_free_seller_purchases = seller_purchases.select(&:in_progress?)
next unless non_free_seller_purchases.present?
# All purchases belonging to the same seller should have the same destination merchant account
if non_free_seller_purchases.pluck(:merchant_account_id).uniq.compact.count > 1
raise StandardError, "Error charging order #{order.id}:: Different merchant accounts in purchases: #{non_free_seller_purchases.pluck(:id)}"
end
params_for_chargeable = params.merge(product_permalink: non_free_seller_purchases.first.link.unique_permalink)
card_data_handling_mode, card_data_handling_error, chargeable_from_params = create_chargeable_from_params(params_for_chargeable)
setup_future_charges = non_free_seller_purchases.any? do |purchase|
(purchase.purchaser.present? && purchase.save_card && chargeable_from_params&.can_be_saved?) ||
purchase.is_preorder_authorization? || purchase.link.is_recurring_billing?
end
if setup_future_charges && chargeable_from_params.present?
credit_card = CreditCard.create(chargeable_from_params, card_data_handling_mode, order.purchaser)
credit_card.users << order.purchaser if order.purchaser.present?
end
chargeable = prepare_purchases_for_charge(non_free_seller_purchases,
card_data_handling_mode, card_data_handling_error,
chargeable_from_params, credit_card)
# If all purchases are either free-trial or preorder authorizations
# then we don't need to create a charge
# but only setup a reusable payment method for the future charges.
# Braintree and PayPal payment methods are already setup for future charges,
# in case of Stripe, create a setup intent.
all_in_progress_purchases = non_free_seller_purchases.reject { !_1.in_progress? || !_1.errors.empty? }
only_setup_for_future_charges = all_in_progress_purchases.present? && all_in_progress_purchases.all? do |purchase|
purchase.is_free_trial_purchase? || purchase.is_preorder_authorization?
end
if only_setup_for_future_charges
setup_for_future_charges_without_charging(non_free_seller_purchases, chargeable, chargeable_from_params.blank? && chargeable.present?)
else
create_charge_for_seller_purchases(non_free_seller_purchases, chargeable, off_session, setup_future_charges)
end
rescue => e
Rails.logger.error("Error charging order (#{order.id}):: #{e.class} => #{e.message} => #{e.backtrace}")
ensure
# Ensure all purchases of the charge are transitioned to a terminal state
# and each line item has a response
ensure_all_purchases_processed(non_free_seller_purchases)
end
charge_responses
end
def mark_successful_if_free_or_test_purchase(purchase)
if purchase.in_progress? && (purchase.free_purchase? || (purchase.is_test_purchase? && !purchase.is_preorder_authorization?))
Purchase::MarkSuccessfulService.new(purchase).perform
purchase.handle_recommended_purchase if purchase.was_product_recommended
line_item_uid = params[:line_items].select { |line_item| line_item[:permalink] == purchase.link.unique_permalink }[0][:uid]
charge_responses[line_item_uid] = purchase.purchase_response
end
end
def create_chargeable_from_params(params)
card_data_handling_mode = CardParamsHelper.get_card_data_handling_mode(params)
card_data_handling_error = CardParamsHelper.check_for_errors(params)
chargeable = CardParamsHelper.build_chargeable(params, params[:browser_guid])
chargeable&.prepare!
return card_data_handling_mode, card_data_handling_error, chargeable
end
def prepare_purchases_for_charge(purchases, card_data_handling_mode, card_data_handling_error, chargeable, credit_card)
purchases.each do |purchase|
purchase.card_data_handling_mode = card_data_handling_mode
purchase.card_data_handling_error = card_data_handling_error
purchase.chargeable = chargeable
purchase.charge_processor_id ||= chargeable&.charge_processor_id
chargeable = purchase.load_and_prepare_chargeable(credit_card) unless purchase.is_test_purchase?
purchase.check_for_blocked_customer_emails
purchase.validate_purchasing_power_parity
end
chargeable
end
def setup_for_future_charges_without_charging(purchases, chargeable, card_already_saved)
merchant_account = purchases.first.merchant_account
if merchant_account.stripe_charge_processor? && !card_already_saved
mandate_options = mandate_options_for_stripe(purchases:, with_currency: true)
self.setup_intent = ChargeProcessor.setup_future_charges!(merchant_account, chargeable, mandate_options:)
if setup_intent.present?
purchases.each do |purchase|
purchase.update!(processor_setup_intent_id: setup_intent.id)
purchase.charge.update!(stripe_setup_intent_id: setup_intent.id)
purchase.credit_card.update!(json_data: { stripe_setup_intent_id: setup_intent.id }) if purchase.credit_card&.requires_mandate?
if setup_intent.succeeded?
mark_setup_future_charges_successful(purchase)
elsif setup_intent.requires_action?
# Check back later to see if the purchase has been completed. If not, transition to a failed state.
FailAbandonedPurchaseWorker.perform_in(ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase.id)
else
purchase.errors.add :base, "Sorry, something went wrong." if purchase.errors.empty?
end
end
end
else
purchases.each do |purchase|
mark_setup_future_charges_successful(purchase)
end
end
end
def mark_setup_future_charges_successful(purchase)
return unless purchase.in_progress?
if purchase.is_free_trial_purchase?
Purchase::MarkSuccessfulService.new(purchase).perform
purchase.handle_recommended_purchase if purchase.was_product_recommended
else
preorder = purchase.preorder
preorder.authorize!
error_message = preorder.errors.full_messages[0]
if purchase.is_test_purchase?
preorder.mark_test_authorization_successful!
elsif error_message.present?
Purchase::MarkFailedService.new(purchase).perform
else
preorder.mark_authorization_successful!
end
end
purchase.charge.update!(credit_card_id: purchase.credit_card.id)
end
def create_charge_for_seller_purchases(purchases, chargeable, off_session, setup_future_charges)
purchases_to_charge = purchases.reject do |purchase|
purchase.is_free_trial_purchase? || purchase.is_preorder_authorization? || purchase.is_test_purchase? ||
!purchase.errors.empty? || !purchase.in_progress?
end
if purchases_to_charge.present?
amount_cents = purchases_to_charge.sum(&:total_transaction_cents)
gumroad_amount_cents = purchases_to_charge.sum(&:total_transaction_amount_for_gumroad_cents)
merchant_account = purchases.first.merchant_account
seller = User.find(purchases.first.seller_id)
statement_description = seller.name_or_username
mandate_options = mandate_options_for_stripe(purchases: purchases_to_charge)
charge = Charge::CreateService.new(
order:,
seller:,
merchant_account:,
chargeable:,
purchases: purchases_to_charge,
amount_cents:,
gumroad_amount_cents:,
setup_future_charges:,
off_session:,
statement_description:,
mandate_options: setup_future_charges ? mandate_options : nil,
).perform
self.charge_intent = charge.charge_intent
charge.credit_card.update!(json_data: { stripe_payment_intent_id: charge_intent.id }) if charge.credit_card&.requires_mandate?
if charge_intent&.succeeded?
purchases.each do |purchase|
if purchases_to_charge.include?(purchase)
purchase.paypal_order_id = charge.paypal_order_id if charge.paypal_order_id.present?
if charge_intent.is_a? StripeChargeIntent
purchase.build_processor_payment_intent(intent_id: charge_intent.id)
end
purchase.save_charge_data(charge_intent.charge, chargeable:)
end
next unless purchase.in_progress? && purchase.errors.empty?
Purchase::MarkSuccessfulService.new(purchase).perform
purchase.handle_recommended_purchase if purchase.was_product_recommended
end
elsif charge_intent&.requires_action?
purchases_to_charge.each do |purchase|
if purchase.processor_payment_intent.present?
purchase.processor_payment_intent.update!(intent_id: charge_intent.id)
else
purchase.create_processor_payment_intent!(intent_id: charge_intent.id)
end
end
else
purchases.each do |purchase|
next unless purchase.in_progress? && purchase.errors.empty?
purchase.errors.add :base, "Sorry, something went wrong."
end
end
end
end
def ensure_all_purchases_processed(purchases)
purchases.each do |purchase|
line_item_uid = params[:line_items].find do |line_item|
purchase.link.unique_permalink == line_item[:permalink] &&
(line_item[:variants].blank? || purchase.variant_attributes.first&.external_id == line_item[:variants]&.first)
end[:uid]
next if charge_responses[line_item_uid].present?
if purchase.errors.present? || purchase.failed?
charge_responses[line_item_uid] = error_response(purchase.errors.first&.message || "Sorry, something went wrong. Please try again.", purchase:)
end
# Mark purchases that are still stuck in progress as failed
# unless there's an SCA verification pending in which case all purchases
# are expected to be in progress, and we schedule a job to check them back later.
if purchase.in_progress?
if charge_intent&.requires_action? || setup_intent&.requires_action?
# Check back later to see if the purchase has been completed. If not, transition to a failed state.
FailAbandonedPurchaseWorker.perform_in(ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase.id)
else
Purchase::MarkFailedService.new(purchase).perform
end
end
if purchase.errors.present? || purchase.failed?
charge_responses[line_item_uid] ||= error_response(purchase.errors.first&.message || "Sorry, something went wrong. Please try again.", purchase:)
elsif charge_intent&.requires_action?
charge_responses[line_item_uid] ||= {
success: true,
requires_card_action: true,
client_secret: charge_intent.client_secret,
order: {
id: order.external_id,
stripe_connect_account_id: order.charges.last.merchant_account.is_a_stripe_connect_account? ? order.charges.last.merchant_account.charge_processor_merchant_id : nil
}
}
elsif setup_intent&.requires_action?
charge_responses[line_item_uid] ||= {
success: true,
requires_card_setup: true,
client_secret: setup_intent.client_secret,
order: {
id: order.external_id,
stripe_connect_account_id: order.purchases.last.merchant_account.is_a_stripe_connect_account? ? order.purchases.last.merchant_account.charge_processor_merchant_id : nil
}
}
else
charge_responses[line_item_uid] ||= purchase.purchase_response
purchase.handle_recommended_purchase if purchase.was_product_recommended
end
end
end
def mandate_options_for_stripe(purchases:, with_currency: false)
return purchases.first.mandate_options_for_stripe(with_currency:) if purchases.count == 1
mandate_amount = purchases.max_by(&:total_transaction_cents).total_transaction_cents
mandate_options = {
payment_method_options: {
card: {
mandate_options: {
reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex,
amount_type: "maximum",
amount: mandate_amount,
start_date: Time.current.to_i,
interval: "sporadic",
supported_types: ["india"]
}
}
}
}
mandate_options[:payment_method_options][:card][:mandate_options][:currency] = "usd" if with_currency
mandate_options
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/order/create_service.rb | app/services/order/create_service.rb | # frozen_string_literal: true
class Order::CreateService
include Order::ResponseHelpers
attr_accessor :params, :buyer, :order
PARAM_TO_ATTRIBUTE_MAPPINGS = {
friend: :friend_actions,
plugins: :purchaser_plugins,
vat_id: :business_vat_id,
is_preorder: :is_preorder_authorization,
cc_zipcode: :credit_card_zipcode,
tax_country_election: :sales_tax_country_code_election
}.freeze
PARAMS_TO_REMOVE_IF_BLANK = [:full_name, :email].freeze
def initialize(params:, buyer: nil)
@params = params
@buyer = buyer
end
def perform
common_params = params.except(:line_items)
line_items = params.fetch(:line_items, [])
offer_codes = {}
order = Order.new(purchaser: buyer)
purchase_responses = {}
cart_items = line_items.map { _1.slice(:permalink, :price_cents) }
line_items.each do |line_item_params|
product = Link.find_by(unique_permalink: line_item_params[:permalink])
line_item_uid = line_item_params[:uid]
if product.nil?
purchase_responses[line_item_uid] = error_response("Product not found")
next
end
begin
purchase_params = build_purchase_params(
product,
common_params
.except(
:billing_agreement_id, :paypal_order_id, :visual, :stripe_payment_method_id, :stripe_customer_id,
:stripe_error, :braintree_transient_customer_store_key, :braintree_device_data,
:use_existing_card, :paymentToken
)
.merge(line_item_params.except(:uid, :permalink))
.merge({ cart_items: })
)
purchase, error = Purchase::CreateService.new(
product:,
params: purchase_params.merge(is_part_of_combined_charge: true),
buyer:
).perform
if error
purchase_responses[line_item_uid] = error_response(error, purchase:)
if line_item_params[:discount_code].present?
offer_codes[line_item_params[:discount_code]] ||= {}
offer_codes[line_item_params[:discount_code]][product.unique_permalink] = { permalink: product.unique_permalink, quantity: line_item_params[:quantity], discount_code: line_item_params[:discount_code] }
end
end
if purchase&.persisted?
order.purchases << purchase
order.save!
if buyer.present? && buyer.email.blank? && !User.where(email: purchase.email).or(User.where(unconfirmed_email: purchase.email)).exists?
buyer.update!(email: purchase.email)
end
end
end
end
if order.persisted? && (cart = Cart.fetch_by(user: buyer, browser_guid: params[:browser_guid]))
cart.order = order
cart.mark_deleted!
end
offer_codes = offer_codes
.map { |offer_code, products| { code: offer_code, result: OfferCodeDiscountComputingService.new(offer_code, products).process } }
.filter_map do |response|
{
code: response[:code],
products: response[:result][:products_data].transform_values { _1[:discount] },
} if response[:result][:error_code].blank?
end
return order, purchase_responses, offer_codes
end
private
def build_purchase_params(product, purchase_params)
purchase_params = purchase_params.to_hash.symbolize_keys
purchase_params[:purchase] = purchase_params[:purchase].symbolize_keys if purchase_params[:purchase].is_a? Hash
# merge in params under `purchase` key to top level
purchase_params.merge!(purchase_params.delete(:purchase)) if purchase_params[:purchase].is_a? Hash
# rename certain params to match purchase attributes
PARAM_TO_ATTRIBUTE_MAPPINGS.each do |param, attribute|
purchase_params[attribute] = purchase_params.delete(param) if purchase_params.has_key?(param)
end
# remove certain keys if blank
PARAMS_TO_REMOVE_IF_BLANK.each do |param|
purchase_params.delete(param) if purchase_params[param].blank?
end
# additional manipulations
purchase_params[:perceived_price_cents] = purchase_params[:perceived_price_cents].try(:to_i)
purchase_params[:recommender_model_name] = purchase_params[:recommender_model_name].presence
purchase_params.delete(:credit_card_zipcode) unless params[:cc_zipcode_required]
if params[:demo]
purchase_params.delete(:price_range)
else
purchase_params.merge!(
session_id: params[:session_id],
ip_country: GeoIp.lookup(params[:ip_address]).try(:country_name),
ip_state: GeoIp.lookup(params[:ip_address]).try(:region_name),
is_mobile: params[:is_mobile],
browser_guid: params[:browser_guid]
)
end
# For some users, the product page reloads without the query string after loading the page. We are yet to identify why this happens.
# Meanwhile, we can set the url_parameters from referrer when it's missing in the request.
# Related GH issue: https://github.com/gumroad/web/issues/18190
# TODO (ershad): Remove parsing url_parameters from referrer after fixing the root issue.
if purchase_params[:url_parameters].blank? || purchase_params[:url_parameters] == "{}"
purchase_params[:url_parameters] = parse_url_parameters_from_referrer(product)
end
gift_params = purchase_params.extract!(:giftee_email, :giftee_id, :gift_note)
additional_params = purchase_params.extract!(
:is_gift, :price_id, :wallet_type, :perceived_free_trial_duration, :accepted_offer,
:cart_items, :variants, :bundle_products, :custom_fields, :tip_cents, :call_start_time,
:pay_in_installments
)
{
purchase: purchase_params,
gift: gift_params,
}.merge(additional_params.to_hash.deep_symbolize_keys)
end
def parse_url_parameters_from_referrer(product)
return if params[:referrer].blank? || params[:referrer] == "direct"
return unless params[:referrer].match?(/\/l\/(#{product.unique_permalink}|#{product.custom_permalink})\?[[:alnum:]]+/)
# Do not parse the params if referrer URL doesn't contain a valid product URL domain
creator = product.user
valid_product_url_domains = VALID_REQUEST_HOSTS.map { |domain| "#{PROTOCOL}://#{domain}" }
valid_product_url_domains << creator.subdomain_with_protocol if creator.subdomain_with_protocol.present?
valid_product_url_domains << "#{PROTOCOL}://#{creator.custom_domain.domain}" if creator.custom_domain.present?
return unless valid_product_url_domains.any? { |product_url_domain| params[:referrer].starts_with?(product_url_domain) }
CGI.parse(URI.parse(params[:referrer]).query).transform_values { |values| values.length <= 1 ? values.first : values }.to_json
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/order/confirm_service.rb | app/services/order/confirm_service.rb | # frozen_string_literal: true
# Finalizes the order once the charge SCA has been confirmed by the user on the front-end.
class Order::ConfirmService
include Order::ResponseHelpers
attr_reader :order, :params
def initialize(order:, params:)
@order = order
@params = params
end
def perform
purchase_responses = {}
offer_codes = {}
order.purchases.each do |purchase|
error = Purchase::ConfirmService.new(purchase:, params:).perform
if error
if purchase.offer_code.present?
offer_codes[purchase.offer_code.code] ||= {}
offer_codes[purchase.offer_code.code][purchase.link.unique_permalink] = { permalink: purchase.link.unique_permalink,
quantity: purchase.quantity,
discount_code: purchase.offer_code.code }
end
purchase_responses[purchase.id] = error_response(error, purchase:)
else
purchase_responses[purchase.id] = purchase.purchase_response
end
end
offer_codes = offer_codes.filter_map do |offer_code, products|
response = { code: offer_code, result: OfferCodeDiscountComputingService.new(offer_code, products).process }
next if response[:result][:error_code].present?
{ code: response[:code], products: response[:result][:products_data].transform_values { _1[:discount] } }
end
return purchase_responses, offer_codes
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/order/response_helpers.rb | app/services/order/response_helpers.rb | # frozen_string_literal: true
module Order::ResponseHelpers
include CurrencyHelper
private
def error_response(error_message, purchase: nil)
card_country = purchase&.card_country
card_country = "CN" if card_country == "C2" # PayPal (wrongly) returns CN2 for China users transacting with USD
{
success: false,
error_message:,
permalink: purchase&.link&.unique_permalink,
name: purchase&.link&.name,
formatted_price: formatted_price(Currency::USD, purchase&.total_transaction_cents_usd),
error_code: purchase&.error_code,
is_tax_mismatch: purchase&.error_code == PurchaseErrorCode::TAX_VALIDATION_FAILED,
card_country: (ISO3166::Country[card_country]&.common_name if card_country.present?),
ip_country: purchase&.ip_country,
updated_product: purchase.present? ? CheckoutPresenter.new(logged_in_user: nil, ip: purchase.ip_address).checkout_product(purchase.link, purchase.link.cart_item({ rent: purchase.is_rental, option: purchase.variant_attributes.first&.external_id, recurrence: purchase.price&.recurrence, price: purchase.customizable_price? ? purchase.displayed_price_cents : nil }), { recommended_by: purchase.recommended_by.presence }) : nil,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/helper/unblock_email_service.rb | app/services/helper/unblock_email_service.rb | # frozen_string_literal: true
class Helper::UnblockEmailService
include ActionView::Helpers::TextHelper
attr_accessor :recent_blocked_purchase
def initialize(conversation_id:, email_id:, email:)
@conversation_id = conversation_id
@email_id = email_id
@email = email
@recent_blocked_purchase = nil
end
def process
return if Feature.inactive?(:helper_unblock_emails)
@replied = unblock_email_blocked_by_gumroad
@replied |= unblock_email_suppressed_by_sendgrid
@replied |= process_email_blocked_by_creator
end
def replied? = @replied.present?
private
attr_reader :email, :conversation_id
REPLIES = {
blocked_by_gumroad: <<~REPLY,
Hey there,
Happy to help today! We noticed your purchase attempts failed as they were flagged as potentially fraudulent. Don’t worry, our system can occasionally throw a false alarm.
We have removed these blocks, so could you please try making the purchase again? In case it still fails, we recommend trying with a different browser and/or a different internet connection.
If those attempts still don't work, feel free to write back to us and we will investigate further.
Thanks!
REPLY
suppressed_by_sendgrid: <<~REPLY,
Hey,
Sorry about that! It seems our email provider stopped sending you emails after a few of them bounced.
I’ve fixed this and you should now start receiving emails as usual. Please let us know if you don't and we'll take a closer look!
Also, please add our email to your contacts list and ensure that you haven't accidentally marked any emails from us as spam.
Hope this helps!
REPLY
blocked_by_creator: <<~REPLY,
Hey there,
It looks like a creator has blocked you from purchasing their products. Please reach out to them directly to resolve this.
Feel free to write back to us if you have any questions.
Thanks!
REPLY
}.freeze
private_constant :REPLIES
def helper
@helper ||= Helper::Client.new
end
def unblock_email_blocked_by_gumroad
if recent_blocked_purchase.present?
unblock_buyer!(purchase: recent_blocked_purchase)
else
blocked_email = BlockedObject.email.find_active_object(email)
return unless blocked_email.present?
blocked_email.unblock!
end
send_reply(REPLIES[:blocked_by_gumroad])
end
def unblock_email_suppressed_by_sendgrid
email_suppression_manager = EmailSuppressionManager.new(email)
reasons = format_reasons(email_suppression_manager.reasons_for_suppression)
add_note_to_conversation(reasons) if reasons.present?
unblocked = email_suppression_manager.unblock_email
send_reply(REPLIES[:suppressed_by_sendgrid]) if unblocked && !replied?
end
def process_email_blocked_by_creator
blocked_email = BlockedCustomerObject.email.where(object_value: email).present?
return unless blocked_email.present?
send_reply(REPLIES[:blocked_by_creator], draft: true) unless replied?
end
def add_note_to_conversation(message)
helper.add_note(conversation_id:, message:)
end
def send_reply(reply, draft: false)
Rails.logger.info "[Helper::UnblockEmailService] Replied to conversation #{@conversation_id}"
formatted_reply = simple_format(reply)
if Feature.active?(:auto_reply_for_blocked_emails_in_helper) && !draft
helper.send_reply(conversation_id:, message: formatted_reply)
helper.close_conversation(conversation_id:)
else
helper.send_reply(conversation_id:, message: formatted_reply, draft: true, response_to: @email_id)
end
end
def unblock_buyer!(purchase:)
purchase.unblock_buyer!
comment_content = "Buyer unblocked by Helper webhook"
purchase.comments.create!(content: comment_content, comment_type: "note", author_id: GUMROAD_ADMIN_ID)
if purchase.purchaser.present?
purchase.purchaser.comments.create!(content: comment_content,
comment_type: "note",
author_id: GUMROAD_ADMIN_ID,
purchase:)
end
end
def bullet_list(lines)
lines.map { |line| "• #{line}" }.join("\n")
end
def format_reasons(reasons)
formatted_reasons = reasons.flat_map do |sendgrid_subuser, suppressions|
suppressions.flat_map do |supression|
"The email #{email} was suppressed in SendGrid. Subuser: #{sendgrid_subuser}, List: #{supression[:list]}, Reason: #{supression[:reason]}"
end
end
bullet_list(formatted_reasons)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/helper/client.rb | app/services/helper/client.rb | # frozen_string_literal: true
##
# Collection of methods to use Helper API.
##
class Helper::Client
include HTTParty
base_uri "https://api.helper.ai"
HELPER_MAILBOX_SLUG = "gumroad"
def create_hmac_digest(params: nil, json: nil)
if (params.present? && json.present?) || (params.nil? && json.nil?)
raise "Either params or json must be provided, but not both"
end
serialized_params = json ? json.to_json : params.to_query
OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), GlobalConfig.get("HELPER_WIDGET_SECRET"), serialized_params)
end
def add_note(conversation_id:, message:)
params = { message:, timestamp: }
headers = get_auth_headers(json: params)
response = self.class.post("/api/v1/mailboxes/#{HELPER_MAILBOX_SLUG}/conversations/#{conversation_id}/notes/", headers:, body: params.to_json)
Bugsnag.notify("Helper error: could not add note", conversation_id:, message:) unless response.success?
response.success?
end
def send_reply(conversation_id:, message:, draft: false, response_to: nil)
params = { message:, response_to:, draft:, timestamp: }
headers = get_auth_headers(json: params)
response = self.class.post("/api/v1/mailboxes/#{HELPER_MAILBOX_SLUG}/conversations/#{conversation_id}/emails/", headers:, body: params.to_json)
Bugsnag.notify("Helper error: could not send reply", conversation_id:, message:) unless response.success?
response.success?
end
def close_conversation(conversation_id:)
params = { status: "closed", timestamp: }
headers = get_auth_headers(json: params)
response = self.class.patch("/api/v1/mailboxes/#{HELPER_MAILBOX_SLUG}/conversations/#{conversation_id}/", headers:, body: params.to_json)
Bugsnag.notify("Helper error: could not close conversation", conversation_id:) unless response.success?
response.success?
end
private
def get_auth_headers(params: nil, json: nil)
hmac_base64 = Base64.encode64(create_hmac_digest(params:, json:))
{
"Content-Type" => "application/json",
"Authorization" => "Bearer #{hmac_base64}"
}
end
def timestamp
DateTime.current.to_i
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/backfill_payment_option_installment_snapshots.rb | app/services/onetime/backfill_payment_option_installment_snapshots.rb | # frozen_string_literal: true
module Onetime
class BackfillPaymentOptionInstallmentSnapshots
def self.perform
PaymentOption.where.not(product_installment_plan_id: nil)
.where.missing(:installment_plan_snapshot)
.find_each do |payment_option|
next unless payment_option.installment_plan.present?
next unless payment_option.subscription&.original_purchase.present?
subscription = payment_option.subscription
installment_plan = payment_option.installment_plan
total_price = calculate_total_price_from_history(subscription, installment_plan)
next unless total_price
InstallmentPlanSnapshot.create!(
payment_option: payment_option,
number_of_installments: installment_plan.number_of_installments,
recurrence: installment_plan.recurrence,
total_price_cents: total_price
)
rescue StandardError => e
Rails.logger.error("Failed to backfill PaymentOption #{payment_option.id}: #{e.message}")
end
end
def self.calculate_total_price_from_history(subscription, installment_plan)
all_installment_purchases = subscription.purchases
.successful
.is_installment_payment
.order(:created_at)
if all_installment_purchases.count <= 1
Rails.logger.info(
"Skipping subscription #{subscription.id}: insufficient payment history " \
"(#{all_installment_purchases.count} payment(s), need at least 2 to reliably determine total price)"
)
return nil
end
completed_installments_count = all_installment_purchases.count
expected_installments_count = installment_plan.number_of_installments
if completed_installments_count == expected_installments_count
return all_installment_purchases.sum(:price_cents)
end
first_payment, second_payment, *_rest = all_installment_purchases
remainder = first_payment.price_cents - second_payment.price_cents
if remainder >= 0 && remainder < expected_installments_count
return second_payment.price_cents * expected_installments_count + remainder
end
Rails.logger.warn(
"Skipping subscription #{subscription.id}: price likely changed mid-subscription. " \
"First payment: #{first_payment.price_cents}, second: #{second_payment.price_cents}, " \
"remainder: #{remainder}, expected count: #{expected_installments_count}"
)
nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/notify_sellers_about_paypal_payouts_removal.rb | app/services/onetime/notify_sellers_about_paypal_payouts_removal.rb | # frozen_string_literal: true
class Onetime::NotifySellersAboutPaypalPayoutsRemoval
def self.process
User.alive.not_suspended
.where("users.id > ?", $redis.get("notified_paypal_removal_till_user_id").to_i)
.joins(:user_compliance_infos)
.where("user_compliance_info.deleted_at IS NULL AND user_compliance_info.country IN (?)", User::Compliance.const_get(:SUPPORTED_COUNTRIES).map(&:common_name) - ["India", "United Arab Emirates"])
.joins(:payments)
.where("payments.processor = 'paypal' AND payments.state = 'completed' and payments.created_at > ?", Date.new(2025, 1, 1))
.order("users.id")
.select("users.id")
.distinct
.each do |user|
ReplicaLagWatcher.watch
ContactingCreatorMailer.paypal_suspension_notification(user.id).deliver_later
$redis.set("notified_paypal_removal_till_user_id", user.id)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/services/onetime/credit_gumroad_sales_fees.rb | app/services/onetime/credit_gumroad_sales_fees.rb | # frozen_string_literal: true
class Onetime::CreditGumroadSalesFees
GUMROAD_DAY = Date.parse("07-04-2021")
LAST_PURCHASE_TO_PROCESS = 36_793_417
VIPUL_USER_ID = 2_241_816
attr_accessor :purchases_to_credit_by_seller
def initialize
@purchases_to_credit_by_seller = Hash.new { |hash, key| hash[key] = [] }
end
def process
identify_purchases_to_credit
create_credits_and_notify_sellers
end
def identify_purchases_to_credit
Purchase.where("created_at > ? AND id < ? AND fee_cents > 0", GUMROAD_DAY, LAST_PURCHASE_TO_PROCESS).successful
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.find_each do |purchase|
if purchase.created_at.in_time_zone("Eastern Time (US & Canada)").to_date == GUMROAD_DAY
Rails.logger.info("Processing credit for purchase with id :: #{purchase.id}")
purchases_to_credit_by_seller[purchase.seller.id] << purchase.id
end
end
end
def create_credits_and_notify_sellers
vipul = User.find(VIPUL_USER_ID)
Rails.logger.info("Sending notifications for all new_credits_by_seller :: #{purchases_to_credit_by_seller}")
purchases_to_credit_by_seller.each do |user_id, purchases_to_credit|
user = User.find user_id
total_credits = user.sales.where(id: purchases_to_credit).map(&:total_fee_cents).sum
Credit.create_for_credit!(user:,
amount_cents: total_credits,
crediting_user: vipul)
ContactingCreatorMailer.gumroad_day_credit_notification(user_id,
total_credits).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/services/onetime/decrease_max_affiliate_basis_points.rb | app/services/onetime/decrease_max_affiliate_basis_points.rb | # frozen_string_literal: true
class Onetime::DecreaseMaxAffiliateBasisPoints
def self.process
SelfServiceAffiliateProduct.where("affiliate_basis_points > ?", max_affiliate_basis_points).find_each do |affiliate_product|
affiliate_product.update(affiliate_basis_points: max_affiliate_basis_points)
end
Affiliate.where("affiliate_basis_points > ?", max_affiliate_basis_points).find_each do |affiliate|
affiliate.update(affiliate_basis_points: max_affiliate_basis_points)
end
end
def self.max_affiliate_basis_points
Affiliate::BasisPointsValidations::MAX_AFFILIATE_BASIS_POINTS
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.