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/models/gabon_bank_account.rb | app/models/gabon_bank_account.rb | # frozen_string_literal: true
class GabonBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "GA"
BANK_CODE_FORMAT_REGEX = /^[0-9A-Za-z]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9]{23}$/
private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::GAB.alpha2
end
def currency
Currency::XAF
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/uae_bank_account.rb | app/models/uae_bank_account.rb | # frozen_string_literal: true
class UaeBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AE"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::ARE.alpha2
end
def currency
Currency::AED
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/customer_email_info.rb | app/models/customer_email_info.rb | # frozen_string_literal: true
class CustomerEmailInfo < EmailInfo
EMAIL_INFO_TYPE = "customer"
def self.find_or_initialize_for_charge(charge_id:, email_name:)
# Queries `email_info_charges` first to leverage the index since there is no `purchase_id` on the associated
# `email_infos` record (`email_infos` has > 1b records, and relies on `purchase_id` index)
email_info = EmailInfoCharge.includes(:email_info)
.where(charge_id:)
.where(email_infos: { email_name: "receipt", type: CustomerEmailInfo.name })
.last&.email_info
return email_info if email_info.present?
email_info = CustomerEmailInfo.new(email_name:)
email_info.assign_attributes(email_info_charge_attributes: { charge_id: })
email_info
end
def self.find_or_initialize_for_purchase(purchase_id:, email_name:)
CustomerEmailInfo.where(email_name:, purchase_id:).last || CustomerEmailInfo.new(email_name:, purchase_id:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/preorder_link.rb | app/models/preorder_link.rb | # frozen_string_literal: true
class PreorderLink < ApplicationRecord
REMINDER_EMAIL_TO_RELEASE_TIME = 1.day # Send the seller reminder email 1 day before the release time.
belongs_to :link, optional: true
has_many :preorders
validates :link, presence: true
validates :release_at, presence: true
validate :release_at_validation, if: ->(preorder_link) { preorder_link.changes["release_at"].present? }
attr_accessor :is_being_manually_released_by_the_seller
state_machine(:state, initial: :unreleased) do
before_transition unreleased: :released, do: :eligible_for_release?
after_transition unreleased: :released, do: :mark_link_as_released
after_transition unreleased: :released, do: :charge_successful_preorders
event :mark_released do
transition unreleased: :released
end
end
def build_preorder(authorization_purchase)
preorders.build(seller: link.user,
purchaser: authorization_purchase.purchaser,
purchases: [authorization_purchase])
end
def revenue_cents
link.sales.successful.where("preorder_id is not null").sum(:price_cents)
end
def release!
# Lock the object to guarantee that no two jobs will try to release the product at the same time.
# There are other safeguards against that, but locking here as well in order to increase confidence.
released_successfully = false
with_lock do
released_successfully = mark_released
end
released_successfully
end
private
def eligible_for_release?
return false if link.banned_at.present? || link.deleted_at.present?
return false if !link.alive? && !is_being_manually_released_by_the_seller
return false if !link.is_physical? && !link.has_content?
unless is_being_manually_released_by_the_seller
# Enforce that the pre-order's release time should be in the past, unless the seller is manually releasing the product.
return false if !link.is_in_preorder_state? || release_at > 1.minute.from_now # Account for slight time differences between instances
end
true
end
def mark_link_as_released
link.update(is_in_preorder_state: false)
# past this point no new preorders will be created for this product
end
def charge_successful_preorders
ChargeSuccessfulPreordersWorker.perform_in(5.seconds, id)
end
def release_at_validation
errors.add :base, "The release time of your pre-order has to be at least 24 hours from now." if release_at <= 24.hours.from_now
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_installment_plan.rb | app/models/product_installment_plan.rb | # frozen_string_literal: true
class ProductInstallmentPlan < ApplicationRecord
include CurrencyHelper
include Deletable
belongs_to :link, inverse_of: :installment_plan
has_many :payment_options, dependent: :restrict_with_exception
enum :recurrence,
BasePrice::Recurrence::ALLOWED_INSTALLMENT_PLAN_RECURRENCES.index_by(&:itself), default: "monthly"
validates :number_of_installments,
presence: true, numericality: { only_integer: true, greater_than: 1 }
validate :validate_product_eligibility, unless: :being_marked_as_deleted?
validate :validate_bundle_content_eligibility, unless: :being_marked_as_deleted?
validate :validate_installment_payment_price, unless: :being_marked_as_deleted?
ELIGIBLE_PRODUCT_NATIVE_TYPES = [
Link::NATIVE_TYPE_CALL,
Link::NATIVE_TYPE_COURSE,
Link::NATIVE_TYPE_DIGITAL,
Link::NATIVE_TYPE_EBOOK,
Link::NATIVE_TYPE_BUNDLE,
].to_set.freeze
class << self
def eligible_for_product?(link)
eligibility_erorr_message_for_product(link).blank?
end
def eligibility_erorr_message_for_product(link)
if link.is_recurring_billing? || link.is_tiered_membership?
return "Installment plans are not available for membership products"
end
if link.is_in_preorder_state?
return "Installment plans are not available for pre-order products"
end
unless ELIGIBLE_PRODUCT_NATIVE_TYPES.include?(link.native_type)
return "Installment plans are not available for this product type"
end
nil
end
end
def calculate_installment_payment_price_cents(full_price_cents)
base_price = full_price_cents / number_of_installments
remainder = full_price_cents % number_of_installments
Array.new(number_of_installments) do |i|
i.zero? ? base_price + remainder : base_price
end
end
def destroy_if_no_payment_options!
destroy!
rescue ActiveRecord::DeleteRestrictionError
mark_deleted!
end
private
def validate_product_eligibility
if error_message = self.class.eligibility_erorr_message_for_product(link)
errors.add(:base, error_message)
end
end
def validate_bundle_content_eligibility
return unless link.is_bundle?
ineligible_products = link.bundle_products.alive.includes(:product)
.reject(&:eligible_for_installment_plans?)
if ineligible_products.any?
errors.add(:base, "Installment plan is not available for the bundled product: #{ineligible_products.first.product.name}")
end
end
def validate_installment_payment_price
if link.customizable_price?
errors.add(:base, 'Installment plans are not available for "pay what you want" pricing')
end
if link.currency["min_price"] * (number_of_installments || 0) > link.price_cents
errors.add(:base, "The minimum price for each installment must be at least #{formatted_amount_in_currency(link.currency["min_price"], link.price_currency_type, no_cents_if_whole: true)}.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/egypt_bank_account.rb | app/models/egypt_bank_account.rb | # frozen_string_literal: true
class EgyptBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "EG"
BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/
private_constant :BANK_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::EGY.alpha2
end
def currency
Currency::EGP
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/swiss_bank_account.rb | app/models/swiss_bank_account.rb | # frozen_string_literal: true
class SwissBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "CH"
ACCOUNT_NUMBER_FORMAT_REGEX = /\ACH[0-9]{7}[A-Za-z0-9]{12}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::CHE.alpha2
end
def currency
Currency::CHF
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/armenia_bank_account.rb | app/models/armenia_bank_account.rb | # frozen_string_literal: true
class ArmeniaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AM"
BANK_CODE_FORMAT_REGEX = /^[0-9A-Za-z]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{11,16}$/
private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
bank_code.to_s
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::ARM.alpha2
end
def currency
Currency::AMD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/imported_customer.rb | app/models/imported_customer.rb | # frozen_string_literal: true
class ImportedCustomer < ApplicationRecord
include ExternalId
include ActionView::Helpers::DateHelper
include Deletable
belongs_to :link, optional: true
belongs_to :importing_user, class_name: "User", optional: true
has_one :url_redirect
has_one :license
after_create :create_or_get_license
validates_presence_of :email
scope :by_ids, ->(ids) { where("id IN (?)", ids) }
def as_json(options = {})
json = super(only: %i[email created_at])
json.merge!(timestamp: "#{time_ago_in_words(purchase_date)} ago",
link_name: link.present? ? link.name : nil,
product_name: link.present? ? link.name : nil,
price: nil,
is_imported_customer: true,
purchase_email: email,
id: external_id)
json[:license_key] = license_key if !options[:without_license_key] && license_key
json[:can_update] = options[:pundit_user] ? Pundit.policy!(options[:pundit_user], self).update? : nil
json
end
def license_key
create_or_get_license.try(:serial)
end
private
def create_or_get_license
return nil unless link.try(:is_licensed?)
return license if license
license = create_license
license.link = link
license.save!
license
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/creator_email_click_summary.rb | app/models/creator_email_click_summary.rb | # frozen_string_literal: true
class CreatorEmailClickSummary
include Mongoid::Document
index({ installment_id: 1 }, { unique: true, name: "installment_index" })
field :installment_id, type: Integer
field :total_unique_clicks, type: Integer
field :urls, type: Hash
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/discover_search_suggestion.rb | app/models/discover_search_suggestion.rb | # frozen_string_literal: true
class DiscoverSearchSuggestion < ApplicationRecord
include Deletable
belongs_to :discover_search
scope :by_user_or_browser, ->(user:, browser_guid:) {
alive
.joins(:discover_search)
.where(discover_searches: user.present? ? { user: } : { browser_guid:, user: nil })
.order(created_at: :desc)
}
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/angola_bank_account.rb | app/models/angola_bank_account.rb | # frozen_string_literal: true
class AngolaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AO"
BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number, if: -> { Rails.env.production? }
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::AGO.alpha2
end
def currency
Currency::AOA
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mauritius_bank_account.rb | app/models/mauritius_bank_account.rb | # frozen_string_literal: true
class MauritiusBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MU"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}?$/
private_constant :BANK_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::MUS.alpha2
end
def currency
Currency::MUR
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/backtax_collection.rb | app/models/backtax_collection.rb | # frozen_string_literal: true
class BacktaxCollection < ApplicationRecord
belongs_to :user
belongs_to :backtax_agreement
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/legacy_permalink.rb | app/models/legacy_permalink.rb | # frozen_string_literal: true
class LegacyPermalink < ApplicationRecord
belongs_to :product, class_name: "Link", optional: true
validates :permalink, presence: true, format: { with: /\A[a-zA-Z0-9_-]+\z/ }, uniqueness: { case_sensitive: false }
validates_presence_of :product
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bank_account.rb | app/models/bank_account.rb | # frozen_string_literal: true
class BankAccount < ApplicationRecord
include ExternalId
include Deletable
belongs_to :user, optional: true
has_many :payments
belongs_to :credit_card, optional: true
encrypt_with_public_key :account_number,
symmetric: :never,
public_key: OpenSSL::PKey.read(GlobalConfig.get("STRONGBOX_GENERAL"),
GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")).public_key,
private_key: GlobalConfig.get("STRONGBOX_GENERAL")
alias_attribute :stripe_external_account_id, :stripe_bank_account_id
validates_presence_of :user, :account_number, :account_number_last_four, :account_holder_full_name,
message: "We could not save your bank account information."
after_create_commit :handle_stripe_bank_account
after_create_commit :handle_compliance_info_request
after_create :update_user_products_search_index
# This state machine can be expanded once we implement a complex verification process.
state_machine(:state, initial: :unverified) do
event :mark_verified do
transition unverified: :verified
end
end
# Public: The routing transit number that is the identifier used to reference
# the final destination institution/location where the funds will be delivered.
# In some countries this will be the bank number (e.g. US), in others it will be
# a combination of bank number and the branch code, or other fields.
def routing_number
bank_number
end
def account_number_visual
"******#{account_number_last_four}"
end
def formatted_account
"#{bank_name || routing_number} - #{account_number_visual}"
end
def bank_name
nil
end
def country
Compliance::Countries::USA.alpha2
end
def currency
Currency::USD
end
def to_hash
hash = {
bank_number:,
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
hash[:bank_name] = bank_name if bank_name.present?
hash
end
def mark_deleted!
self.deleted_at = Time.current
save!
end
def supports_instant_payouts?
return false unless stripe_connect_account_id.present? && stripe_external_account_id.present?
@supports_instant_payouts ||= begin
external_account = Stripe::Account.retrieve_external_account(
stripe_connect_account_id,
stripe_external_account_id
)
external_account.available_payout_methods.include?("instant")
rescue Stripe::StripeError => e
Bugsnag.notify(e)
false
end
end
private
def handle_stripe_bank_account
HandleNewBankAccountWorker.perform_in(5.seconds, id)
end
def handle_compliance_info_request
UserComplianceInfoRequest.handle_new_bank_account(self)
end
def account_number_decrypted
account_number.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))
end
def update_user_products_search_index
return if user.bank_accounts.alive.count > 1
user.products.find_each do |product|
product.enqueue_index_update_for(["is_recommendable"])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/country.rb | app/models/country.rb | # frozen_string_literal: true
class Country
include CurrencyHelper
CROSS_BORDER_PAYOUTS_COUNTRIES = [
Compliance::Countries::THA,
Compliance::Countries::KOR,
Compliance::Countries::ISR,
Compliance::Countries::TTO,
Compliance::Countries::PHL,
Compliance::Countries::MEX,
Compliance::Countries::ARG,
Compliance::Countries::PER,
Compliance::Countries::ALB,
Compliance::Countries::BHR,
Compliance::Countries::AZE,
Compliance::Countries::AGO,
Compliance::Countries::NER,
Compliance::Countries::SMR,
Compliance::Countries::NGA,
Compliance::Countries::JOR,
Compliance::Countries::IND,
Compliance::Countries::BIH,
Compliance::Countries::VNM,
Compliance::Countries::TWN,
Compliance::Countries::ATG,
Compliance::Countries::TZA,
Compliance::Countries::NAM,
Compliance::Countries::IDN,
Compliance::Countries::CRI,
Compliance::Countries::CHL,
Compliance::Countries::BWA,
Compliance::Countries::PAK,
Compliance::Countries::TUR,
Compliance::Countries::MAR,
Compliance::Countries::SRB,
Compliance::Countries::ZAF,
Compliance::Countries::ETH,
Compliance::Countries::BRN,
Compliance::Countries::GUY,
Compliance::Countries::GTM,
Compliance::Countries::KEN,
Compliance::Countries::EGY,
Compliance::Countries::COL,
Compliance::Countries::SAU,
Compliance::Countries::RWA,
Compliance::Countries::KAZ,
Compliance::Countries::ECU,
Compliance::Countries::MYS,
Compliance::Countries::URY,
Compliance::Countries::MUS,
Compliance::Countries::JAM,
Compliance::Countries::OMN,
Compliance::Countries::BGD,
Compliance::Countries::BTN,
Compliance::Countries::LAO,
Compliance::Countries::MOZ,
Compliance::Countries::DOM,
Compliance::Countries::UZB,
Compliance::Countries::BOL,
Compliance::Countries::TUN,
Compliance::Countries::MDA,
Compliance::Countries::MKD,
Compliance::Countries::PAN,
Compliance::Countries::SLV,
Compliance::Countries::MDG,
Compliance::Countries::PRY,
Compliance::Countries::GHA,
Compliance::Countries::ARM,
Compliance::Countries::LKA,
Compliance::Countries::KWT,
Compliance::Countries::ISL,
Compliance::Countries::QAT,
Compliance::Countries::BHS,
Compliance::Countries::LCA,
Compliance::Countries::SEN,
Compliance::Countries::KHM,
Compliance::Countries::MNG,
Compliance::Countries::GAB,
Compliance::Countries::MCO,
Compliance::Countries::DZA,
Compliance::Countries::MAC,
Compliance::Countries::BEN,
Compliance::Countries::CIV,
].freeze
private_constant :CROSS_BORDER_PAYOUTS_COUNTRIES
attr_reader :alpha2_code
def initialize(country_code)
@alpha2_code = country_code
end
def supports_stripe_cross_border_payouts?
CROSS_BORDER_PAYOUTS_COUNTRIES.map(&:alpha2).include?(alpha2_code)
end
def can_accept_stripe_charges?
!supports_stripe_cross_border_payouts?
end
def stripe_capabilities
supports_stripe_cross_border_payouts? ?
StripeMerchantAccountManager::CROSS_BORDER_PAYOUTS_ONLY_CAPABILITIES :
StripeMerchantAccountManager::REQUESTED_CAPABILITIES
end
def default_currency
case alpha2_code
when Compliance::Countries::USA.alpha2
Currency::USD
when Compliance::Countries::CAN.alpha2
Currency::CAD
when Compliance::Countries::SGP.alpha2
Currency::SGD
when Compliance::Countries::AUS.alpha2
Currency::AUD
when Compliance::Countries::GBR.alpha2
Currency::GBP
when Compliance::Countries::AUT.alpha2,
Compliance::Countries::BEL.alpha2,
Compliance::Countries::HRV.alpha2,
Compliance::Countries::CYP.alpha2,
Compliance::Countries::EST.alpha2,
Compliance::Countries::FIN.alpha2,
Compliance::Countries::FRA.alpha2,
Compliance::Countries::DEU.alpha2,
Compliance::Countries::GRC.alpha2,
Compliance::Countries::IRL.alpha2,
Compliance::Countries::ITA.alpha2,
Compliance::Countries::LVA.alpha2,
Compliance::Countries::LTU.alpha2,
Compliance::Countries::LUX.alpha2,
Compliance::Countries::MLT.alpha2,
Compliance::Countries::NLD.alpha2,
Compliance::Countries::PRT.alpha2,
Compliance::Countries::SVK.alpha2,
Compliance::Countries::SVN.alpha2,
Compliance::Countries::ESP.alpha2
Currency::EUR
when Compliance::Countries::HKG.alpha2
Currency::HKD
when Compliance::Countries::NZL.alpha2
Currency::NZD
when Compliance::Countries::SGP.alpha2
Currency::SGD
when Compliance::Countries::CHE.alpha2
Currency::CHF
when Compliance::Countries::POL.alpha2
Currency::PLN
when Compliance::Countries::CZE.alpha2
Currency::CZK
when Compliance::Countries::JPN.alpha2
Currency::JPY
when Compliance::Countries::LIE.alpha2
Currency::CHF
end
end
def payout_currency
case alpha2_code
when Compliance::Countries::THA.alpha2
Currency::THB
when Compliance::Countries::BGR.alpha2
Currency::EUR
when Compliance::Countries::DNK.alpha2
Currency::DKK
when Compliance::Countries::HUN.alpha2
Currency::HUF
when Compliance::Countries::KOR.alpha2
Currency::KRW
when Compliance::Countries::ARE.alpha2
Currency::AED
when Compliance::Countries::ISR.alpha2
Currency::ILS
when Compliance::Countries::TTO.alpha2
Currency::TTD
when Compliance::Countries::PHL.alpha2
Currency::PHP
when Compliance::Countries::ROU.alpha2
Currency::RON
when Compliance::Countries::SWE.alpha2
Currency::SEK
when Compliance::Countries::MEX.alpha2
Currency::MXN
when Compliance::Countries::BIH.alpha2
Currency::BAM
when Compliance::Countries::RWA.alpha2
Currency::RWF
when Compliance::Countries::ARG.alpha2
Currency::ARS
when Compliance::Countries::PER.alpha2
Currency::PEN
when Compliance::Countries::IND.alpha2
Currency::INR
when Compliance::Countries::VNM.alpha2
Currency::VND
when Compliance::Countries::TWN.alpha2
Currency::TWD
when Compliance::Countries::ATG.alpha2
Currency::XCD
when Compliance::Countries::TZA.alpha2
Currency::TZS
when Compliance::Countries::NAM.alpha2
Currency::NAD
when Compliance::Countries::IDN.alpha2
Currency::IDR
when Compliance::Countries::CRI.alpha2
Currency::CRC
when Compliance::Countries::NOR.alpha2
Currency::NOK
when Compliance::Countries::CHL.alpha2
Currency::CLP
when Compliance::Countries::PAK.alpha2
Currency::PKR
when Compliance::Countries::TUR.alpha2
Currency::TRY
when Compliance::Countries::MAR.alpha2
Currency::MAD
when Compliance::Countries::SRB.alpha2
Currency::RSD
when Compliance::Countries::ZAF.alpha2
Currency::ZAR
when Compliance::Countries::ETH.alpha2
Currency::ETB
when Compliance::Countries::BRN.alpha2
Currency::BND
when Compliance::Countries::GUY.alpha2
Currency::GYD
when Compliance::Countries::GTM.alpha2
Currency::GTQ
when Compliance::Countries::KEN.alpha2
Currency::KES
when Compliance::Countries::EGY.alpha2
Currency::EGP
when Compliance::Countries::COL.alpha2
Currency::COP
when Compliance::Countries::SAU.alpha2
Currency::SAR
when Compliance::Countries::KAZ.alpha2
Currency::KZT
when Compliance::Countries::BWA.alpha2
Currency::BWP
when Compliance::Countries::ECU.alpha2
Currency::USD
when Compliance::Countries::MYS.alpha2
Currency::MYR
when Compliance::Countries::URY.alpha2
Currency::UYU
when Compliance::Countries::MUS.alpha2
Currency::MUR
when Compliance::Countries::JAM.alpha2
Currency::JMD
when Compliance::Countries::DOM.alpha2
Currency::DOP
when Compliance::Countries::BGD.alpha2
Currency::BDT
when Compliance::Countries::BTN.alpha2
Currency::BTN
when Compliance::Countries::LAO.alpha2
Currency::LAK
when Compliance::Countries::MOZ.alpha2
Currency::MZN
when Compliance::Countries::UZB.alpha2
Currency::UZS
when Compliance::Countries::BOL.alpha2
Currency::BOB
when Compliance::Countries::MDA.alpha2
Currency::MDL
when Compliance::Countries::MKD.alpha2
Currency::MKD
when Compliance::Countries::PAN.alpha2
Currency::USD
when Compliance::Countries::SLV.alpha2
Currency::USD
when Compliance::Countries::GIB.alpha2
Currency::GBP
when Compliance::Countries::OMN.alpha2
Currency::OMR
when Compliance::Countries::TUN.alpha2
Currency::TND
when Compliance::Countries::ALB.alpha2
Currency::ALL
when Compliance::Countries::BHR.alpha2
Currency::BHD
when Compliance::Countries::AZE.alpha2
Currency::AZN
when Compliance::Countries::AGO.alpha2
Currency::AOA
when Compliance::Countries::NER.alpha2
Currency::XOF
when Compliance::Countries::SMR.alpha2
Currency::EUR
when Compliance::Countries::ARM.alpha2
Currency::AMD
when Compliance::Countries::LKA.alpha2
Currency::LKR
when Compliance::Countries::KWT.alpha2
Currency::KWD
when Compliance::Countries::JOR.alpha2
Currency::JOD
when Compliance::Countries::NGA.alpha2
Currency::NGN
when Compliance::Countries::MDG.alpha2
Currency::MGA
when Compliance::Countries::PRY.alpha2
Currency::PYG
when Compliance::Countries::GHA.alpha2
Currency::GHS
when Compliance::Countries::ISL.alpha2
Currency::EUR
when Compliance::Countries::QAT.alpha2
Currency::QAR
when Compliance::Countries::BHS.alpha2
Currency::BSD
when Compliance::Countries::LCA.alpha2
Currency::XCD
when Compliance::Countries::SEN.alpha2
Currency::XOF
when Compliance::Countries::KHM.alpha2
Currency::KHR
when Compliance::Countries::MNG.alpha2
Currency::MNT
when Compliance::Countries::GAB.alpha2
Currency::XAF
when Compliance::Countries::MCO.alpha2
Currency::EUR
when Compliance::Countries::DZA.alpha2
Currency::DZD
when Compliance::Countries::MAC.alpha2
Currency::MOP
when Compliance::Countries::BEN.alpha2
Currency::XOF
when Compliance::Countries::CIV.alpha2
Currency::XOF
else
default_currency
end
end
# Ref: https://docs.stripe.com/connect/cross-border-payouts/special-requirements#cross-border-minimum-payout-amounts-table
def min_cross_border_payout_amount_local_cents
case alpha2_code
when Compliance::Countries::ALB.alpha2 # Albania
3_000_00
when Compliance::Countries::DZA.alpha2 # Algeria
1_00
when Compliance::Countries::AGO.alpha2 # Angola
23_000_00
when Compliance::Countries::ATG.alpha2 # Antigua & Barbuda
1_00
when Compliance::Countries::ARG.alpha2 # Argentina
4_600_00
when Compliance::Countries::ARM.alpha2 # Armenia
12_100_00
when Compliance::Countries::AZE.alpha2 # Azerbaijan
50_00
when Compliance::Countries::BHS.alpha2 # Bahamas
1_00
when Compliance::Countries::BHR.alpha2 # Bahrain
1_00
when Compliance::Countries::BGD.alpha2 # Bangladesh
20_00
when Compliance::Countries::BEN.alpha2 # Benin
1_00
when Compliance::Countries::BTN.alpha2 # Bhutan
2_500_00
when Compliance::Countries::BOL.alpha2 # Bolivia
200_00
when Compliance::Countries::BIH.alpha2 # Bosnia & Herzegovina
50_00
when Compliance::Countries::BWA.alpha2 # Botswana
1_00
when Compliance::Countries::BRN.alpha2 # Brunei
1_00
when Compliance::Countries::BRN.alpha2 # Brunei
1_00
when Compliance::Countries::KHM.alpha2 # Cambodia
123_000_00
when Compliance::Countries::CHL.alpha2 # Chile
23_000_00
when Compliance::Countries::COL.alpha2 # Colombia
140_000_00
when Compliance::Countries::CRI.alpha2 # Costa Rica
0
when Compliance::Countries::CIV.alpha2 # Côte d’Ivoire
1_00
when Compliance::Countries::DOM.alpha2 # Dominican Republic
1_00
when Compliance::Countries::ECU.alpha2 # Ecuador
0
when Compliance::Countries::EGY.alpha2 # Egypt
20_00
when Compliance::Countries::SLV.alpha2 # El Salvador
30_00
when Compliance::Countries::ETH.alpha2 # Ethiopia
1_00
when Compliance::Countries::GAB.alpha2 # Gabon
100_00
when Compliance::Countries::GHA.alpha2 # Ghana
1_00
when Compliance::Countries::GTM.alpha2 # Guatemala
1_00
when Compliance::Countries::GUY.alpha2 # Guyana
6_300_00
when Compliance::Countries::ISL.alpha2 # Iceland
1_00
when Compliance::Countries::IND.alpha2 # India
1_00
when Compliance::Countries::IDN.alpha2 # Indonesia
1_00
when Compliance::Countries::ISR.alpha2 # Israel
0
when Compliance::Countries::JAM.alpha2 # Jamaica
1_00
when Compliance::Countries::JOR.alpha2 # Jordan
1_00
when Compliance::Countries::KAZ.alpha2 # Kazakhstan
1_00
when Compliance::Countries::KEN.alpha2 # Kenya
1_00
when Compliance::Countries::KWT.alpha2 # Kuwait
1_00
when Compliance::Countries::LAO.alpha2 # Laos
516_000_00
when Compliance::Countries::MAC.alpha2 # Macao SAR China
1_00
when Compliance::Countries::MDG.alpha2 # Madagascar
132_300_00
when Compliance::Countries::MYS.alpha2 # Malaysia
133_00
when Compliance::Countries::MUS.alpha2 # Mauritius
1_00
when Compliance::Countries::MEX.alpha2 # Mexico
10_00
when Compliance::Countries::MDA.alpha2 # Moldova
500_00
when Compliance::Countries::MCO.alpha2 # Monaco
1_00
when Compliance::Countries::MNG.alpha2 # Mongolia
105_000_00
when Compliance::Countries::MAR.alpha2 # Morocco
0
when Compliance::Countries::MOZ.alpha2 # Mozambique
1_700_00
when Compliance::Countries::NAM.alpha2 # Namibia
550_00
when Compliance::Countries::NER.alpha2 # Niger
1_00
when Compliance::Countries::NGA.alpha2 # Nigeria
1_00
when Compliance::Countries::MKD.alpha2 # North Macedonia
1_500_00
when Compliance::Countries::OMN.alpha2 # Oman
1_00
when Compliance::Countries::PAK.alpha2 # Pakistan
1_00
when Compliance::Countries::PAN.alpha2 # Panama
50_00
when Compliance::Countries::PRY.alpha2 # Paraguay
210_000_00
when Compliance::Countries::PER.alpha2 # Peru
0
when Compliance::Countries::PHL.alpha2 # Philippines
20_00
when Compliance::Countries::QAT.alpha2 # Qatar
1_00
when Compliance::Countries::RWA.alpha2 # Rwanda
100_00
when Compliance::Countries::SMR.alpha2 # San Marino
1_00
when Compliance::Countries::SAU.alpha2 # Saudi Arabia
1_00
when Compliance::Countries::SEN.alpha2 # Senegal
1_00
when Compliance::Countries::SRB.alpha2 # Serbia
3_000_00
when Compliance::Countries::ZAF.alpha2 # South Africa
100_00
when Compliance::Countries::KOR.alpha2 # South Korea
40_000_00
when Compliance::Countries::LKA.alpha2 # Sri Lanka
1_00
when Compliance::Countries::LCA.alpha2 # St. Lucia
1_00
when Compliance::Countries::TWN.alpha2 # Taiwan
800_00
when Compliance::Countries::TZA.alpha2 # Tanzania
800_00
when Compliance::Countries::THA.alpha2 # Thailand
600_00
when Compliance::Countries::TTO.alpha2 # Trinidad & Tobago
0
when Compliance::Countries::TUN.alpha2 # Tunisia
0
when Compliance::Countries::TUR.alpha2 # Turkey
5_00
when Compliance::Countries::URY.alpha2 # Uruguay
0
when Compliance::Countries::UZB.alpha2 # Uzbekistan
343_000_00
when Compliance::Countries::VNM.alpha2 # Vietnam
81_125_00
else
nil
end
end
def min_cross_border_payout_amount_usd_cents
return 0 unless payout_currency.present?
get_usd_cents(payout_currency, min_cross_border_payout_amount_local_cents.to_i)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/black_recurring_service.rb | app/models/black_recurring_service.rb | # frozen_string_literal: true
class BlackRecurringService < RecurringService
SERVICE_DESCRIPTION = "Gumroad Premium"
attr_json_data_accessor :change_recurrence_to
attr_json_data_accessor :invite_credit
# black recurring service state transitions:
#
# → pending_cancellation → cancelled
# ↑ ↓ ↓
# inactive → active ← ← ←
# ↓ ↑ ↑
# → pending_failure → failed
#
state_machine :state, initial: :inactive do
event :mark_active do
transition any => :active
end
event :mark_active_from_pending_cancellation do
transition pending_cancellation: :active
end
event :mark_pending_cancellation do
transition %i[active pending_failure] => :pending_cancellation
end
event :mark_cancelled do
transition pending_cancellation: :cancelled
end
event :mark_cancelled_immediately do
transition %i[active pending_cancellation pending_failure] => :cancelled
end
event :mark_pending_failure do
transition active: :pending_failure
end
event :mark_failed do
transition pending_failure: :failed
end
end
scope :active, -> { where(state: "active") }
scope :active_including_pending_cancellation, -> { where("state = 'active' or state = 'pending_cancellation'") }
def is_active?
active? || pending_cancellation? || pending_failure?
end
def service_description
SERVICE_DESCRIPTION
end
def discount_code
return unless invite_credit.present? && invite_credit > 0
self.invite_credit -= 1
save!
INVITE_CREDIT_DISCOUNT_CODE
end
def invite_discount_amount
return price_cents if recurrence == "monthly" && price_cents > 0
monthly_tier_amount_cents(user.distinct_paid_customers_count_last_year)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/cart.rb | app/models/cart.rb | # frozen_string_literal: true
class Cart < ApplicationRecord
include ExternalId
include Deletable
DISCOUNT_CODES_SCHEMA = {
"$schema": "http://json-schema.org/draft-06/schema#",
type: "array",
items: { "$ref": "#/$defs/discount_code" },
"$defs": {
discount_code: {
type: "object",
properties: {
code: { type: "string" },
fromUrl: { type: "boolean" },
},
required: [:code, :fromUrl]
},
}
}.freeze
ABANDONED_IF_UPDATED_AFTER_AGO = 1.month
ABANDONED_IF_UPDATED_BEFORE_AGO = 24.hours
MAX_ALLOWED_CART_PRODUCTS = 50
belongs_to :user, optional: true
belongs_to :order, optional: true
has_many :cart_products
has_many :alive_cart_products, -> { alive }, class_name: "CartProduct"
has_many :products, through: :cart_products
has_many :sent_abandoned_cart_emails
scope :abandoned, ->(updated_at: ABANDONED_IF_UPDATED_AFTER_AGO.ago.beginning_of_day..ABANDONED_IF_UPDATED_BEFORE_AGO.ago) do
alive
.where(updated_at:)
.left_outer_joins(:sent_abandoned_cart_emails)
.where(sent_abandoned_cart_emails: { id: nil })
.where(id: CartProduct.alive.select(:cart_id))
end
after_initialize :assign_default_discount_codes
validate :ensure_discount_codes_conform_to_schema
validate :ensure_only_one_alive_cart_per_user, on: :create
def abandoned?
alive? && updated_at >= ABANDONED_IF_UPDATED_AFTER_AGO.ago.beginning_of_day && updated_at <= ABANDONED_IF_UPDATED_BEFORE_AGO.ago && sent_abandoned_cart_emails.none? && alive_cart_products.exists?
end
def self.fetch_by(user:, browser_guid:)
return user.carts.alive.first if user.present?
alive.find_by(browser_guid:, user: nil) if browser_guid.present?
end
private
def assign_default_discount_codes
self.discount_codes = [] if discount_codes.nil?
end
def ensure_discount_codes_conform_to_schema
JSON::Validator.fully_validate(DISCOUNT_CODES_SCHEMA, discount_codes).each { errors.add(:discount_codes, _1) }
end
def ensure_only_one_alive_cart_per_user
if self.class.fetch_by(user:, browser_guid:).present?
errors.add(:base, "An alive cart already exists")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/gibraltar_bank_account.rb | app/models/gibraltar_bank_account.rb | # frozen_string_literal: true
class GibraltarBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "GI"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::GIB.alpha2
end
def currency
Currency::GBP
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/kenya_bank_account.rb | app/models/kenya_bank_account.rb | # frozen_string_literal: true
class KenyaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "KE"
BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9a-zA-Z]{1,32}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::KEN.alpha2
end
def currency
Currency::KES
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/large_seller.rb | app/models/large_seller.rb | # frozen_string_literal: true
# This table contains a list of users that have a large number sales.
# It's needed for the performance of the web analytics.
# Note that:
# - This has nothing to do with VIPs / sellers that have a large revenue.
# This is strictly about the number of `purchases` rows associated with a seller,
# whether they're free or not.
# - This model/table is destined to be deleted once we get faster analytics
# - This table isn't refreshed automatically, because we rarely need to update it
class LargeSeller < ApplicationRecord
SALES_LOWER_LIMIT = 1000
belongs_to :user, optional: true
def self.create_if_warranted(user)
return if where(user:).exists?
sales_count = user.sales.count
return if sales_count < SALES_LOWER_LIMIT
create!(user:, sales_count:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/thailand_bank_account.rb | app/models/thailand_bank_account.rb | # frozen_string_literal: true
class ThailandBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "TH"
BANK_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{6,15}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::THA.alpha2
end
def currency
Currency::THB
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/taiwan_bank_account.rb | app/models/taiwan_bank_account.rb | # frozen_string_literal: true
class TaiwanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "TW"
BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{10,14}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::TWN.alpha2
end
def currency
Currency::TWD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/botswana_bank_account.rb | app/models/botswana_bank_account.rb | # frozen_string_literal: true
class BotswanaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BW"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{1,16}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number, if: -> { Rails.env.production? }
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::BWA.alpha2
end
def currency
Currency::BWP
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/email_info.rb | app/models/email_info.rb | # frozen_string_literal: true
class EmailInfo < ApplicationRecord
include ExternalId
# Note: For performance, the state transitions (and validations) are ignored when sending
# an email in PostSendgridApi.
belongs_to :purchase, optional: true
belongs_to :installment, optional: true
has_one :email_info_charge, dependent: :destroy
accepts_nested_attributes_for :email_info_charge
delegate :charge_id, to: :email_info_charge, allow_nil: true
# EmailInfo state transitions:
#
# created → sent → delivered → opened
# ↓ ↑
# bounced
#
state_machine :state, initial: :created do
before_transition any => :sent, do: ->(email_info) { email_info.sent_at = Time.current }
before_transition any => :sent, :do => :clear_event_time_fields
before_transition any => :delivered, do: ->(email_info, transition) { email_info.delivered_at = transition.args.first || Time.current }
before_transition any => :opened, do: ->(email_info, transition) { email_info.opened_at = transition.args.first || Time.current }
after_transition any => :bounced, :do => :unsubscribe_buyer
event :mark_bounced do
transition any => :bounced
end
event :mark_sent do
transition any => :sent
end
event :mark_delivered do
transition any => :delivered
end
event :mark_opened do
transition any => :opened
end
end
def clear_event_time_fields
self.delivered_at = nil
self.opened_at = nil
end
def most_recent_state_at
if opened_at.present?
opened_at
elsif delivered_at.present?
delivered_at
else
sent_at
end
end
def unsubscribe_buyer
if charge_id
email_info_charge.charge.order.unsubscribe_buyer
else
purchase.orderable.unsubscribe_buyer
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/oauth_application.rb | app/models/oauth_application.rb | # frozen_string_literal: true
class OauthApplication < Doorkeeper::Application
include ExternalId
include Deletable
include CdnUrlHelper
has_many :resource_subscriptions, dependent: :destroy
has_many :affiliate_credits
has_many :links, foreign_key: :affiliate_application_id
belongs_to :owner, class_name: "User", optional: true
before_validation :set_default_scopes, on: :create
validates :scopes, presence: true
validate :affiliate_basis_points_must_fall_in_an_acceptable_range
validate :validate_file
ALLOW_CONTENT_TYPES = /jpeg|png|jpg/i
MOBILE_API_OAUTH_APPLICATION_UID = GlobalConfig.get("MOBILE_API_OAUTH_APPLICATION_UID")
def validate_file
return unless file.attached?
if !file.image? || !file.content_type.match?(ALLOW_CONTENT_TYPES)
errors.add(:base, "Invalid image type for icon, please try again.")
end
end
def mark_deleted!
transaction do
access_grants.where(revoked_at: nil).update_all(revoked_at: Time.current)
access_tokens.where(revoked_at: nil).update_all(revoked_at: Time.current)
resource_subscriptions.alive.each(&:mark_deleted!)
update!(deleted_at: Time.current)
end
end
def affiliate_basis_points_must_fall_in_an_acceptable_range
return if affiliate_basis_points.nil?
return if affiliate_basis_points >= 0 && affiliate_basis_points <= 7000
errors.add(:base, "Affiliate commission must be between 0% and 70%")
end
has_one_attached :file
def affiliate_basis_points=(affiliate_basis_points)
return unless self.affiliate_basis_points.nil?
self[:affiliate_basis_points] = affiliate_basis_points
end
def affiliate_percent
return nil if affiliate_basis_points.nil?
affiliate_basis_points / 100.0
end
# Returns an existing active access token or creates one if none exist
def get_or_generate_access_token
ensure_access_grant_exists
access_tokens.where(resource_owner_id: owner.id,
revoked_at: nil,
scopes: Doorkeeper.configuration.public_scopes.join(" ")).first_or_create!
end
def revoke_access_for(user)
Doorkeeper::AccessToken.revoke_all_for(id, user)
resource_subscriptions.where(user:).alive.each(&:mark_deleted!)
end
def icon_url
return unless file.attached?
cdn_url_for(file.url)
end
private
def ensure_access_grant_exists
access_grants.where(resource_owner_id: owner.id,
scopes: Doorkeeper.configuration.public_scopes.join(" "),
redirect_uri:).first_or_create! { |access_grant| access_grant.expires_in = 60.years }
end
def set_default_scopes
self.scopes = Doorkeeper.configuration.public_scopes.join(" ") unless self.scopes.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sku.rb | app/models/sku.rb | # frozen_string_literal: true
class Sku < BaseVariant
belongs_to :link, optional: true
has_and_belongs_to_many :variants, join_table: :skus_variants
delegate :user, to: :link
validates_presence_of :link
def as_json(options = {})
json = super(options)
json["custom_sku"] = custom_sku if custom_sku
json
end
def sku_category_name
link.sku_title
end
def custom_name_or_external_id
custom_sku.presence || external_id
end
# Public: This method returns the remaining inventory considering the product's overall quantity limitation as well as this SKU's.
# Returns Float::INFINITY when no inventory limitation exists.
def inventory_left
product_quantity_left = link.max_purchase_count ? [(link.max_purchase_count - link.sales_count_for_inventory), 0].max : Float::INFINITY
quantity_left ? [quantity_left, product_quantity_left].min : product_quantity_left
end
def to_option_for_product
{
id: external_id,
name:,
quantity_left:,
description: description || "",
price_difference_cents:,
recurrence_price_values: nil,
is_pwyw: false,
duration_in_minutes:,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_taxjar_info.rb | app/models/purchase_taxjar_info.rb | # frozen_string_literal: true
class PurchaseTaxjarInfo < ApplicationRecord
belongs_to :purchase
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_cached_value.rb | app/models/product_cached_value.rb | # frozen_string_literal: true
class ProductCachedValue < ApplicationRecord
belongs_to :product, class_name: "Link", optional: true
before_create :assign_cached_values
validates_presence_of :product
scope :fresh, -> { where(expired: false) }
scope :expired, -> { where(expired: true) }
def expire!
update!(expired: true)
end
private
def assign_cached_values
self.assign_attributes(
successful_sales_count: product.successful_sales_count,
remaining_for_sale_count: product.remaining_for_sale_count,
monthly_recurring_revenue: product.monthly_recurring_revenue,
revenue_pending: product.revenue_pending,
total_usd_cents: product.total_usd_cents,
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/brunei_bank_account.rb | app/models/brunei_bank_account.rb | # frozen_string_literal: true
class BruneiBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BN"
BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9]{1,13}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::BRN.alpha2
end
def currency
Currency::BND
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/monaco_bank_account.rb | app/models/monaco_bank_account.rb | # frozen_string_literal: true
class MonacoBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MC"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::MCO.alpha2
end
def currency
Currency::EUR
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sent_abandoned_cart_email.rb | app/models/sent_abandoned_cart_email.rb | # frozen_string_literal: true
class SentAbandonedCartEmail < ApplicationRecord
belongs_to :cart
belongs_to :installment
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/media_location.rb | app/models/media_location.rb | # frozen_string_literal: true
class MediaLocation < ApplicationRecord
include MediaLocation::Unit
include Platform
include TimestampScopes
belongs_to :product_file, optional: true
belongs_to :purchase, optional: true
scope :max_consumed_at_by_file, lambda { |purchase_id:|
subquery = MediaLocation.select("product_file_id, MAX(consumed_at) AS max_consumed_at").where(purchase_id:).group(:product_file_id)
join_sql = <<-SQL.squish
INNER JOIN (#{subquery.to_sql}) AS max_ml
ON media_locations.product_file_id = max_ml.product_file_id
AND media_locations.consumed_at = max_ml.max_consumed_at
SQL
where(purchase_id:).joins(join_sql)
}
before_create :add_unit
validate :file_is_consumable
validates_presence_of :url_redirect_id, :product_file_id, :purchase_id, :location, :product_id
validates :platform, inclusion: { in: Platform.all }
def as_json(*)
{
location:,
unit:,
timestamp: consumed_at
}
end
private
def add_unit
if product_file.streamable? || product_file.listenable?
self.unit = Unit::SECONDS
elsif product_file.readable?
self.unit = Unit::PAGE_NUMBER
else
self.unit = Unit::PERCENTAGE
end
end
def file_is_consumable
return if product_file.consumable?
errors.add(:base, "File should be consumable")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/israel_bank_account.rb | app/models/israel_bank_account.rb | # frozen_string_literal: true
class IsraelBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "IL"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::ISR.alpha2
end
def currency
Currency::ILS
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/creator_email_open_event.rb | app/models/creator_email_open_event.rb | # frozen_string_literal: true
class CreatorEmailOpenEvent
include Mongoid::Document
include Mongoid::Timestamps
index({ mailer_method: 1, mailer_args: 1 }, { unique: true, name: "recipient_index" })
index({ installment_id: 1 }, { name: "installment_index" })
field :mailer_method, type: String
field :mailer_args, type: String
field :installment_id, type: Integer
field :open_timestamps, type: Array
field :open_count, type: Integer
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/azerbaijan_bank_account.rb | app/models/azerbaijan_bank_account.rb | # frozen_string_literal: true
class AzerbaijanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AZ"
BANK_CODE_FORMAT_REGEX = /^\d{6}$/
private_constant :BANK_CODE_FORMAT_REGEX
BRANCH_CODE_FORMAT_REGEX = /^\d{6}$/
private_constant :BRANCH_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_branch_code
validate :validate_account_number, if: -> { Rails.env.production? }
def routing_number
"#{bank_code}-#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::AZE.alpha2
end
def currency
Currency::AZN
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_branch_code
return if BRANCH_CODE_FORMAT_REGEX.match?(branch_code)
errors.add :base, "The branch code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/zip_tax_rate.rb | app/models/zip_tax_rate.rb | # frozen_string_literal: true
class ZipTaxRate < ApplicationRecord
include FlagShihTzu
include Deletable
include JsonData
has_flags 1 => :is_seller_responsible,
2 => :is_epublication_rate,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
attr_json_data_accessor :invoice_sales_tax_id
attr_json_data_accessor :applicable_years
has_many :purchases
validates :combined_rate, presence: true
validates :country, length: { is: 2 }
alias opt_out_eligible is_seller_responsible
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/credit.rb | app/models/credit.rb | # frozen_string_literal: true
class Credit < ApplicationRecord
include CurrencyHelper, JsonData
belongs_to :user, optional: true
belongs_to :merchant_account, optional: true
belongs_to :crediting_user, class_name: "User", optional: true
belongs_to :balance, optional: true
belongs_to :chargebacked_purchase, class_name: "Purchase", optional: true
belongs_to :dispute, optional: true
belongs_to :returned_payment, class_name: "Payment", optional: true
belongs_to :refund, optional: true
belongs_to :financing_paydown_purchase, class_name: "Purchase", optional: true
belongs_to :fee_retention_refund, class_name: "Refund", optional: true
belongs_to :backtax_agreement, optional: true
has_one :balance_transaction
after_create :add_comment
validates :user, :merchant_account, presence: true
validate :validate_associated_entity
attr_json_data_accessor :stripe_loan_paydown_id
def self.create_for_credit!(user:, amount_cents:, crediting_user:)
credit = new
credit.user = user
credit.merchant_account = MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)
credit.amount_cents = amount_cents
credit.crediting_user = crediting_user
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit.amount_cents,
net_cents: credit.amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_dispute_won!(user:, merchant_account:, dispute:, chargedback_purchase:, balance_transaction_issued_amount:, balance_transaction_holding_amount:)
credit = new
credit.user = user
credit.merchant_account = merchant_account
credit.amount_cents = balance_transaction_issued_amount.net_cents
credit.chargebacked_purchase = chargedback_purchase
credit.dispute = dispute
credit.save!
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_issued_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_returned_payment_difference!(user:, merchant_account:, returned_payment:, difference_amount_cents:)
credit = new
credit.user = user
credit.merchant_account = merchant_account
credit.amount_cents = 0
credit.returned_payment = returned_payment
credit.save!
balance_transaction_issued_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: 0,
net_cents: 0
)
balance_transaction_holding_amount = BalanceTransaction::Amount.new(
currency: returned_payment.currency,
gross_cents: difference_amount_cents,
net_cents: difference_amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_issued_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_vat_refund!(refund:)
total_refunded_vat_amount = refund.total_transaction_cents
purchase_amount = refund.purchase.total_transaction_cents
gumroad_amount = refund.purchase.total_transaction_amount_for_gumroad_cents
refunded_gumroad_amount = gumroad_amount * (total_refunded_vat_amount.to_f / purchase_amount)
credit_amount = total_refunded_vat_amount - refunded_gumroad_amount.to_i
credit = new
credit.user = refund.purchase.seller
credit.merchant_account = refund.purchase.stripe_charge_processor? ?
MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id) :
MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id)
credit.amount_cents = credit_amount
credit.refund = refund
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit.amount_cents,
net_cents: credit.amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
# When we refund VAT for a purchase paid via PayPal Native, we create a positive credit for the creator
# (`Credit.create_for_vat_refund!`) to compensate for the portion of the VAT that was refunded
# from their PayPal/Stripe Connect balance (since there's no way to specify that the refund should be taken out entirely
# from the Gumroad's portion of the purchase, see https://github.com/gumroad/web/issues/20820#issuecomment-1021042784).
#
# When a purchase with VAT refund is further partially or fully refunded, we need to apply proportional negative credit
# to the creator's balance because these refunds will be partially taken out from the Gumroad's portion
# (for which we have already given the creator credit during the VAT refund).
#
# If during VAT refund we apply $X credit for the user, and afterwards the purchase is fully refunded, we should apply -$X
# credit to even things out.
def self.create_for_vat_exclusive_refund!(refund:)
# Only create negative credit if:
# - VAT was charged initially
# - the refund does not include any VAT (meaning that VAT was refunded separately from the body of the purchase
# and there's no more VAT to refund left)
return if refund.gumroad_tax_cents > 0 || refund.purchase.gumroad_tax_cents == 0
total_refunded_amount = refund.total_transaction_cents
purchase_gumroad_amount = refund.purchase.total_transaction_amount_for_gumroad_cents
purchase_gumroad_tax_amount = refund.purchase.gumroad_tax_cents
purchase_gumroad_amount_sans_vat = purchase_gumroad_amount - purchase_gumroad_tax_amount
purchase_total_amount = refund.purchase.total_transaction_cents
purchase_amount_sans_vat = refund.purchase.price_cents
refunded_gumroad_amount = purchase_gumroad_amount * (total_refunded_amount.to_f / purchase_total_amount)
expected_refunded_gumroad_amount = purchase_gumroad_amount_sans_vat * (total_refunded_amount.to_f / purchase_amount_sans_vat)
# Negative credit amount
amount_to_credit = (expected_refunded_gumroad_amount - refunded_gumroad_amount).round
credit = new
credit.user = refund.purchase.seller
credit.merchant_account = refund.purchase.stripe_charge_processor? ?
MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id) :
MerchantAccount.gumroad(BraintreeChargeProcessor.charge_processor_id)
credit.amount_cents = amount_to_credit
credit.refund = refund
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit.amount_cents,
net_cents: credit.amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_financing_paydown!(purchase:, amount_cents:, merchant_account:, stripe_loan_paydown_id:)
return unless stripe_loan_paydown_id.present?
user = merchant_account.user
return if user.credits.where("json_data->'$.stripe_loan_paydown_id' = ?", stripe_loan_paydown_id).exists?
credit = new
credit.user = user
credit.amount_cents = amount_cents
credit.merchant_account = merchant_account
credit.financing_paydown_purchase = purchase
credit.stripe_loan_paydown_id = stripe_loan_paydown_id
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit.get_usd_cents(credit.merchant_account.currency, credit.amount_cents),
net_cents: credit.get_usd_cents(credit.merchant_account.currency, credit.amount_cents)
)
balance_transaction_holding_amount = BalanceTransaction::Amount.new(
currency: credit.merchant_account.currency,
gross_cents: credit.amount_cents,
net_cents: credit.amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_bank_debit_on_stripe_account!(amount_cents:, merchant_account:)
create_for_balance_change_on_stripe_account!(amount_cents_holding_currency: amount_cents, merchant_account:)
end
def self.create_for_manual_paydown_on_stripe_loan!(amount_cents:, merchant_account:, stripe_loan_paydown_id:)
credit = create_for_balance_change_on_stripe_account!(amount_cents_holding_currency: amount_cents, merchant_account:)
credit.update!(stripe_loan_paydown_id:)
credit
end
def self.create_for_balance_change_on_stripe_account!(amount_cents_holding_currency:, merchant_account:, amount_cents_usd: nil)
credit = new
credit.user = merchant_account.user
credit_amount_cents_usd = amount_cents_usd.presence || credit.get_usd_cents(merchant_account.currency, amount_cents_holding_currency)
credit.amount_cents = credit_amount_cents_usd
credit.merchant_account = merchant_account
credit.crediting_user = User.find(GUMROAD_ADMIN_ID)
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit_amount_cents_usd,
net_cents: credit_amount_cents_usd
)
balance_transaction_holding_amount = BalanceTransaction::Amount.new(
currency: credit.merchant_account.currency,
gross_cents: amount_cents_holding_currency,
net_cents: amount_cents_holding_currency
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_refund_fee_retention!(refund:)
# We retain the payment processor fee (2.9% + 30c) and the Gumroad fee (10% + any discover fee) in case of refunds.
# For Stripe Connect sales, the application fee includes the Gumroad fee, the VAT/sales tax,
# and the affiliate credit. We debit connected accounts for the full application fee, so we add a positive credit
# to the seller's balance. We have to do it this way because we don't have the seller's balance in our control,
# so adding a negative credit to their account for Gumroad's fee wouldn't work because there likely wouldn't be a
# balance to collect from.
unless refund.purchase.charged_using_gumroad_merchant_account?
purchase = refund.purchase
application_fee_refundable_portion = purchase.gumroad_tax_cents + purchase.affiliate_credit_cents
return if application_fee_refundable_portion.zero?
credit = new
credit.user = purchase.seller
credit.amount_cents = (application_fee_refundable_portion * (refund.amount_cents.to_f / purchase.price_cents)).round
credit.merchant_account = MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id)
credit.fee_retention_refund = refund
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: credit.amount_cents,
net_cents: credit.amount_cents
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_amount
)
credit.balance = balance_transaction.balance
credit.save!
return credit
end
credit = new
credit.user = refund.purchase.seller
# If purchase.processor_fee_cents is present (most cases), we use it to calculate the fee to be retained.
# We also check that purchase.processor_fee_cents_currency is 'usd' here, although that should always be the case,
# as we are only doing this calculation for sales via gumroad-controlled Stripe accounts and Braintree,
# and in both those cases transactions are always in USD.
# If purchase.processor_fee_cents is not present for some reason (rare case), we calculate the fee amount,
# that is to be retained, using the fee percentage used in Purchase#calculate_fees.
credit.amount_cents = if refund.purchase.processor_fee_cents.present? && refund.purchase.processor_fee_cents_currency == "usd"
-(refund.purchase.processor_fee_cents * (refund.amount_cents.to_f / refund.purchase.price_cents)).round
else
-(refund.amount_cents * Purchase::PROCESSOR_FEE_PER_THOUSAND / 1000.0 + (Purchase::PROCESSOR_FIXED_FEE_CENTS * refund.amount_cents.to_f / refund.purchase.price_cents)).round
end
credit.merchant_account = refund.purchase.merchant_account
credit.fee_retention_refund = refund
credit.save!
refund.retained_fee_cents = credit.amount_cents.abs
refund.save!
reversed_amount_cents_in_usd = credit.amount_cents
reversed_amount_cents_in_holding_currency = credit.usd_cents_to_currency(credit.merchant_account.currency, credit.amount_cents)
# For Stripe sales that use a gumroad-managed custom connect account, we debit the Stripe account for the fee amount.
if credit.merchant_account.holder_of_funds == HolderOfFunds::STRIPE && credit.merchant_account.country == Compliance::Countries::USA.alpha2
# For gumroad-controlled Stripe accounts from the US, we can make new debit transfers.
# So we transfer the retained fee back to Gumroad's Stripe platform account.
Stripe::Transfer.create({ amount: credit.amount_cents.abs, currency: "usd", destination: Stripe::Account.retrieve.id, },
{ stripe_account: credit.merchant_account.charge_processor_merchant_id })
elsif credit.merchant_account.holder_of_funds == HolderOfFunds::STRIPE
# For non-US gumroad-controlled Stripe accounts, we cannot make debit transfers.
# So we try and reverse the retained fee amount from one of the old transfers made to that Stripe account.
net_amount_on_stripe_in_holding_currency = StripeChargeProcessor.debit_stripe_account_for_refund_fee(credit:)
reversed_amount_cents_in_holding_currency = -net_amount_on_stripe_in_holding_currency if net_amount_on_stripe_in_holding_currency.present?
end
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: reversed_amount_cents_in_usd,
net_cents: reversed_amount_cents_in_usd
)
balance_transaction_holding_amount = BalanceTransaction::Amount.new(
currency: credit.merchant_account.currency,
gross_cents: reversed_amount_cents_in_holding_currency,
net_cents: reversed_amount_cents_in_holding_currency
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def self.create_for_partial_refund_transfer_reversal!(amount_cents_usd:, amount_cents_holding_currency:, merchant_account:)
credit = new
credit.user = merchant_account.user
credit.amount_cents = amount_cents_usd
credit.merchant_account = merchant_account
credit.crediting_user = User.find(GUMROAD_ADMIN_ID)
credit.save!
balance_transaction_amount = BalanceTransaction::Amount.new(
currency: Currency::USD,
gross_cents: amount_cents_usd,
net_cents: amount_cents_usd
)
balance_transaction_holding_amount = BalanceTransaction::Amount.new(
currency: credit.merchant_account.currency,
gross_cents: amount_cents_holding_currency,
net_cents: amount_cents_holding_currency
)
balance_transaction = BalanceTransaction.create!(
user: credit.user,
merchant_account: credit.merchant_account,
credit:,
issued_amount: balance_transaction_amount,
holding_amount: balance_transaction_holding_amount
)
credit.balance = balance_transaction.balance
credit.save!
credit
end
def notify_user
ContactingCreatorMailer.credit_notification(user.id, amount_cents).deliver_later(queue: "critical")
end
def add_comment
return if fee_retention_refund.present?
comment_attrs = {
content: "issued #{formatted_dollar_amount(amount_cents)} credit.",
comment_type: :credit
}
if crediting_user
comment_attrs[:author_id] = crediting_user_id
elsif chargebacked_purchase
comment_attrs[:author_name] = "AutoCredit Chargeback Won (#{chargebacked_purchase.id})"
elsif returned_payment
comment_attrs[:author_name] = "AutoCredit Returned Payment (#{returned_payment.id})"
comment_attrs[:content] = "issued adjustment due to currency conversion differences when payment #{returned_payment.id} returned."
elsif refund
comment_attrs[:author_name] = "AutoCredit PayPal Connect VAT refund (#{refund.purchase.id})"
end
user.comments.create(comment_attrs)
end
private
def validate_associated_entity
return if crediting_user || chargebacked_purchase || returned_payment || refund || financing_paydown_purchase || fee_retention_refund || backtax_agreement
errors.add(:base, "A crediting user, chargebacked purchase, returned payment, refund, financing_paydown_purchase, fee_retention_refund or backtax_agreement must be provided.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/san_marino_bank_account.rb | app/models/san_marino_bank_account.rb | # frozen_string_literal: true
class SanMarinoBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "SM"
BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::SMR.alpha2
end
def currency
Currency::EUR
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/hong_kong_bank_account.rb | app/models/hong_kong_bank_account.rb | # frozen_string_literal: true
class HongKongBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "HK"
CLEARING_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/
private_constant :CLEARING_CODE_FORMAT_REGEX
BRANCH_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/
private_constant :BRANCH_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{6,12}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :clearing_code, :bank_number
validate :validate_clearing_code
validate :validate_branch_code
validate :validate_account_number
def routing_number
"#{clearing_code}-#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::HKG.alpha2
end
def currency
Currency::HKD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_clearing_code
return if CLEARING_CODE_FORMAT_REGEX.match?(clearing_code)
errors.add :base, "The clearing code is invalid."
end
def validate_branch_code
return if BRANCH_CODE_FORMAT_REGEX.match?(branch_code)
errors.add :base, "The branch code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/base_variant.rb | app/models/base_variant.rb | # frozen_string_literal: true
class BaseVariant < ApplicationRecord
include ActionView::Helpers::SanitizeHelper
include CurrencyHelper
include ExternalId
include Deletable
include WithProductFilesManyToMany
include FlagShihTzu
include MaxPurchaseCount
include Integrations
include RichContents
MINIMUM_DAYS_TIL_EXISTING_MEMBERSHIP_PRICE_CHANGE = 7
has_and_belongs_to_many :purchases
has_many :subscriptions, through: :purchases
has_many :base_variant_integrations
has_many :live_base_variant_integrations, -> { alive }, class_name: "BaseVariantIntegration"
has_many :active_integrations, through: :live_base_variant_integrations, source: :integration
delegate :has_stampable_pdfs?, to: :link
scope :in_order, -> { order(created_at: :asc) }
has_flags 1 => :is_default_sku,
2 => :apply_price_changes_to_existing_memberships,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
after_commit :invalidate_product_cache,
if: ->(base_variant) { base_variant.previous_changes.present? && base_variant.previous_changes.present? != [:updated_at] }
after_commit :update_product_search_index
validates_presence_of :name, unless: -> { link.native_type == Link::NATIVE_TYPE_COFFEE }
validate :max_purchase_count_is_greater_than_or_equal_to_inventory_sold
validate :price_difference_cents_validation
validate :apply_price_changes_to_existing_memberships_settings
before_validation :strip_subscription_price_change_message, unless: -> { subscription_price_change_message.nil? }
def mark_deleted
super
DeleteProductRichContentWorker.perform_async(variant_category.link_id, id)
DeleteProductFilesArchivesWorker.perform_async(variant_category.link_id, id)
end
def price_difference_in_currency_units
return price_difference_cents if link.single_unit_currency?
price_difference_cents.to_i / 100.0
end
def price_formatted_without_dollar_sign
return 0 unless price_difference_cents
display_price(symbol: false)
end
def quantity_left
return nil if max_purchase_count.nil?
[max_purchase_count - sales_count_for_inventory, 0].max
end
def available?
return false if deleted?
return true if max_purchase_count.nil?
quantity_left > 0
end
def sold_out?
return false if max_purchase_count.nil?
quantity_left == 0
end
def free?
!((price_difference_cents.present? && price_difference_cents > 0) || prices.alive.is_buy.where("price_cents > 0").exists?)
end
def as_json(options = {})
if options[:for_views]
variant_quantity_left = quantity_left
variant_json = {
"option" => name,
"name" => name == "Untitled" ? link.name : name,
"description" => description,
"id" => external_id,
"max_purchase_count" => max_purchase_count,
"price_difference_cents" => price_difference_cents,
"price_difference_in_currency_units" => price_difference_in_currency_units,
"showing" => price_difference_cents != 0,
"quantity_left" => variant_quantity_left,
"amount_left_title" => variant_quantity_left ? "#{variant_quantity_left} left" : "",
"displayable" => name,
"sold_out" => variant_quantity_left == 0,
"price_difference" => price_formatted_without_dollar_sign,
"currency_symbol" => link.currency_symbol,
"product_files_ids" => product_files.collect(&:external_id),
}
if options[:for_seller] == true
variant_json["active_subscriber_count"] = active_subscribers_count
variant_json["settings"] = {
apply_price_changes_to_existing_memberships: apply_price_changes_to_existing_memberships? ?
{ enabled: true, effective_date: subscription_price_change_effective_date, custom_message: subscription_price_change_message } :
{ enabled: false }
}
end
variant_json["integrations"] = {}
Integration::ALL_NAMES.each do |name|
variant_json["integrations"][name] = find_integration_by_name(name).present?
end
variant_json
else
{
"id" => external_id,
"max_purchase_count" => max_purchase_count,
"name" => name,
"description" => description,
"price_difference_cents" => price_difference_cents
}
end
end
def to_option(subscription_attrs: nil)
{
id: external_id,
name: name == "Untitled" ? link.name : name || "",
quantity_left:,
description: description || "",
price_difference_cents:,
recurrence_price_values: link.is_tiered_membership ? recurrence_price_values(subscription_attrs:) : nil,
is_pwyw: !!customizable_price,
duration_in_minutes:,
}
end
def sales_count_for_inventory
purchases.counts_towards_inventory.sum(:quantity)
end
def is_downloadable?
return false if link.purchase_type == "rent_only"
return false if has_stampable_pdfs?
return false if stream_only?
true
end
def stream_only?
link.has_same_rich_content_for_all_variants? ? link.product_files.alive.all?(&:stream_only?) : super
end
def active_subscribers_count
return 0 unless link.is_recurring_billing?
link.successful_sales_count(variant: self)
end
private
def display_price(options = {})
attrs = { no_cents_if_whole: true, symbol: true }.merge(options)
MoneyFormatter.format(price_difference_cents, link.price_currency_type.to_sym, attrs)
end
def invalidate_product_cache
link.invalidate_cache if link.present?
end
def price_difference_cents_validation
if price_difference_cents && price_difference_cents < 0
errors.add(:base, "Please enter a price that is equal to or greater than the price of the product.")
end
if link.native_type == Link::NATIVE_TYPE_COFFEE && price_difference_cents && price_difference_cents <= 0
errors.add(:base, "Price difference cents must be greater than 0")
end
end
def max_purchase_count_is_greater_than_or_equal_to_inventory_sold
return unless max_purchase_count_changed?
return if max_purchase_count.nil?
cached_sales_count_for_inventory = sales_count_for_inventory
return if max_purchase_count >= cached_sales_count_for_inventory
errors.add(:base, "You have chosen an amount lower than what you have already sold. Please enter an amount greater than #{cached_sales_count_for_inventory}.")
end
def apply_price_changes_to_existing_memberships_settings
if apply_price_changes_to_existing_memberships?
if !subscription_price_change_effective_date.present?
errors.add(:base, "Effective date for existing membership price changes must be present")
elsif subscription_price_change_effective_date_changed? && subscription_price_change_effective_date < MINIMUM_DAYS_TIL_EXISTING_MEMBERSHIP_PRICE_CHANGE.days.from_now.in_time_zone(user.timezone).to_date
errors.add(:base, "The effective date must be at least 7 days from today")
end
end
end
def update_product_search_index
if link.present? && saved_change_to_price_difference_cents?
link.enqueue_index_update_for(["available_price_cents"])
end
end
def strip_subscription_price_change_message
unless strip_tags(subscription_price_change_message).present?
self.subscription_price_change_message = nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sent_email_info.rb | app/models/sent_email_info.rb | # frozen_string_literal: true
class SentEmailInfo < ApplicationRecord
validates_presence_of :key
def self.key_exists?(key)
where(key:).exists?
end
def self.set_key!(key)
record = new
record.key = key
begin
record.save!
rescue ActiveRecord::RecordNotUnique
nil
end
end
def self.mailer_key_digest(mailer_class, mailer_method, *args)
mail_key = "#{mailer_class}.#{mailer_method}#{args}"
Digest::SHA1.hexdigest(mail_key)
end
def self.mailer_exists?(mailer_class, mailer_method, *args)
digest = mailer_key_digest(mailer_class, mailer_method, *args)
key_exists?(digest)
end
def self.ensure_mailer_uniqueness(mailer_class, mailer_method, *args, &block)
digest = mailer_key_digest(mailer_class, mailer_method, *args)
if !key_exists?(digest) && set_key!(digest)
yield
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/installment.rb | app/models/installment.rb | # frozen_string_literal: true
require "custom_rouge_theme"
class Installment < ApplicationRecord
has_paper_trail
include Rails.application.routes.url_helpers
include ExternalId, ActionView::Helpers::SanitizeHelper, ActionView::Helpers::TextHelper, CurrencyHelper, S3Retrievable, WithProductFiles, Deletable, JsonData,
WithFiltering, Post::Caching, Installment::Searchable, FlagShihTzu
extend FriendlyId
PRODUCT_LIST_PLACEHOLDER_TAG_NAME = "product-list-placeholder"
MAX_ABANDONED_CART_PRODUCTS_TO_SHOW_IN_EMAIL = 3
PUBLISHED = "published"
SCHEDULED = "scheduled"
DRAFT = "draft"
LANGUAGE_LEXERS = {
"arduino" => Rouge::Lexers::Cpp,
"bash" => Rouge::Lexers::Shell,
"c" => Rouge::Lexers::C,
"cpp" => Rouge::Lexers::Cpp,
"csharp" => Rouge::Lexers::CSharp,
"css" => Rouge::Lexers::CSS,
"diff" => Rouge::Lexers::Diff,
"go" => Rouge::Lexers::Go,
"graphql" => Rouge::Lexers::GraphQL,
"ini" => Rouge::Lexers::INI,
"java" => Rouge::Lexers::Java,
"javascript" => Rouge::Lexers::Javascript,
"json" => Rouge::Lexers::JSON,
"kotlin" => Rouge::Lexers::Kotlin,
"less" => Rouge::Lexers::CSS,
"lua" => Rouge::Lexers::Lua,
"makefile" => Rouge::Lexers::Make,
"markdown" => Rouge::Lexers::Markdown,
"objectivec" => Rouge::Lexers::ObjectiveC,
"perl" => Rouge::Lexers::Perl,
"php" => Rouge::Lexers::PHP,
"php-template" => Rouge::Lexers::PHP,
"plaintext" => Rouge::Lexers::PlainText,
"python" => Rouge::Lexers::Python,
"python-repl" => Rouge::Lexers::Python,
"r" => Rouge::Lexers::R,
"ruby" => Rouge::Lexers::Ruby,
"rust" => Rouge::Lexers::Rust,
"scss" => Rouge::Lexers::Scss,
"shell" => Rouge::Lexers::Shell,
"sql" => Rouge::Lexers::SQL,
"swift" => Rouge::Lexers::Swift,
"typescript" => Rouge::Lexers::Typescript,
"vbnet" => Rouge::Lexers::VisualBasic,
"wasm" => Rouge::Lexers::ArmAsm,
"xml" => Rouge::Lexers::XML,
"yaml" => Rouge::Lexers::YAML
}.freeze
attr_json_data_accessor :workflow_trigger
belongs_to :link, optional: true
belongs_to :base_variant, optional: true
belongs_to :seller, class_name: "User", optional: true
belongs_to :workflow, optional: true
has_many :url_redirects
has_one :installment_rule
has_many :installment_events
has_many :email_infos
has_many :purchases, through: :email_infos
has_many :comments, as: :commentable
has_many :sent_post_emails, foreign_key: "post_id"
has_many :blasts, class_name: "PostEmailBlast", foreign_key: "post_id"
has_many :sent_abandoned_cart_emails
friendly_id :slug_candidates, use: :slugged
after_save :trigger_iffy_ingest
validates :name, length: { maximum: 255 }
validate :message_must_be_provided, :validate_call_to_action_url_and_text, :validate_channel,
:published_at_cannot_be_in_the_future, :validate_sending_limit_for_sellers
validate :shown_on_profile_only_for_confirmed_users, if: :shown_on_profile_changed?
has_flags 1 => :is_unpublished_by_admin,
2 => :DEPRECATED_is_automated_installment,
3 => :DEPRECATED_stream_only,
4 => :DEPRECATED_is_open_rate_tracking_enabled,
5 => :DEPRECATED_is_click_rate_tracking_enabled,
6 => :is_for_new_customers_of_workflow,
7 => :workflow_installment_published_once_already,
8 => :shown_on_profile,
9 => :send_emails,
10 => :ready_to_publish,
11 => :allow_comments,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
scope :published, -> { where.not(published_at: nil) }
scope :not_published, -> { where(published_at: nil) }
scope :scheduled, -> { not_published.ready_to_publish }
scope :draft, -> { not_published.not_ready_to_publish }
scope :not_workflow_installment, -> { where(workflow_id: nil) }
scope :send_emails, -> { where("installments.flags & ? > 0", Installment.flag_mapping["flags"][:send_emails]) }
scope :profile_only, -> { not_send_emails.shown_on_profile }
scope :visible_on_profile, -> { alive.published.audience_type.shown_on_profile.not_workflow_installment }
scope :ordered_updates, -> (user, type) {
order_clause = if type == DRAFT
{ updated_at: :desc }
else
Arel.sql("published_at IS NULL, COALESCE(published_at, installments.created_at) DESC")
end
# The custom `ORDER BY` clause does the following:
# - Keep all unpublished updates at the top
# - Sort unpublished updates by `created_at DESC` and sort published updates by `published_at DESC`
by_seller_sql = where(seller: user).to_sql
by_product_sql = where(link_id: user.links.visible.select(:id)).to_sql
from("((#{by_seller_sql}) UNION (#{by_product_sql})) installments")
.alive
.not_workflow_installment
.order(order_clause)
}
scope :filter_by_product_id_if_present, -> (product_id) {
if product_id.present?
where(link_id: product_id)
end
}
scope :missed_for_purchase, -> (purchase) {
product_installment_ids = purchase.link.installments.where(seller_id: purchase.seller_id).alive.published.pluck(:id)
seller_installment_ids = purchase.seller.installments.alive.published.filter_map do |post|
post.id if post.purchase_passes_filters(purchase)
end
purchase_ids_with_same_email = Purchase.where(email: purchase.email, seller_id: purchase.seller_id)
.all_success_states
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.pluck(:id)
where_sent_sql = <<-SQL.squish
NOT EXISTS (
SELECT 1
FROM email_infos
WHERE installments.id = email_infos.installment_id
AND email_infos.purchase_id IN (#{purchase_ids_with_same_email.append(purchase.id).join(", ")})
AND email_infos.installment_id IS NOT NULL
)
SQL
send_emails.
where(id: product_installment_ids + seller_installment_ids).
where(where_sent_sql)
}
scope :product_or_variant_with_sent_emails_for_purchases, -> (purchase_ids) {
send_emails.
joins(:purchases).
where("purchases.id IN (?)", purchase_ids).
product_or_variant_type.
alive.
published.
order("email_infos.sent_at DESC, email_infos.delivered_at DESC, email_infos.id DESC").
select("installments.*, email_infos.sent_at, email_infos.delivered_at, email_infos.opened_at")
}
scope :seller_with_sent_emails_for_purchases, -> (purchase_ids) {
alive.
published.
send_emails.
seller_type.
joins(:purchases).
where("purchases.id IN (?)", purchase_ids)
}
scope :profile_only_for_products, -> (product_ids) {
profile_only.
alive.
published.
product_type.
where(link_id: product_ids, base_variant_id: nil)
}
scope :profile_only_for_variants, -> (variant_ids) {
profile_only.
alive.
published.
variant_type.
where(base_variant_id: variant_ids)
}
scope :profile_only_for_sellers, -> (seller_ids) {
alive.
published.
profile_only.
seller_type.
where(seller_id: seller_ids)
}
scope :for_products, ->(product_ids:) {
alive.
published.
not_workflow_installment.
product_type.
where(link_id: product_ids)
}
scope :for_variants, ->(variant_ids:) {
alive.
published.
not_workflow_installment.
variant_type.
where(base_variant_id: variant_ids)
}
scope :for_sellers, ->(seller_ids:) {
alive.
published.
not_workflow_installment.
seller_type.
where(seller_id: seller_ids)
}
scope :past_posts_to_show_for_products, -> (product_ids:, excluded_post_ids: []) {
exclude_posts_sql = excluded_post_ids.empty? ? "" : sanitize_sql_array(["installments.id NOT IN (?) AND ", excluded_post_ids])
joins(:link).
for_products(product_ids:).
where("#{exclude_posts_sql}links.flags & ?", Link.flag_mapping["flags"][:should_show_all_posts])
}
scope :past_posts_to_show_for_variants, -> (variant_ids:, excluded_post_ids: []) {
exclude_posts_sql = excluded_post_ids.empty? ? "" : sanitize_sql_array(["installments.id NOT IN (?) AND ", excluded_post_ids])
joins(:link).
for_variants(variant_ids:).
where("#{exclude_posts_sql}links.flags & ?", Link.flag_mapping["flags"][:should_show_all_posts])
}
scope :seller_posts_for_sellers, -> (seller_ids:, excluded_post_ids: []) {
exclude_posts_sql = excluded_post_ids.empty? ? "" : sanitize_sql_array(["installments.id NOT IN (?)", excluded_post_ids])
for_sellers(seller_ids:).where(exclude_posts_sql)
}
scope :emailable_posts_for_purchase, ->(purchase:) do
subqueries = [
for_products(product_ids: [purchase.link_id]).send_emails,
for_variants(variant_ids: purchase.variant_attributes.pluck(:id)).send_emails,
seller_posts_for_sellers(seller_ids: [purchase.seller_id]).send_emails,
]
subqueries_sqls = subqueries.map { "(" + _1.to_sql + ")" }
from("(" + subqueries_sqls.join(" UNION ") + ") AS #{table_name}")
end
scope :group_by_installment_rule, -> (timezone) {
includes(:installment_rule)
.sort_by { |post| post.installment_rule.to_be_published_at }
.group_by { |post| post.installment_rule.to_be_published_at.in_time_zone(timezone).strftime("%B %-d, %Y") }
}
SENDING_LIMIT = 100
MINIMUM_SALES_CENTS_VALUE = 100_00 # $100
MEMBER_CANCELLATION_WORKFLOW_TRIGGER = "member_cancellation"
def user
seller.presence || link.user
end
def installment_mobile_json_data(purchase: nil, subscription: nil, imported_customer: nil, follower: nil)
installment_url_redirect = if subscription.present?
url_redirect(subscription) || generate_url_redirect_for_subscription(subscription)
elsif purchase.present?
purchase_url_redirect(purchase) || generate_url_redirect_for_purchase(purchase)
elsif imported_customer.present?
imported_customer_url_redirect(imported_customer) || generate_url_redirect_for_imported_customer(imported_customer)
elsif follower.present?
# Default to sending follower post instead of breaking up
follower_or_audience_url_redirect || generate_url_redirect_for_follower
end
files_data = alive_product_files.map do |product_file|
installment_url_redirect.mobile_product_file_json_data(product_file)
end
released_at = if purchase.present?
action_at_for_purchase(purchase.original_purchase)
elsif subscription.present?
action_at_for_purchase(subscription.original_purchase)
end
{
files_data:,
message:,
name:,
call_to_action_text:,
call_to_action_url:,
installment_type:,
published_at: released_at || published_at,
external_id:,
url_redirect_external_id: installment_url_redirect.external_id,
creator_name: seller.name_or_username,
creator_profile_picture_url: seller.avatar_url,
creator_profile_url: seller.profile_url
}
end
def member_cancellation_trigger?
workflow_trigger == MEMBER_CANCELLATION_WORKFLOW_TRIGGER
end
def displayed_name
return name if name.present?
truncate(strip_tags(message), separator: " ", length: 48)
end
def truncated_description
TextScrubber.format(message).squish.truncate(255)
end
def message_with_inline_syntax_highlighting_and_upsells
return message if message.blank?
doc = Nokogiri::HTML.fragment(message)
doc.search("pre > code").each do |node|
language = node.attr("class")&.sub("language-", "")
content = node.content
lexer = (language.present? ? LANGUAGE_LEXERS[language] : Rouge::Lexer.guesses(source: content).first) || Rouge::Lexers::PlainText
tokens = lexer.lex(content)
formatter = Rouge::Formatters::HTMLInline.new(CustomRougeTheme.mode(:light))
node.parent.replace(%(<pre style="white-space: revert; overflow: auto; border: 1px solid currentColor; border-radius: 4px; background-color: #fff;"><code style="max-width: unset; border-width: 0; width: 100vw; background-color: #fff;">#{formatter.format(tokens)}</code></pre>))
end
doc.search("upsell-card").each do |card|
upsell_id = card["id"]
upsell = seller.upsells.find_by_external_id!(upsell_id)
product = upsell.product
card.replace(
ApplicationController.renderer.render(
template: "posts/upsell",
layout: false,
assigns: {
product: product,
offer_code: upsell.offer_code,
upsell_url: checkout_index_url(accepted_offer_id: upsell.external_id, product: product.unique_permalink, host: DOMAIN)
}
)
)
end
doc.search(".tiptap__raw[data-url]").each do |node|
thumbnail_url = node["data-thumbnail"]
target_url = node["data-url"]
alt_title = node["data-title"]
return if target_url.blank?
content = thumbnail_url.present? ? "<img src='#{thumbnail_url}' alt='#{alt_title}' />" : alt_title.presence || target_url
node.replace(%(<p><a href="#{target_url}" target="_blank" rel="noopener noreferrer">#{content}</a></p>))
end
doc.to_html
end
def message_with_inline_abandoned_cart_products(products:, checkout_url: nil)
return message if message.blank? || products.blank?
default_checkout_url = Rails.application.routes.url_helpers.checkout_index_url(host: UrlService.domain_with_protocol)
checkout_url ||= default_checkout_url
doc = Nokogiri::HTML.fragment(message_with_inline_syntax_highlighting_and_upsells)
doc.search("#{PRODUCT_LIST_PLACEHOLDER_TAG_NAME}").each do |node|
node.replace(
ApplicationController.renderer.render(
template: "posts/abandoned_cart_products_list",
layout: false,
assigns: { products: },
)
)
end
doc.search("a[href='#{default_checkout_url}']").each { _1["href"] = checkout_url } if default_checkout_url != checkout_url
doc.to_html
end
def send_preview_email(recipient_user)
if recipient_user.has_unconfirmed_email?
raise PreviewEmailError, "You have to confirm your email address before you can do that."
elsif abandoned_cart_type?
CustomerMailer.abandoned_cart_preview(recipient_user.id, id).deliver_later
else
recipient = { email: recipient_user.email }
recipient[:url_redirect] = UrlRedirect.find_or_create_by!(installment: self, purchase: nil) if has_files?
PostEmailApi.process(post: self, recipients: [recipient], preview: true)
end
end
def send_installment_from_workflow_for_purchase(purchase_id)
sale = Purchase.find(purchase_id)
return if sale.is_recurring_subscription_charge
sale = sale.original_purchase
return unless sale.can_contact?
return if sale.chargedback_not_reversed_or_refunded?
return if sale.subscription.present? && !sale.subscription.alive?
other_purchase_ids = Purchase.where(email: sale.email, seller_id: sale.seller_id)
.all_success_states
.no_or_active_subscription
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.pluck(:id)
return if other_purchase_ids.present? && CreatorContactingCustomersEmailInfo.where(purchase: other_purchase_ids, installment: id).present?
return if workflow.present? && !workflow.applies_to_purchase?(sale)
expected_delivery_time_for_sale = expected_delivery_time(sale)
if Time.current < expected_delivery_time_for_sale
# reschedule for later if it's too soon to send (only applicable for subscriptions
# that have been terminated and later restarted)
SendWorkflowInstallmentWorker.perform_at(expected_delivery_time_for_sale + 1.minute, id, installment_rule.version, sale.id, nil)
else
SentPostEmail.ensure_uniqueness(post: self, email: sale.email) do
recipient = { email: sale.email, purchase: sale }
recipient[:url_redirect] = generate_url_redirect_for_purchase(sale) if has_files?
send_email(recipient)
end
end
end
def send_installment_from_workflow_for_member_cancellation(subscription_id)
return unless member_cancellation_trigger?
subscription = Subscription.find(subscription_id)
return if subscription.alive?
sale = subscription.original_purchase
return unless sale.present?
return unless sale.can_contact?
return if sale.chargedback_not_reversed_or_refunded?
other_purchase_ids = Purchase.where(email: sale.email, seller_id: sale.seller_id)
.all_success_states
.inactive_subscription
.not_fully_refunded
.not_chargedback_or_chargedback_reversed
.pluck(:id)
return if other_purchase_ids.present? && CreatorContactingCustomersEmailInfo.where(purchase: other_purchase_ids, installment: id).present?
return if workflow.present? && !workflow.applies_to_purchase?(sale)
SentPostEmail.ensure_uniqueness(post: self, email: sale.email) do
recipient = { email: sale.email, purchase: sale, subscription: }
recipient[:url_redirect] = generate_url_redirect_for_subscription(sale) if has_files?
send_email(recipient)
end
end
def send_installment_from_workflow_for_follower(follower_id)
follower = Follower.find_by(id: follower_id)
return if follower.nil? || follower.deleted? || follower.unconfirmed? # check for nil followers because we removed duplicates that may have been queued
SentPostEmail.ensure_uniqueness(post: self, email: follower.email) do
recipient = { email: follower.email, follower: }
recipient[:url_redirect] = generate_url_redirect_for_follower if has_files?
send_email(recipient)
end
end
def send_installment_from_workflow_for_affiliate_user(affiliate_user_id)
affiliate_user = User.find_by(id: affiliate_user_id)
return if affiliate_user.nil?
SentPostEmail.ensure_uniqueness(post: self, email: affiliate_user.email) do
recipient = { email: affiliate_user.email, affiliate: affiliate_user }
recipient[:url_redirect] = generate_url_redirect_for_affiliate if has_files?
send_email(recipient)
end
end
def subject
return name if name.present?
(link.try(:name) || seller.name || "Creator").to_s + " - " + "Update"
end
def post_views_count
installment_events_count.nil? ? 0 : installment_events_count
end
def full_url(purchase_id: nil)
return unless slug.present?
if user.subdomain_with_protocol.present?
custom_domain_view_post_url(
host: user.subdomain_with_protocol,
slug:,
purchase_id: purchase_id.presence
)
else
view_post_path(
username: user.username.presence || user.external_id,
slug:,
purchase_id: purchase_id.presence
)
end
end
def generate_url_redirect_for_imported_customer(imported_customer, product: nil)
return unless imported_customer
product ||= imported_customer.link
UrlRedirect.create(installment: self, imported_customer:, link: product)
end
def generate_url_redirect_for_subscription(subscription)
UrlRedirect.create(installment: self, subscription:)
end
def generate_url_redirect_for_purchase(purchase)
UrlRedirect.create(installment: self, purchase:)
end
def generate_url_redirect_for_follower
UrlRedirect.create(installment: self)
end
def generate_url_redirect_for_affiliate
UrlRedirect.create(installment: self)
end
def url_redirect(subscription)
UrlRedirect.where(subscription_id: subscription.id, installment_id: id).first
end
def purchase_url_redirect(purchase)
UrlRedirect.where(purchase_id: purchase.id, installment_id: id).first if purchase
end
def imported_customer_url_redirect(imported_customer)
UrlRedirect.where(imported_customer_id: imported_customer.id, installment_id: id).last
end
# Public: Returns the url redirect to be used for follower or audience installments.
# These two types of installments have one single url redirect that is not tied to any individual follower/purchase.
def follower_or_audience_url_redirect
url_redirects.where(purchase_id: nil).last
end
# NOTE: This method is now only used in one place (PostPresenter), and shouldn't be expected to create any new records:
# it can be heavily simplified / removed altogether.
def download_url(subscription, purchase, imported_customer = nil)
url_redirect = nil
# workflow installments belonging to a subscription product will include subscription in the parameters and not check
# purchase_url_redirect which is where the url is. This results in missing 'view attachment' button for some installments
url_redirect = self.url_redirect(subscription) if subscription.present?
if url_redirect.nil? && (follower_type? || audience_type? || affiliate_type?) && has_files?
url_redirect = follower_or_audience_url_redirect
elsif url_redirect.nil? && purchase.present?
url_redirect = purchase_url_redirect(purchase)
elsif imported_customer.present?
url_redirect = imported_customer_url_redirect(imported_customer)
return nil if !has_files?
product_files = link.try(:alive_product_files)
return nil if !has_files? && (product_files.nil? || product_files.empty?)
end
return nil if url_redirect.nil? && !has_files?
return nil if url_redirect.nil? &&
subscription.nil? &&
purchase.nil? &&
needs_purchase_to_access_content?
# We turned off the feature where new subscribers get the last update, resulting in some url_redirects not being created.
# We need to create the url_redirect and return the download_page_url for installments with files. This also protects us from
# customers getting/seeing an installment without a 'View Attachments' button when it has files.
if url_redirect.nil?
url_redirect = if subscription.present?
generate_url_redirect_for_subscription(subscription)
else
generate_url_redirect_for_purchase(purchase)
end
url_redirect.download_page_url
else
has_files? ? url_redirect.download_page_url : url_redirect.url
end
end
def published?
published_at.present?
end
def display_type
return "published" if published?
ready_to_publish? ? "scheduled" : "draft"
end
def publish!(published_at: nil)
enforce_user_email_confirmation!
transcode_videos!
self.published_at = published_at.presence || Time.current
self.workflow_installment_published_once_already = true if workflow.present?
save!
end
def unpublish!(is_unpublished_by_admin: false)
self.published_at = nil
self.is_unpublished_by_admin = is_unpublished_by_admin
save!
end
def is_affiliate_product_post?
!!(affiliate_type? && affiliate_products&.one?)
end
def streamable?
alive_product_files.map(&:filegroup).include?("video")
end
def stream_only?
alive_product_files.all?(&:stream_only?)
end
def targeted_at_purchased_item?(purchase)
return true if product_type? && link_id == purchase.link_id
return true if variant_type? && purchase.variant_attributes.pluck(:id).include?(base_variant_id)
return true if bought_products.present? && bought_products.include?(purchase.link.unique_permalink)
return true if bought_variants.present? && (bought_variants & purchase.variant_attributes.map(&:external_id)).present?
false
end
def passes_member_cancellation_checks?(purchase)
return true unless member_cancellation_trigger?
return false if purchase.nil?
sent_email_info = CreatorContactingCustomersEmailInfo.where(installment_id: id, purchase_id: purchase.id).last
sent_email_info.present?
end
def unique_open_count
Rails.cache.fetch(key_for_cache(:unique_open_count)) do
CreatorEmailOpenEvent.where(installment_id: id).count
end
end
def unique_click_count
Rails.cache.fetch(key_for_cache(:unique_click_count)) do
summary = CreatorEmailClickSummary.where(installment_id: id).last
summary.present? ? summary[:total_unique_clicks] : 0
end
end
# Return a breakdown of clicks by url.
def clicked_urls
summary = CreatorEmailClickSummary.where(installment_id: id).last
return {} if summary.blank?
# Change urls back into human-readable format (Necessary because Mongo keys cannot contain ".") Also remove leading protocol & www
summary.urls.keys.each { |k| summary.urls[k.gsub(/./, ".").sub(%r{^https?://}, "").sub(/^www./, "")] = summary.urls.delete(k) }
Hash[summary.urls.sort_by { |_, v| v }.reverse] # Sort by number of clicks.
end
# Public: Returns the percentage of email opens for this installment, or nil if one cannot be calculated.
def open_rate_percent
unique_open_count = self.unique_open_count
total_delivered = customer_count
return nil if total_delivered.nil?
return 100 if total_delivered == 0
unique_open_count / total_delivered.to_f * 100
end
# Public: Returns the percentage of email clicks for this installment, or nil if one cannot be calculated.
def click_rate_percent
unique_click_count = self.unique_click_count
total_delivered = customer_count
return nil if total_delivered.nil?
return 100 if total_delivered == 0
unique_click_count / total_delivered.to_f * 100
end
def action_at_for_purchase(purchase)
action_at_for_purchases([purchase.id])
end
def action_at_for_purchases(purchase_ids)
email_info = CreatorContactingCustomersEmailInfo.where(installment_id: id, purchase_id: purchase_ids).last
action_at = email_info.present? ? email_info.sent_at || email_info.delivered_at || email_info.opened_at : published_at
action_at || Time.current
end
def increment_total_delivered(by: 1)
self.class.update_counters id, customer_count: by
end
def eligible_purchase_for_user(user)
# No purchase needed to view content for post sent to followers or audience, so return nil.
return nil if user.blank? || !needs_purchase_to_access_content?
purchases = user.purchases.successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback
purchases = if installment_type == PRODUCT_TYPE
purchases.where(link_id:)
elsif installment_type == VARIANT_TYPE
user.purchases.where(link_id:).select { |purchase| purchase.variant_attributes.pluck(:id).include?(base_variant_id) }
elsif installment_type == SELLER_TYPE
purchases.where(seller_id:)
end
purchases && purchases.select { |purchase| purchase_passes_filters(purchase) }.first
end
def eligible_purchase?(purchase)
return true unless needs_purchase_to_access_content?
return false if purchase.nil?
is_purchase_relevant = if product_type?
purchase.link_id == link_id
elsif variant_type?
purchase.variant_attributes.pluck(:id).include?(base_variant_id)
elsif seller_type?
purchase.seller_id == seller_id
else
false
end
is_purchase_relevant && purchase_passes_filters(purchase)
end
def affiliate_product_name
return unless is_affiliate_product_post?
Link.find_by(unique_permalink: affiliate_products.first)&.name
end
def audience_members_filter_params
params = {}
if seller_or_product_or_variant_type?
params[:type] = "customer"
elsif follower_type?
params[:type] = "follower"
elsif affiliate_type?
params[:type] = "affiliate"
end
params[:bought_product_ids] = seller.products.where(unique_permalink: bought_products).ids if bought_products.present?
params[:not_bought_product_ids] = seller.products.where(unique_permalink: not_bought_products).ids if not_bought_products.present?
params[:bought_variant_ids] = bought_variants&.map { ObfuscateIds.decrypt(_1) }
params[:not_bought_variant_ids] = not_bought_variants&.map { ObfuscateIds.decrypt(_1) }
params[:paid_more_than_cents] = paid_more_than_cents.presence
params[:paid_less_than_cents] = paid_less_than_cents.presence
params[:created_after] = Date.parse(created_after.to_s).in_time_zone(seller.timezone).iso8601 if created_after.present?
params[:created_before] = Date.parse(created_before.to_s).in_time_zone(seller.timezone).end_of_day.iso8601 if created_before.present?
params[:bought_from] = bought_from if bought_from.present?
params[:affiliate_product_ids] = seller.products.where(unique_permalink: affiliate_products).ids if affiliate_products.present?
params.compact_blank!
end
def audience_members_count(limit = nil)
AudienceMember.filter(seller_id:, params: audience_members_filter_params).limit(limit).count
end
def self.receivable_by_customers_of_product(product:, variant_external_id:)
product_permalink = product.unique_permalink
product_variant_external_ids = product.alive_variants.map(&:external_id)
posts = self.includes(:installment_rule, :seller).alive.published.where(seller_id: product.user_id).filter do |post|
post.seller_or_product_or_variant_type? && (
(post.bought_products.present? && post.bought_products.include?(product_permalink)) ||
(post.bought_variants.present? && post.bought_variants.any? { product_variant_external_ids.include?(_1) }) ||
(post.bought_products.blank? && post.bought_variants.blank?)
)
end
if variant_external_id.present?
posts = posts.filter do |post|
(post.bought_products.blank? && post.bought_variants.blank?) ||
(post.bought_products.presence || []).include?(product_permalink) ||
(post.bought_variants.presence || []).include?(variant_external_id)
end
end
posts.sort_by do |post|
post.workflow_id.present? && post.installment_rule.present? ? DateTime.current + post.installment_rule.delayed_delivery_time : post.published_at
end.reverse
end
def has_been_blasted? = blasts.exists?
def can_be_blasted? = send_emails? && !has_been_blasted?
def featured_image_url
return nil if message.blank?
fragment = Nokogiri::HTML.fragment(message)
first_element = fragment.element_children.first
return nil unless first_element&.name == "figure"
first_element.at_css("img")&.attr("src")
end
def message_snippet
return "" if message.blank?
# Add spaces between paragraphs and line breaks, so that `Hello<br/>World`
# becomes `Hello World`.
spaced_message = message.split(%r{</p>|<br\s*/?>}i).join(" ")
strip_tags(spaced_message)
.squish
.truncate(200, separator: " ", omission: "...")
end
def tags
return [] if message.blank?
fragment = Nokogiri::HTML.fragment(message)
last_element = fragment.element_children.last
return [] unless last_element&.name == "p"
tags = last_element.content.split
return [] unless tags.all? { |tag| tag.start_with?("#") }
tags.map { normalize_tag(it) }.uniq
end
class InstallmentInvalid < StandardError
end
class PreviewEmailError < StandardError
end
private
# message, no name or file is ok
# if name or file, then need the other
def message_must_be_provided
errors.add(:base, "Please include a message as part of the update.") if scrubbed_message.blank?
end
def scrubbed_message
# Default empty message from TipTap editor is "<p><br></p>", so we need check the scrubbed version of the message for validation
scrubber = Rails::HTML::TargetScrubber.new
scrubber.tags = %w[br p]
sanitize(message, scrubber:)
end
def validate_call_to_action_url_and_text
return unless call_to_action_url.present? || call_to_action_text.present?
errors.add(:base, "Please enter text for your call to action.") if call_to_action_text.blank?
errors.add(:base, "Please provide a valid URL for your call to action.") unless call_to_action_url.present? && call_to_action_url =~ /\A#{URI.regexp([%w[http https]])}\z/
end
def expected_delivery_time(sale)
return sale.created_at unless installment_rule.present?
original_delivery_time = sale.created_at + installment_rule.delayed_delivery_time
subscription = sale.subscription
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/early_fraud_warning.rb | app/models/early_fraud_warning.rb | # frozen_string_literal: true
class EarlyFraudWarning < ApplicationRecord
self.table_name = "purchase_early_fraud_warnings"
has_paper_trail
include TimestampStateFields
belongs_to :purchase, optional: true
belongs_to :charge, optional: true
belongs_to :dispute, optional: true
belongs_to :refund, optional: true
stripped_fields :resolution_message
validates :processor_id, presence: true, uniqueness: true
validates_presence_of :purchase, if: -> { charge.blank? }
validates_uniqueness_of :purchase, allow_nil: true
validates_presence_of :charge, if: -> { purchase.blank? }
validates_uniqueness_of :charge, allow_nil: true
validate :only_one_of_purchase_or_charge_is_allowed
ELIGIBLE_DISPUTE_WINDOW_DURATION = 120.days
# https://stripe.com/docs/api/radar/early_fraud_warnings/object#early_fraud_warning_object-fraud_type
FRAUD_TYPES = %w(
card_never_received
fraudulent_card_application
made_with_counterfeit_card
made_with_lost_card
made_with_stolen_card
misc
unauthorized_use_of_card
).freeze
FRAUD_TYPES.each do |fraud_type|
self.const_set("FRAUD_TYPE_#{fraud_type.upcase}", fraud_type)
end
validates :fraud_type, inclusion: { in: FRAUD_TYPES }
# https://stripe.com/docs/api/charges/object#charge_object-outcome-risk_level
CHARGE_RISK_LEVELS = %w(normal elevated highest unknown).freeze
CHARGE_RISK_LEVELS.each do |charge_risk_level|
self.const_set("CHARGE_RISK_LEVEL_#{charge_risk_level.upcase}", charge_risk_level)
end
validates :charge_risk_level, inclusion: { in: CHARGE_RISK_LEVELS }
RESOLUTIONS = %w(
unknown
not_actionable_disputed
not_actionable_refunded
resolved_customer_contacted
resolved_ignored
resolved_refunded_for_fraud
).freeze
RESOLUTIONS.each do |resolution|
self.const_set("RESOLUTION_#{resolution.upcase}", resolution)
end
validates :resolution, inclusion: { in: RESOLUTIONS }
timestamp_state_fields :created, :processor_created, :resolved
def update_from_stripe!
EarlyFraudWarning::UpdateService.new(self).perform!
rescue EarlyFraudWarning::UpdateService::AlreadyResolvedError
# Ignore
end
def chargeable_refundable_for_fraud?
return false if chargeable.created_at.before?(ELIGIBLE_DISPUTE_WINDOW_DURATION.ago)
true
end
ELIGIBLE_EMAIL_INFO_STATES_FOR_SUBSCRIPTION_CONTACTABLE = %w(sent delivered opened).freeze
def purchase_for_subscription_contactable?
return false if fraud_type != FRAUD_TYPE_UNAUTHORIZED_USE_OF_CARD
return false if purchase_for_subscription.present? && purchase_for_subscription.subscription.blank?
return false if charge_risk_level != CHARGE_RISK_LEVEL_NORMAL
return false if receipt_email_info.blank? ||
ELIGIBLE_EMAIL_INFO_STATES_FOR_SUBSCRIPTION_CONTACTABLE.exclude?(receipt_email_info.state)
true
end
def associated_early_fraud_warning_ids_for_subscription_contacted
# The parent purchase might be associated with a charge, while a recurring purchase doesn't have a charge
other_purchases = purchase_for_subscription.subscription.purchases.where.not(id: purchase_for_subscription.id)
other_purchase_ids = other_purchases.reject { _1.charge.present? }.map(&:id)
other_charge_ids = other_purchases.select { _1.charge.present? }.map { _1.charge.id }.uniq
EarlyFraudWarning.where(purchase_id: other_purchase_ids)
.or(EarlyFraudWarning.where(charge_id: other_charge_ids))
.where(resolution: RESOLUTION_RESOLVED_CUSTOMER_CONTACTED)
.ids
end
def chargeable
charge || purchase
end
def purchase_for_subscription
@_purchase_for_subscription ||= if charge.present?
charge.first_purchase_for_subscription
else
purchase if purchase.subscription.present?
end
end
private
def receipt_email_info
@_receipt_email_info ||= chargeable.receipt_email_info
end
def only_one_of_purchase_or_charge_is_allowed
return if purchase.present? ^ charge.present?
errors.add(:base, "Only a purchase or a charge is allowed.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/utm_link_driven_sale.rb | app/models/utm_link_driven_sale.rb | # frozen_string_literal: true
class UtmLinkDrivenSale < ApplicationRecord
belongs_to :utm_link
belongs_to :utm_link_visit
belongs_to :purchase
validates :purchase_id, uniqueness: { scope: :utm_link_visit_id }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_wallet_type.rb | app/models/purchase_wallet_type.rb | # frozen_string_literal: true
class PurchaseWalletType < ApplicationRecord
belongs_to :purchase, optional: true
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bank.rb | app/models/bank.rb | # frozen_string_literal: true
class Bank < ApplicationRecord
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/hungary_bank_account.rb | app/models/hungary_bank_account.rb | # frozen_string_literal: true
class HungaryBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "HU"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::HUN.alpha2
end
def currency
Currency::HUF
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_profile.rb | app/models/seller_profile.rb | # frozen_string_literal: true
class SellerProfile < ApplicationRecord
FONT_CHOICES = ["ABC Favorit", "Inter", "Domine", "Merriweather", "Roboto Slab", "Roboto Mono"]
belongs_to :seller, class_name: "User"
validates :font, inclusion: { in: FONT_CHOICES }
validates :background_color, hex_color: true
validates :highlight_color, hex_color: true
validate :validate_json_data, if: -> { self[:json_data].present? }
after_save :clear_custom_style_cache, if: -> { %w[highlight_color background_color font].any? { |prop| send(:"saved_change_to_#{prop}?") } }
after_initialize do
self.font ||= "ABC Favorit"
self.background_color ||= "#ffffff"
self.highlight_color ||= "#ff90e8"
end
def custom_styles
Rails.cache.fetch(custom_style_cache_name) do
component_path = File.read(Rails.root.join("app", "views", "layouts", "custom_styles", "styles.scss.erb"))
sass = ERB.new(component_path).result(binding)
SassC::Engine.new(
sass,
syntax: :scss,
load_paths: Rails.application.config.assets.paths,
read_cache: false,
cache: false,
style: :compressed,
).render
end
end
def font_family
fallback = case font
when "Domine", "Merriweather", "Roboto Slab"
"serif"
when "Roboto Mono"
"monospace"
else
"sans-serif"
end
%("#{font}", "ABC Favorit", #{fallback})
end
def custom_style_cache_name
"users/#{seller.id}/custom_styles_v2"
end
def validate_json_data
# slice away the "in schema [id]" part that JSON::Validator otherwise includes
json_validator.validate(json_data).each { errors.add(:base, _1[..-48]) }
end
def json_validator
json_schema = JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "seller_profile.json").to_s))
@__json_validator ||= JSON::Validator.new(json_schema, insert_defaults: true, record_errors: true)
end
def json_data
self[:json_data] ||= {}
super
end
private
def clear_custom_style_cache
Rails.cache.delete custom_style_cache_name
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/balance_transaction.rb | app/models/balance_transaction.rb | # frozen_string_literal: true
# A record that records each change to a Balance record.
# Positive amount_cents represent deposited into the Balance.
# Negative amount_cents represent money withdrawn from the Balance.
class BalanceTransaction < ApplicationRecord
include Immutable
include ExternalId
class Amount
# The currency of the amount.
attr_accessor :currency
# The gross amount of money that was collected or received prior to fees, taxes and affiliate portions being taken out (in the currency).
attr_accessor :gross_cents
# The net amount of money that the user has earned towards their balance (in the currency).
attr_accessor :net_cents
def initialize(currency:, gross_cents:, net_cents:)
@currency = currency
@gross_cents = gross_cents
@net_cents = net_cents
end
def self.create_issued_amount_for_affiliate(flow_of_funds:, issued_affiliate_cents:)
new(
currency: flow_of_funds.gumroad_amount.currency,
gross_cents: issued_affiliate_cents,
net_cents: issued_affiliate_cents
)
end
def self.create_holding_amount_for_affiliate(flow_of_funds:, issued_affiliate_cents:)
new(
currency: flow_of_funds.gumroad_amount.currency,
gross_cents: issued_affiliate_cents,
net_cents: issued_affiliate_cents
)
end
def self.create_issued_amount_for_seller(flow_of_funds:, issued_net_cents:)
new(
currency: flow_of_funds.issued_amount.currency,
gross_cents: flow_of_funds.issued_amount.cents,
net_cents: issued_net_cents
)
end
def self.create_holding_amount_for_seller(flow_of_funds:, issued_net_cents:)
if flow_of_funds.merchant_account_gross_amount
new(
currency: flow_of_funds.merchant_account_gross_amount.currency,
gross_cents: flow_of_funds.merchant_account_gross_amount.cents,
net_cents: flow_of_funds.merchant_account_net_amount.cents
)
else
new(
currency: flow_of_funds.issued_amount.currency,
gross_cents: flow_of_funds.issued_amount.cents,
net_cents: issued_net_cents
)
end
end
end
MAX_ATTEMPTS_TO_UPDATE_BALANCE = 2
private_constant :MAX_ATTEMPTS_TO_UPDATE_BALANCE
belongs_to :user
belongs_to :merchant_account
belongs_to :balance, optional: true
# Belongs to one of the following: purchase, dispute, refund, credit.
belongs_to :purchase, optional: true
belongs_to :dispute, optional: true
belongs_to :refund, optional: true
belongs_to :credit, optional: true
# The balance_id should never be changed once it's set, but it gets set after the initial BalanceTransaction record is saved and so must be marked as mutable
# so that it can be set after the initial save.
attr_mutable :balance_id
validate :validate_exactly_one_of_purchase_dispute_refund_credit_is_present
# Public: Creates a balance transaction for a user and mutates the User's balance and Balance objects.
# The merchant account should be the account that the funds are being held in, and for a purchase this is simply the same merchant account as the purchase.
#
# issued_amount is the money that was issued by an credit card issuer to the merchant account, for a purchase it will be the amount that was actually
# charged to the buyers card, for a refund it will be the amount actually returned to the issuer, etc.
#
# holding_amount is the money that was collected and is actually being held in the merchant account, for a purchase it will be the amount that is
# settled into the merchant account after the charge was successfully authorized and completed, and this amount will always be in the currency of the
# merchant account (USD, CAD, AUD, GBP, etc) or Gumroad's merchant account (USD).
#
# Returns the BalanceTransaction, which will have an association to the `Balance` affected.
def self.create!(user:, merchant_account:, purchase: nil, refund: nil, dispute: nil, credit: nil, issued_amount:, holding_amount:, update_user_balance: true)
balance_transaction = new
balance_transaction.user = user
balance_transaction.merchant_account = merchant_account
balance_transaction.purchase = purchase
balance_transaction.refund = refund
balance_transaction.dispute = dispute
balance_transaction.credit = credit
balance_transaction.issued_amount_currency = issued_amount.currency
balance_transaction.issued_amount_gross_cents = issued_amount.gross_cents
balance_transaction.issued_amount_net_cents = issued_amount.net_cents
balance_transaction.holding_amount_currency = holding_amount.currency
balance_transaction.holding_amount_gross_cents = holding_amount.gross_cents
balance_transaction.holding_amount_net_cents = holding_amount.net_cents
balance_transaction.save!
# The balances are updated outside of the save so that Balance selection occurs outside of a transaction. Because balance selection involves the selection
# and locking of balances and that occurs concurrently in other threads for payout, refund, etc, there is the possibility for deadlock if the selection
# and locking occurs within a transaction that may implicitly lock other records. For this reason it's safer to save the BalanceTransaction and complete
# it's transaction, and then do the selection outside of a transaction, ensuring that we only lock on the Balance object when updating it.
if update_user_balance
balance_transaction.update_balance!
end
balance_transaction
end
# Public: Update the balance for this balance transaction, selecting the most appropriate balance given the type of object it's associated with.
# Selection of a balance may be attempted multiple times in the rare case of the balance state changing between when we select and lock it and
# it's in a state where the amounts cannot be changed. If the maximum number of attempts is exhausted, the ActiveRecord::RecordInvalid error from the attempt
# to change the amount will be passed up.
def update_balance!
balance = find_or_create_balance
balance.with_lock do
balance.increment(:amount_cents, issued_amount_net_cents)
balance.increment(:holding_amount_cents, holding_amount_net_cents)
balance.save!
self.balance = balance
save!
end
rescue ActiveRecord::RecordInvalid => e
# Saving the balance can fail if the balance's state changed between selection and locking, to a state invalid for changing the amounts.
failed_count ||= 1
logger.info("Updating balance for transaction #{id}: Balance #{balance.id} could not be saved. Failed count: #{failed_count} Exception:\n#{e}")
failed_count += 1
retry if failed_count < MAX_ATTEMPTS_TO_UPDATE_BALANCE
raise
end
# Public: Selects the most appropriate balance given the type of object this balance transaction is associated with.
# Creates a balance if one does not already exists.
# Returns the balance found or created.
def find_or_create_balance
# Working around Octopus choosing the slave db for all selects, even the ones with "FOR UPDATE"
ActiveRecord::Base.connection.stick_to_primary!
unpaid_balances = Balance.where(
user:,
merchant_account:,
currency: issued_amount_currency,
holding_currency: holding_amount_currency,
state: "unpaid"
).order(date: :asc)
# attempt to find an existing balance this transaction can be applied to, as close to when the money first moved relating to this change in balance
balance =
if purchase
unpaid_balances.where(date: purchase.succeeded_at.to_date).first
elsif refund
unpaid_balances.where(date: refund.purchase.succeeded_at.to_date).first || unpaid_balances.first
elsif dispute
unpaid_balances.where(date: dispute.disputable.dispute_balance_date).first || unpaid_balances.first
elsif credit&.financing_paydown_purchase
unpaid_balances.where(date: credit.financing_paydown_purchase.succeeded_at.to_date).first || unpaid_balances.first
elsif credit&.fee_retention_refund
unpaid_balances.first
elsif credit
unpaid_balances.first
end
# create the balance as a last resort
if balance.nil?
# get the date this balance transaction has occurred, based on the associated object
occurred_at =
if purchase
purchase.succeeded_at.to_date
elsif refund
refund.created_at.to_date
elsif dispute
dispute.formalized_at.to_date
elsif credit
credit.created_at.to_date
end
# create a new balance at the date this balance transaction occurred
balance =
begin
Balance.create!(
user:,
merchant_account:,
currency: issued_amount_currency,
holding_currency: holding_amount_currency,
date: occurred_at
)
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
logger.info("Creating balance for transaction #{id}: Balance already exists in the DB; we are not duplicating it. Exception: #{e.message}")
unpaid_balances.where(date: occurred_at).first
end
end
raise BalanceCouldNotBeFoundOrCreated, id if balance.nil?
balance
end
private
def validate_exactly_one_of_purchase_dispute_refund_credit_is_present
exactly_one_is_present = purchase.present? ^ dispute.present? ^ refund.present? ^ credit.present?
return if exactly_one_is_present
errors.add(:base, "can only have one of: purchase, dispute, refund, credit")
end
class BalanceCouldNotBeFoundOrCreated < GumroadRuntimeError
def initialize(balance_transaction_id)
super("A suitable balance for transaction #{balance_transaction_id} could not be found or created.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/madagascar_bank_account.rb | app/models/madagascar_bank_account.rb | # frozen_string_literal: true
class MadagascarBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MG"
BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^MG([0-9]){25}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::MDG.alpha2
end
def currency
Currency::MGA
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/link.rb | app/models/link.rb | # frozen_string_literal: true
require "zip/zipfilesystem"
class Link < ApplicationRecord
has_paper_trail
# Moving the definition of these flags will cause an error.
include FlagShihTzu
include ActionView::Helpers::SanitizeHelper
has_flags 1 => :product_refund_policy_enabled,
2 => :is_recurring_billing,
3 => :free_trial_enabled,
4 => :is_in_preorder_state,
5 => :archived,
6 => :is_duplicating,
7 => :is_licensed,
8 => :is_physical,
9 => :skus_enabled,
10 => :block_access_after_membership_cancellation,
11 => :is_price_tax_exclusive_DEPRECATED,
12 => :should_include_last_post,
13 => :from_bundle_marketing,
14 => :quantity_enabled,
15 => :has_outdated_purchases,
16 => :is_adult,
17 => :display_product_reviews,
18 => :allow_double_charges,
19 => :is_tiered_membership,
20 => :should_show_all_posts,
21 => :is_multiseat_license,
22 => :should_show_sales_count,
23 => :is_epublication,
24 => :transcode_videos_on_purchase,
25 => :has_same_rich_content_for_all_variants,
26 => :is_bundle,
27 => :purchasing_power_parity_disabled,
28 => :is_collab,
29 => :is_unpublished_by_admin,
30 => :community_chat_enabled,
31 => :DEPRECATED_excluded_from_mobile_app_discover,
32 => :moderated_by_iffy,
33 => :hide_sold_out_variants,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
include ProductsHelper, PreorderHelper, CurrencyHelper, SocialShareUrlHelper, Product::AsJson, Product::Stats, Product::Preview,
Product::Validations, Product::Caching, Product::NativeTypeTemplates, Product::Recommendations,
Product::Prices, Product::Shipping, Product::Searchable, Product::Tags, Product::Taxonomies,
Product::ReviewStat, Product::Utils, Product::StructuredData, ActionView::Helpers::SanitizeHelper,
ActionView::Helpers::NumberHelper, Mongoable, TimestampScopes, ExternalId,
WithFileProperties, JsonData, Deletable, WithProductFiles, WithCdnUrl, MaxPurchaseCount,
Integrations, Product::StaffPicked, RichContents, Product::Sorting, Product::CreationLimit
has_cdn_url :description
TIME_EVENTS_TABLE_CREATED = Time.zone.parse("2012-10-11 23:35:41")
PURCHASE_PROPERTIES = ["updated_at"].freeze
MAX_ALLOWED_FILE_SIZE_FOR_SEND_TO_KINDLE = 15_500_000.bytes
METADATA_CACHE_NAMESPACE = :product_metadata_cache
REQUIRE_CAPTCHA_FOR_SELLERS_YOUNGER_THAN = 6.months
# Tax categories: https://developers.taxjar.com/api/reference/#get-list-tax-categories
# Categories mapping choices: https://www.notion.so/gumroad/System-support-for-US-sales-tax-collection-on-Gumroad-MPF-sales-9fa88740bf3c4453b476b7fa0a7af1e7#3404578361074b4ca24a6fb63464f522
NATIVE_TYPES_TO_TAX_CODE = {
"digital" => "31000",
"course" => "86132000A0002",
"ebook" => "31000",
"newsletter" => "55111516A0310",
"membership" => "55111516A0310",
"podcast" => "55111516A0310",
"audiobook" => "31000",
"physical" => nil,
"bundle" => "55111500A9220",
"commission" => nil,
"call" => nil,
"coffee" => nil,
}.freeze
NATIVE_TYPES = NATIVE_TYPES_TO_TAX_CODE.keys.freeze
NATIVE_TYPES.each do |native_type|
self.const_set("NATIVE_TYPE_#{native_type.upcase}", native_type)
end
SERVICE_TYPES = [NATIVE_TYPE_COMMISSION, NATIVE_TYPE_CALL, NATIVE_TYPE_COFFEE].freeze
LEGACY_TYPES = ["podcast", "newsletter", "audiobook"].freeze
DEFAULT_BOOSTED_DISCOVER_FEE_PER_THOUSAND = 300
belongs_to :user, optional: true
has_many :prices
has_many :alive_prices, -> { alive }, class_name: "Price"
has_one :installment_plan, -> { alive }, class_name: "ProductInstallmentPlan"
has_many :sales, class_name: "Purchase"
has_many :orders, through: :sales, source: :order
has_many :sold_calls, through: :sales, source: :call
has_many :asset_previews
has_one :thumbnail, foreign_key: "product_id"
has_one :thumbnail_alive, -> { alive }, class_name: "Thumbnail", foreign_key: "product_id"
has_many :display_asset_previews, -> { alive.in_order }, class_name: "AssetPreview"
has_many :gifts
has_many :url_redirects
has_many :variant_categories
has_many :variant_categories_alive, -> { alive }, class_name: "VariantCategory"
has_many :variants, through: :variant_categories, class_name: "Variant"
has_many :alive_variants, through: :variant_categories_alive, source: :alive_variants
has_many :tier_categories, -> { alive.is_tier_category }, class_name: "VariantCategory"
has_many :tiers, through: :tier_categories, class_name: "Variant"
has_one :tier_category, -> { alive.is_tier_category }, class_name: "VariantCategory"
has_one :default_tier, through: :tier_category
has_many :skus
has_many :skus_alive_not_default, -> { alive.not_is_default_sku }, class_name: "Sku"
has_many :installments
has_many :subscriptions
has_and_belongs_to_many :offer_codes, join_table: "offer_codes_products", foreign_key: "product_id"
has_many :transcoded_videos
has_many :imported_customers
has_many :licenses
has_one :preorder_link
belongs_to :affiliate_application, class_name: "OauthApplication", optional: true
has_many :affiliate_credits
has_many :comments, as: :commentable
has_many :workflows
has_many :dropbox_files
has_many :shipping_destinations
has_many :product_affiliates
has_many :affiliates, through: :product_affiliates
has_many :direct_affiliates, -> { direct_affiliates }, through: :product_affiliates, source: :affiliate
has_many :global_affiliates, -> { global_affiliates }, through: :product_affiliates, source: :affiliate
has_many :confirmed_collaborators, -> { confirmed_collaborators }, through: :product_affiliates, source: :affiliate
has_many :pending_or_confirmed_collaborators, -> { pending_or_confirmed_collaborators }, through: :product_affiliates, source: :affiliate
has_many :self_service_affiliate_products, foreign_key: :product_id
has_many :third_party_analytics
has_many :alive_third_party_analytics, -> { alive }, class_name: "ThirdPartyAnalytic"
# info of purchases this product has recommended
has_many :recommended_purchase_infos, class_name: "RecommendedPurchaseInfo", foreign_key: :recommended_by_link_id
# info of recommended purchases that have bought this product
has_many :recommended_by_purchase_infos, class_name: "RecommendedPurchaseInfo", foreign_key: :recommended_link_id
has_one :product_review_stat
has_many :product_reviews
has_many :product_integrations, class_name: "ProductIntegration", foreign_key: :product_id
has_many :live_product_integrations, -> { alive }, class_name: "ProductIntegration", foreign_key: :product_id
has_many :active_integrations, through: :live_product_integrations, source: :integration
has_many :product_cached_values, foreign_key: :product_id
has_one :upsell, -> { upsell.alive }, foreign_key: :product_id
has_one :available_upsell, -> { upsell.available_to_customers },
class_name: "Upsell", foreign_key: :product_id
has_many :available_upsell_variants, through: :available_upsell, source: :upsell_variants
has_many :available_cross_sells, ->(link) {
includes(:selected_products)
.where(selected_products: { id: link.id })
.or(where(universal: true))
}, through: :user, source: :available_cross_sells
has_and_belongs_to_many :custom_fields, join_table: "custom_fields_products", foreign_key: "product_id"
has_one :product_refund_policy, foreign_key: "product_id"
has_one :staff_picked_product, foreign_key: "product_id"
has_one :custom_domain, -> { alive }, foreign_key: "product_id"
has_many :bundle_products, foreign_key: "bundle_id", inverse_of: :bundle
has_many :wishlist_products, foreign_key: "product_id"
has_many :call_availabilities, foreign_key: "call_id"
has_one :call_limitation_info, foreign_key: "call_id"
has_many :seller_profile_sections, foreign_key: :product_id
has_many :public_files, as: :resource
has_many :alive_public_files, -> { alive }, class_name: "PublicFile", as: :resource
has_many :communities, as: :resource, dependent: :destroy
has_one :active_community, -> { alive }, class_name: "Community", as: :resource
before_validation :associate_price, on: :create
before_validation :set_unique_permalink
before_validation :release_custom_permalink_if_possible, if: :custom_permalink_changed?
validates :user, presence: true
validates :name, presence: true, length: { maximum: 255 }
# Keep in sync with Product::BulkUpdateSupportEmailService.
validates :support_email, email_format: true, not_reserved_email_domain: true, allow_nil: true
validates :default_price_cents, presence: true
validates :unique_permalink, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z_]+\z/ }
validates :custom_permalink, format: { with: /\A[a-zA-Z0-9_-]+\z/ }, uniqueness: { scope: :user_id, case_sensitive: false }, allow_nil: true, allow_blank: true
validate :suggested_price_greater_than_price
validate :duration_multiple_of_price_options
validate :custom_and_unique_permalink_uniqueness
validate :custom_permalink_of_licensed_product, if: :custom_permalink_or_is_licensed_changed?
validate :max_purchase_count_is_greater_than_or_equal_to_inventory_sold
validate :free_trial_only_enabled_if_recurring_billing
validates :native_type, inclusion: { in: NATIVE_TYPES }
validates :discover_fee_per_thousand, inclusion: { in: [100, *(300..1000)], message: "must be between 30% and 100%" }
validates :free_trial_duration_unit, presence: true, if: :free_trial_enabled?
# Only allow "1 week" and "1 month" free trials for now
validates :free_trial_duration_amount, presence: true,
numericality: { only_integer: true,
equal_to: 1,
allow_nil: true },
if: ->(link) { link.free_trial_enabled? && (!link.persisted? || link.free_trial_duration_amount_changed?) }
validate :price_must_be_within_range
validate :require_shipping_for_physical
validate :valid_tier_version_structure, if: :is_tiered_membership, on: :update
validate :calls_must_have_at_least_one_duration, on: :update
validate :alive_category_variants_presence, on: :update
validate :content_has_no_adult_keywords, if: -> { description_changed? || name_changed? }
validate :custom_view_content_button_text_length
validates :custom_receipt_text, length: { maximum: Product::Validations::MAX_CUSTOM_RECEIPT_TEXT_LENGTH }
validates_presence_of :filetype
validates_presence_of :filegroup
validate :bundle_is_not_in_bundle, if: :is_bundle_changed?
validate :published_bundle_must_have_at_least_one_product, on: :update
validate :user_is_eligible_for_service_products, on: :create, if: :is_service?
validate :commission_price_is_valid, if: -> { native_type == Link::NATIVE_TYPE_COMMISSION }
validate :one_coffee_per_user, on: :create, if: -> { native_type == Link::NATIVE_TYPE_COFFEE }
validate :quantity_enabled_state_is_allowed
validates_associated :installment_plan, message: -> (link, _) { link.installment_plan.errors.full_messages.first }
before_save :downcase_filetype
before_save :remove_xml_tags
after_save :set_customizable_price
after_update :invalidate_cache, if: ->(link) { (link.saved_changes.keys - PURCHASE_PROPERTIES).present? }
after_update :create_licenses_for_existing_customers,
if: ->(link) { link.saved_change_to_is_licensed? && link.is_licensed? }
after_update :delete_unused_prices, if: :saved_change_to_purchase_type?
after_update :reset_moderated_by_iffy_flag, if: :saved_change_to_description?
after_save :queue_iffy_ingest_job_if_unpublished_by_admin
enum subscription_duration: %i[monthly yearly quarterly biannually every_two_years]
enum purchase_type: %i[buy_only rent_only buy_and_rent] # Indicates whether this product can be bought or rented or both.
enum free_trial_duration_unit: %i[week month]
attr_json_data_accessor :excluded_sales_tax_regions, default: -> { [] }
attr_json_data_accessor :sections, default: -> { [] }
attr_json_data_accessor :main_section_index, default: -> { 0 }
attr_json_data_accessor :custom_view_content_button_text
attr_json_data_accessor :custom_receipt_text
scope :alive, -> { where(purchase_disabled_at: nil, banned_at: nil, deleted_at: nil) }
scope :visible, -> { where(deleted_at: nil) }
scope :visible_and_not_archived, -> { visible.not_archived }
scope :by_user, ->(user) { where(user.present? ? { user_id: user.id } : "1 = 1") }
scope :by_general_permalink, ->(permalink) { where("unique_permalink = ? OR custom_permalink = ?", permalink, permalink) }
scope :by_unique_permalinks, ->(permalinks) { where("unique_permalink IN (?)", permalinks) }
scope :has_paid_sales, lambda {
distinct.joins(:sales).where("purchases.purchase_state = 'successful' AND purchases.price_cents > 0" \
" AND (purchases.stripe_refunded IS NULL OR purchases.stripe_refunded = 0)")
}
scope :not_draft, -> { where(draft: false) }
scope :has_paid_sales_between, lambda { |begin_time, end_time|
distinct.joins(:sales).where(["purchases.purchase_state = 'successful' AND purchases.price_cents > 0 AND purchases.created_at > ?" \
"AND purchases.created_at < ? AND (purchases.stripe_refunded IS NULL OR purchases.stripe_refunded = 0)", begin_time, end_time])
}
scope :membership, -> { is_recurring_billing }
scope :non_membership, -> { not_is_recurring_billing }
scope :with_min_price, ->(min_price) { min_price.present? ? distinct.joins(:prices).where("prices.deleted_at IS NULL AND prices.price_cents >= ?", min_price) : where("1 = 1") }
# !! MySQL ONLY !! Retrieves products in the order specified by the ids array. Relies on MySQL FIELD.
scope :ordered_by_ids, ->(ids) { order([Arel.sql("FIELD(links.id, ?)"), ids]) }
scope :with_direct_affiliates, -> { left_outer_joins(:direct_affiliates) }
scope :for_affiliate_user, ->(affiliate_user_id) { where(affiliates: { affiliate_user_id: }) }
scope :with_user_category, ->(category_ids) {
distinct.joins(user: [:categories]).where(categories: category_ids)
}
scope :collabs_as_collaborator, ->(user) do
joins(product_affiliates: :affiliate)
.is_collab
.where(affiliates: { affiliate_user: user })
.merge(Collaborator.invitation_accepted.alive)
end
scope :collabs_as_seller_or_collaborator, ->(user) do
joins(product_affiliates: :affiliate)
.is_collab
.where("affiliates.seller_id = :user_id OR affiliates.affiliate_user_id = :user_id", user_id: user.id)
.merge(Collaborator.invitation_accepted.alive)
end
scope :for_balance_page, ->(user) do
products_as_seller = Link.where(user: user)
collabs_as_collaborator = Link.collabs_as_collaborator(user)
subquery_sqls = [products_as_seller, collabs_as_collaborator].map(&:to_sql)
from("(" + subquery_sqls.join(" UNION ") + ") AS #{table_name}")
end
scope :not_call, -> { where.not(native_type: NATIVE_TYPE_CALL) }
scope :can_be_bundle, -> { non_membership.not_call.where.missing(:variant_categories_alive).or(is_bundle) }
scope :with_latest_product_cached_values, ->(user_id:) {
products_ids_sql = Link.where(user_id:).select(:id).to_sql # redundant subquery for performance
cte_join_sql = <<~SQL.squish
INNER JOIN (
SELECT product_id, MAX(id) AS max_id
FROM product_cached_values
WHERE product_id IN (#{products_ids_sql})
GROUP BY product_id
) latest ON product_cached_values.product_id = latest.product_id AND product_cached_values.id = latest.max_id
SQL
join_sql = <<~SQL.squish
LEFT JOIN latest_product_cached_values ON latest_product_cached_values.product_id = links.id
SQL
with(latest_product_cached_values: ProductCachedValue.joins(cte_join_sql)).joins(join_sql)
}
scope :eligible_for_content_upsells, -> { visible_and_not_archived.not_is_tiered_membership }
before_create :set_default_discover_fee_per_thousand
after_create :initialize_tier_if_needed
after_create :add_to_profile_sections
after_create :initialize_suggested_amount_if_needed!
after_create :initialize_call_limitation_info_if_needed!
after_create :initialize_duration_variant_category_for_calls!
def set_default_discover_fee_per_thousand
self.discover_fee_per_thousand = DEFAULT_BOOSTED_DISCOVER_FEE_PER_THOUSAND if user.discover_boost_enabled?
end
def initialize_tier_if_needed
if is_tiered_membership
self.subscription_duration ||= BasePrice::Recurrence::DEFAULT_TIERED_MEMBERSHIP_RECURRENCE
category = variant_categories.create!(title: "Tier")
category.variants.create!(name: "Untitled")
initialize_default_tier_prices!
end
end
def initialize_default_tier_prices!
if default_tier.present?
# create a default price for the default tier
initial_price_cents = read_attribute(:price_cents) || 0
initial_price_cents = initial_price_cents * 100.0 if single_unit_currency?
default_tier.save_recurring_prices!(
subscription_duration.to_s => {
enabled: true,
price: formatted_dollar_amount(initial_price_cents)
}
)
end
end
def initialize_suggested_amount_if_needed!
return unless native_type == NATIVE_TYPE_COFFEE
category = variant_categories.create!(title: "Suggested Amounts")
category.variants.create!(name: "", price_difference_cents: price_cents)
update!(price_cents: 0, customizable_price: true)
end
def initialize_call_limitation_info_if_needed!
return unless native_type == NATIVE_TYPE_CALL
create_call_limitation_info!
end
def initialize_duration_variant_category_for_calls!
return unless native_type == NATIVE_TYPE_CALL
variant_categories.create!(title: "Duration")
end
def banned?
banned_at.present?
end
def alive?
purchase_disabled_at.nil? && banned_at.nil? && deleted_at.nil?
end
alias_method :alive, :alive?
def published?
deleted_at.nil? && purchase_disabled_at.nil? && !draft
end
def compliance_blocked(ip)
return false if ip.blank?
country_code = GeoIp.lookup(ip)&.country_code
country_code.present? && Compliance::Countries.blocked?(country_code)
end
def admins_can_generate_url_redirects?
alive_product_files.any?
end
alias_method :admins_can_generate_url_redirects, :admins_can_generate_url_redirects?
def rentable?
rent_only? || buy_and_rent?
end
def buyable?
buy_only? || buy_and_rent?
end
def delete!
mark_deleted!
custom_domain&.mark_deleted!
alive_public_files.update_all(scheduled_for_deletion_at: 10.minutes.from_now)
CancelSubscriptionsForProductWorker.perform_in(10.minutes, id) if subscriptions.active.present?
DeleteProductFilesWorker.perform_in(10.minutes, id)
DeleteProductRichContentWorker.perform_in(10.minutes, id)
DeleteProductFilesArchivesWorker.perform_in(10.minutes, id, nil)
DeleteWishlistProductsJob.perform_in(10.minutes, id)
end
def publish!
enforce_shipping_destinations_presence!
enforce_user_email_confirmation!
enforce_merchant_account_exits_for_new_users!
if auto_transcode_videos?
transcode_videos!
else
enable_transcode_videos_on_purchase!
end
self.purchase_disabled_at = nil
self.deleted_at = nil
self.draft = false
save!
user.direct_affiliates.alive.apply_to_all_products.each do |affiliate|
unless affiliate.products.include?(self)
affiliate.products << self
AffiliateMailer.notify_direct_affiliate_of_new_product(affiliate.id, id).deliver_later
end
end
end
def unpublish!(is_unpublished_by_admin: false)
self.purchase_disabled_at ||= Time.current
self.is_unpublished_by_admin = is_unpublished_by_admin
save!
end
def publishable?
user.can_publish_products?
end
def has_filegroup?(filegroup)
alive_product_files.map(&:filegroup).include?(filegroup)
end
def has_filetype?(filetype)
alive_product_files.map(&:filetype).include?(filetype)
end
def has_stampable_pdfs?
alive_product_files.any?(&:must_be_pdf_stamped?)
end
alias_method :has_stampable_pdfs, :has_stampable_pdfs?
def streamable?
has_filegroup?("video")
end
alias_method :streamable, :streamable?
def require_captcha?
user.created_at > REQUIRE_CAPTCHA_FOR_SELLERS_YOUNGER_THAN.ago
end
def stream_only?
alive_product_files.all?(&:stream_only?)
end
def listenable?
has_filegroup?("audio")
end
def readable?
has_filetype?("pdf")
end
def can_enable_rentals?
streamable? && !is_in_preorder_state && !is_recurring_billing
end
def can_enable_quantity?
[NATIVE_TYPE_MEMBERSHIP, NATIVE_TYPE_CALL].exclude?(native_type)
end
def eligible_for_installment_plans?
ProductInstallmentPlan.eligible_for_product?(self)
end
def allow_installment_plan?
installment_plan.present?
end
def has_downloadable_content?
return false unless has_files?
return false if stream_only?
true
end
def customize_file_per_purchase?
# Add other forms of per-purchase file customizations here (e.g. video watermark).
has_stampable_pdfs?
end
def allow_parallel_purchases?
!max_purchase_count? && native_type != NATIVE_TYPE_CALL
end
def link
self
end
def long_url(recommended_by: nil, recommender_model_name: nil, include_protocol: true, layout: nil, affiliate_id: nil, query: nil, code: nil, autocomplete: false)
host = user.subdomain_with_protocol || UrlService.domain_with_protocol
options = { host: }
options[:recommended_by] = recommended_by if recommended_by.present?
options[:recommender_model_name] = recommender_model_name if recommender_model_name.present?
options[:layout] = layout if layout.present?
options[:query] = query if query.present?
options[:affiliate_id] = affiliate_id if affiliate_id.present?
options[:code] = code if code.present?
options[:autocomplete] = "true" if autocomplete
product_long_url = Rails.application.routes.url_helpers.short_link_url(general_permalink, options)
product_long_url.sub!(/\A#{PROTOCOL}:\/\//o, "") unless include_protocol
product_long_url
end
def thumbnail_or_cover_url
thumbnail_alive&.url || display_asset_previews.find(&:image_url?)&.url
end
def for_email_thumbnail_url
thumbnail_alive&.url ||
ActionController::Base.helpers.asset_url("native_types/thumbnails/#{native_type}.png")
end
def plaintext_description
return "" if description.blank?
escaped_description = sanitize(description, tags: [])
escaped_description = escaped_description.squish
escaped_description
end
def html_safe_description
return unless description.present?
Rinku.auto_link(sanitize(description, scrubber: description_scrubber), :all, 'target="_blank" rel="noopener noreferrer nofollow"').html_safe
end
def to_param
unique_permalink
end
def twitter_share_url
twitter_url(long_url, social_share_text)
end
def social_share_text
if user.twitter_handle.present?
return "I pre-ordered #{name} from @#{user.twitter_handle} on @Gumroad" if is_in_preorder_state
"I got #{name} from @#{user.twitter_handle} on @Gumroad"
else
return "I pre-ordered #{name} on @Gumroad" if is_in_preorder_state
"I got #{name} on @Gumroad"
end
end
def self.human_attribute_name(attr, _)
case attr
when "discover_fee_per_thousand" then "Gumroad fee"
when "native_type" then "Product type"
else super
end
end
def file_info_for_product_page
removed_file_info_attributes = self.removed_file_info_attributes
multifile_aware_product_file_info.delete_if { |key, _value| removed_file_info_attributes.include?(key) }
end
# Public: Returns the file info (size, dimensions, etc) if there's only one file associated with this product.
def multifile_aware_product_file_info
multifile_aware_product_file_info = {}
if alive_product_files.count == 1
multifile_aware_product_file_info = alive_product_files.first.file_info(require_shipping)
end
multifile_aware_product_file_info
end
def single_unit_currency?
currency.key?("single_unit")
end
def remaining_for_sale_count
return 0 unless variants_available?
return tiers.first.quantity_left if tiers.size == 1
minimum_bundle_product_quantity_left = if is_bundle?
bundle_products.alive.flat_map do
[_1.product.remaining_for_sale_count, _1.variant&.quantity_left]
end.compact.min
end
product_quantity_left = (max_purchase_count - sales_count_for_inventory) unless max_purchase_count.nil?
quantity_left = [product_quantity_left, minimum_bundle_product_quantity_left].compact.min
return if quantity_left.nil?
[quantity_left, 0].max
end
def remaining_call_availabilities
Product::ComputeCallAvailabilitiesService.new(self).perform
end
def options
if skus_enabled
skus.not_is_default_sku.alive.map(&:to_option_for_product)
elsif variant_categories_alive.any?
variants.where(variant_category: variant_categories_alive.first).in_order.alive.map(&:to_option)
else
[]
end
end
def variants_or_skus
skus_enabled? ? skus.not_is_default_sku.alive : alive_variants
end
def recurrences
is_recurring_billing ? {
default: default_price_recurrence.recurrence,
enabled: prices.alive.is_buy.sort_by { |price| BasePrice::Recurrence.number_of_months_in_recurrence(price.recurrence) }.map { |price| { recurrence: price.recurrence, price_cents: price.price_cents, id: price.external_id } }
} : nil
end
def rental
purchase_type != "buy_only" ? { price_cents: rental_price_cents, rent_only: purchase_type == "rent_only" } : nil
end
def is_legacy_subscription?
!is_tiered_membership && is_recurring_billing
end
def sales_count_for_inventory
sales.counts_towards_inventory.sum(:quantity)
end
def variants_available?
return true if variant_categories_alive.empty?
variant_categories_alive.any?(&:available?)
end
# Returns a visible (non-deleted) product identified by a permalink.
#
# Params:
# +general_permalink+ - unique or custom permalink to locate the product by
# +user+ - if passed, the search will be scoped to this user's products only.
# if not passed, the search will return the earliest product by unique or custom permalink.
# NOTE: a custom permalink can match different products by different sellers,
# this option should only be used to support legacy URLs.
# Ref: https://gumroad.slack.com/archives/C01B70APF9P/p1627054984386700
def self.fetch_leniently(general_permalink, user: nil)
product_via_legacy_permalink = Link.visible.find_by(id: LegacyPermalink.select(:product_id).where(permalink: general_permalink)) if user.blank?
product_via_legacy_permalink || Link.by_user(user).visible.by_general_permalink(general_permalink).order(created_at: :asc, id: :asc).first
end
def self.fetch(unique_permalink, user: nil)
Link.by_user(user).visible.find_by(unique_permalink:)
end
def can_gift?
!is_in_preorder_state
end
def time_fields
fields = attributes.keys.keep_if { |key| key.include?("_at") && send(key) }
fields << "last_partner_sync" if last_partner_sync
fields
end
def general_permalink
custom_permalink.presence || unique_permalink
end
def matches_permalink?(permalink)
permalink.present? && (permalink.downcase == unique_permalink.downcase || permalink.downcase == custom_permalink&.downcase)
end
def permalink_overlaps_with_other_sellers?
permalinks = [unique_permalink.presence, custom_permalink.presence].compact
products_by_other_sellers = Link.where.not(user_id:)
products_by_other_sellers.where(unique_permalink: permalinks).or(products_by_other_sellers.where(custom_permalink: permalinks)).present?
end
def add_removed_file_info_attributes(removed_file_info_attributes)
self.json_data ||= {}
if self.json_data["removed_file_info_attributes"]
self.json_data["removed_file_info_attributes"].concat(removed_file_info_attributes)
else
self.json_data["removed_file_info_attributes"] = removed_file_info_attributes
end
end
def removed_file_info_attributes
removed_file_info_attributes = self.json_data.present? ? self.json_data["removed_file_info_attributes"] : []
if removed_file_info_attributes.present?
removed_file_info_attributes.map(&:to_sym)
else
[]
end
end
def save_shipping_destinations!(shipping_destinations)
shipping_destinations ||= []
deduped_destinations = shipping_destinations.uniq { |destination| destination["country_code"] }
if deduped_destinations.size != shipping_destinations.size
errors.add(:base, "Sorry, shipping destinations have to be unique.")
raise LinkInvalid, "Sorry, shipping destinations have to be unique."
end
remaining_shipping_destinations = self.shipping_destinations.alive.pluck(:id)
# Cannot empty out shipping destinations for a published physical product
if alive? && (shipping_destinations.empty? || shipping_destinations.first == "")
errors.add(:base, "The product needs to be shippable to at least one destination.")
raise LinkInvalid, "The product needs to be shippable to at least one destination."
end
shipping_destinations.each do |destination|
next if destination.try(:[], "country_code").blank?
shipping_destination = ShippingDestination.find_or_create_by(country_code: destination["country_code"], link_id: id)
# TODO: :product_edit_react cleanup
one_item_rate_cents = destination["one_item_rate_cents"]
multiple_items_rate_cents = destination["multiple_items_rate_cents"]
one_item_rate_cents ||= string_to_price_cents(price_currency_type, destination["one_item_rate"])
multiple_items_rate_cents ||= string_to_price_cents(price_currency_type, destination["multiple_items_rate"])
begin
shipping_destination.one_item_rate_cents = one_item_rate_cents
shipping_destination.multiple_items_rate_cents = multiple_items_rate_cents
shipping_destination.deleted_at = nil
shipping_destination.is_virtual_country = ShippingDestination::Destinations::VIRTUAL_COUNTRY_CODES.include?(shipping_destination.country_code)
self.shipping_destinations << shipping_destination
# only write to DB if changing attribute
shipping_destination.save! if shipping_destination.changed?
remaining_shipping_destinations.delete(shipping_destination.id)
rescue ActiveRecord::RecordNotUnique => e
errors.add(:base, "Sorry, shipping destinations have to be unique.")
raise e
end
end
record_deactivation_timestamp = Time.current
# Deactivate the remaining shipping destinations that were not echo'ed back
remaining_shipping_destinations.each do |id|
ShippingDestination.find(id).update(deleted_at: record_deactivation_timestamp)
end
end
def save_default_sku!(sku_id, custom_sku)
sku = skus.find_by_external_id(sku_id)
sku.update!(custom_sku:) unless sku.nil?
end
def sku_title
variant_categories_alive.present? ? variant_categories_alive.map(&:title).join(" - ") : "Version"
end
def variant_list(seller = nil)
return { categories: [], skus: [], skus_enabled: } if variant_categories_alive.empty?
variants = { categories:
variant_categories_alive.each_with_index.map do |category, i|
{
id: category.external_id,
i:,
name: category.title,
options:
category.variants.in_order.alive.map do |variant|
variant.as_json(for_views: true, for_seller: seller.present? && (seller == user || seller.is_team_member?))
end
}
end }
if skus_enabled
variants[:skus] = skus.not_is_default_sku.alive.map do |sku|
sku.as_json(for_views: true)
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bolivia_bank_account.rb | app/models/bolivia_bank_account.rb | # frozen_string_literal: true
class BoliviaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BO"
BANK_CODE_FORMAT_REGEX = /^\d{1,3}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{10,15}$/
private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::BOL.alpha2
end
def currency
Currency::BOB
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_integration.rb | app/models/purchase_integration.rb | # frozen_string_literal: true
class PurchaseIntegration < ApplicationRecord
include Deletable
belongs_to :purchase, optional: true
belongs_to :integration, optional: true
validates :purchase_id, presence: true
validates :integration_id, presence: true
validates :integration_id, uniqueness: { scope: %i[purchase_id deleted_at] }, unless: :deleted?
validates :discord_user_id, presence: true, if: -> { integration&.type === DiscordIntegration.name }
validate :matches_integration_on_product
validate :unique_for_integration_type
def unique_for_integration_type
return if purchase.nil? || integration.nil?
return unless purchase.active_integrations.where(type: integration.type).where.not(id: integration.id).exists?
errors.add(:base, "Purchase cannot have multiple integrations of the same type.")
end
def matches_integration_on_product
return if purchase.nil? || integration.nil?
return if purchase.find_enabled_integration(integration.name) === integration
errors.add(:base, "Integration does not match the one available for the associated product.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/invite.rb | app/models/invite.rb | # frozen_string_literal: true
class Invite < ApplicationRecord
belongs_to :user, foreign_key: "sender_id", optional: true
# invite state machine
#
# invitation_sent → → → → signed_up
#
state_machine :invite_state, initial: :invitation_sent do
after_transition invitation_sent: :signed_up, do: :notify_sender_of_registration
event :mark_signed_up do
transition invitation_sent: :signed_up
end
end
validates_presence_of :user, :receiver_email
%w[invitation_sent signed_up].each do |invite_state|
scope invite_state.to_sym, -> { where(invite_state:) }
end
def notify_sender_of_registration
InviteMailer.receiver_signed_up(id).deliver_later(queue: "default")
end
def invite_state_text
case invite_state
when "invitation_sent"
"Invitation sent"
when "signed_up"
"Signed up!"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/circle_integration.rb | app/models/circle_integration.rb | # frozen_string_literal: true
class CircleIntegration < Integration
INTEGRATION_DETAILS = %w[community_id space_group_id]
INTEGRATION_DETAILS.each { |detail| attr_json_data_accessor detail }
validates_presence_of :api_key
def as_json(*)
super.merge(api_key:)
end
def self.is_enabled_for(purchase)
purchase.find_enabled_integration(Integration::CIRCLE).present?
end
def self.connection_settings
super + %w[api_key keep_inactive_members]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/asset_preview.rb | app/models/asset_preview.rb | # frozen_string_literal: true
class AssetPreview < ApplicationRecord
include Deletable
include CdnUrlHelper
SUPPORTED_IMAGE_CONTENT_TYPES = /jpeg|gif|png|jpg/i
DEFAULT_DISPLAY_WIDTH = 670
RETINA_DISPLAY_WIDTH = (DEFAULT_DISPLAY_WIDTH * 1.5).to_i
after_commit :invalidate_product_cache
after_create :reset_moderated_by_iffy_flag
# Update updated_at of product to regenerate the sitemap in RefreshSitemapMonthlyWorker
belongs_to :link, touch: true, optional: true
before_create :generate_guid
before_create :set_position
serialize :oembed, coder: YAML
validate :url_or_file
validate :height_and_width_presence
validate :duration_presence_for_video
validate :max_preview_count, on: :create
validate :oembed_has_width_and_height
validate :oembed_url_presence, on: :create, if: -> { oembed.present? }
validates :link, presence: :true
delegate :content_type, to: :file, allow_nil: true
scope :in_order, -> { order(position: :asc, created_at: :asc) }
has_one_attached :file
def as_json(*)
{ url:,
original_url: url(style: :original),
thumbnail: oembed_thumbnail_url,
id: guid,
type: display_type,
filetype:,
width: display_width,
height: display_height,
native_width: width,
native_height: height }
end
def display_height
width && height && (height.to_i * (display_width.to_i / width.to_f)).to_i
end
def display_width
width && [DEFAULT_DISPLAY_WIDTH, width].min
end
def retina_width
width && [RETINA_DISPLAY_WIDTH, width].min
end
def width
if file.attached?
file.blob.metadata[:width]
else
oembed_width
end
end
def height
if file.attached?
file.blob.metadata[:height]
else
oembed_height
end
end
def oembed_width
oembed && oembed["info"]["width"].to_i
end
def oembed_height
oembed && oembed["info"]["height"].to_i
end
def retina_variant
return unless file.attached?
file.variant(resize_to_limit: [retina_width, nil]).processed
end
def display_type
return "unsplash" if unsplash_url
return "oembed" if oembed
%w[image video].detect { |type| file.public_send(:"#{ type }?") }
end
def filetype
if file.attached?
from_ext = File.extname(file.filename.to_s).sub(".", "")
from_ext = file.content_type.split("/").last if from_ext.blank?
from_ext
else
nil
end
end
def generate_guid
self.guid ||= SecureRandom.hex # For duplicate product, use the original attachment guid to avoid regeneration.
end
def oembed_thumbnail_url
return nil unless oembed
url = oembed["info"]["thumbnail_url"].to_s.strip
return nil unless safe_url?(url)
url
end
def oembed_url
return nil unless oembed
doc = Nokogiri::HTML(oembed["html"])
iframe = doc.css("iframe").first
return nil unless iframe
url = iframe[:src].strip
return nil unless safe_url?(url)
url = "https:#{url}" if url.starts_with?("//")
url += "&enablejsapi=1" if /youtube.*feature=oembed/.match?(url)
url += "?api=1" if %r{vimeo.com/video/\d+\z}.match?(url)
url
end
def image_url?
unsplash_url.present? || (file.attached? && file.image?)
end
def url(style: nil)
return unsplash_url if unsplash_url.present?
return oembed_url if oembed_url.present?
return unless file.attached?
style ||= default_style
cdn_url_for(url_from_file(style:))
end
def url_from_file(style: nil)
return unless file.attached?
style ||= default_style
Rails.cache.fetch("attachment_#{file.id}_#{style}_url") do
if style == :retina
retina_variant.url
else
file.url
end
end
rescue
file.url
end
def default_style
should_post_process? ? :retina : :original
end
def should_post_process?
return false unless file.attached?
file.image? && !file.content_type.include?("gif")
end
def url=(new_url)
new_url = new_url.to_s
new_url = "https:#{new_url}" if new_url.starts_with?("//")
new_url = Addressable::URI.escape(new_url) unless URI::ABS_URI.match?(new_url)
new_uri = URI.parse(new_url)
raise URI::InvalidURIError.new("URL '#{new_url}' is not a web url") unless new_uri.scheme.in?(["http", "https"])
new_url = new_uri.to_s
embeddable = OEmbedFinder.embeddable_from_url(new_url)
if embeddable
self.oembed = embeddable.stringify_keys
file.purge
else
self.oembed = nil
response = SsrfFilter.get(new_url)
tempfile = Tempfile.new(binmode: true)
tempfile.write(response.body)
tempfile.rewind
blob = ActiveStorage::Blob.create_and_upload!(io: tempfile,
filename: File.basename(new_url),
content_type: response.content_type)
self.file.attach(blob.signed_id)
self.file.analyze
end
end
def analyze_file
if file.attached? && !file.analyzed?
file.analyze
end
end
private
def set_position
previous = link.asset_previews.in_order.last
if previous
self.position = previous.position.present? ? previous.position + 1 : link.asset_previews.in_order.count
else
self.position = 0
end
end
def url_or_file
return if deleted?
errors.add(:base, "Could not process your preview, please try again.") unless valid_file_type?
end
def max_preview_count
return if deleted?
errors.add(:base, "Sorry, we have a limit of #{Link::MAX_PREVIEW_COUNT} previews. Please delete an existing one before adding another.") if link.asset_previews.alive.count >= Link::MAX_PREVIEW_COUNT
end
def valid_file_type?
return true unless file.attached?
return true if file.video?
file.image? && content_type.match?(SUPPORTED_IMAGE_CONTENT_TYPES)
end
def height_and_width_presence
return unless file.attached? && file.analyzed?
if (file.image? || file.video?) && !(file.blob.metadata&.dig(:height) && file.blob.metadata&.dig(:width))
errors.add(:base, "Could not analyze cover. Please check the uploaded file.")
end
end
def oembed_has_width_and_height
return if file.attached? || unsplash_url.present?
unless oembed&.dig("info", "width") && oembed&.dig("info", "height")
errors.add(:base, "Could not analyze cover. Please check the uploaded file.")
end
end
def oembed_url_presence
errors.add(:base, "A URL from an unsupported platform was provided. Please try again.") if oembed_url.blank?
end
def duration_presence_for_video
return unless file.attached? && file.analyzed?
errors.add(:base, "Could not analyze cover. Please check the uploaded file.") if file.video? && !file.blob.metadata&.dig(:duration)
end
def invalidate_product_cache
link.invalidate_cache if link.present?
end
def reset_moderated_by_iffy_flag
link&.update_attribute(:moderated_by_iffy, false)
end
def safe_url?(url)
return false if url.blank?
return false if url.match?(/\A\s*(?:javascript|data|vbscript|file):/i)
true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_profile_section.rb | app/models/seller_profile_section.rb | # frozen_string_literal: true
class SellerProfileSection < ApplicationRecord
include ExternalId, FlagShihTzu
belongs_to :seller, class_name: "User"
belongs_to :product, class_name: "Link", optional: true
validate :validate_json_data
attribute :json_data, default: {}
scope :on_profile, -> { where(product_id: nil) }
has_flags 1 => :DEPRECATED_add_new_products,
2 => :hide_header,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
private
def self.inherited(subclass)
subclass.define_singleton_method :json_schema do
@__json_schema ||= JSON.parse(File.read(Rails.root.join("lib", "json_schemas", "#{subclass.name.underscore}.json").to_s))
end
subclass.json_schema["properties"].keys.each do |key|
subclass.define_method key do
json_data[key]
end
subclass.define_method :"#{key}=" do |value|
json_data[key] = value
end
end
super
end
def validate_json_data
# slice away the "in schema [id]" part that JSON::Validator otherwise includes
json_validator.validate(json_data).each { errors.add(:base, _1[..-48]) }
end
def json_validator
@__json_validator ||= JSON::Validator.new(self.class.json_schema, insert_defaults: true, record_errors: true)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/guyana_bank_account.rb | app/models/guyana_bank_account.rb | # frozen_string_literal: true
class GuyanaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "GY"
BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9a-zA-Z]{1,32}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::GUY.alpha2
end
def currency
Currency::GYD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/preorder.rb | app/models/preorder.rb | # frozen_string_literal: true
class Preorder < ApplicationRecord
include ExternalId
include AfterCommitEverywhere
belongs_to :preorder_link, optional: true
belongs_to :seller, class_name: "User", optional: true
belongs_to :purchaser, class_name: "User", optional: true
has_many :purchases
has_one :url_redirect
has_one :credit_card
validates :preorder_link, presence: true
validates :seller, presence: true
# Preorder state transitions:
#
# → charge_successful
# ↑
# in_progress → authorization_successful
# ↓ ↓
# authorization_failed → cancelled
#
state_machine(:state, initial: :in_progress) do
before_transition in_progress: :authorization_successful, do: :authorization_purchase_successful?
before_transition authorization_successful: :charge_successful, do: :charge_purchase_successful?
after_transition in_progress: :authorization_successful, do: :associate_credit_card_to_preorder
after_transition in_progress: %i[test_authorization_successful authorization_successful], do: :send_preorder_notifications
after_transition authorization_successful: :charge_successful, do: :mark_authorization_purchase_as_concluded_successfully
after_transition authorization_successful: :cancelled, do: :mark_authorization_purchase_as_concluded_unsuccessfully
after_transition authorization_successful: :cancelled, do: :send_cancellation_emails
after_transition any => any, :do => :log_transition
event :mark_authorization_failed do
transition in_progress: :authorization_failed
end
event :mark_authorization_successful do
transition in_progress: :authorization_successful
end
event :mark_test_authorization_successful do
transition in_progress: :test_authorization_successful
end
event :mark_charge_successful do
transition authorization_successful: :charge_successful
end
event :mark_cancelled do
transition authorization_successful: :cancelled
end
end
scope :in_progress, -> { where(state: "in_progress") }
scope :authorization_successful, -> { where(state: "authorization_successful") }
scope :authorization_failed, -> { where(state: "authorization_failed") }
scope :charge_successful, -> { where(state: "charge_successful") }
scope :authorization_successful_or_charge_successful, -> { where("preorders.state = 'authorization_successful' or preorders.state = 'charge_successful'") }
delegate :link, to: :preorder_link
def is_authorization_successful?
state == "authorization_successful"
end
def is_cancelled?
state == "cancelled"
end
def authorization_purchase
# The preorder's first purchase is always the credit card authorization (customer creation)
purchases.first
end
def authorize!
authorization_purchase.process!
purchase_errors = authorization_purchase.errors
if is_test_preorder?
authorization_purchase.mark_test_preorder_successful!
elsif purchase_errors&.any?
errors.add(:base, purchase_errors.full_messages[0])
elsif authorization_purchase.setup_intent&.requires_action?
# Leave in `in_progress` state until the UI action is completed
else
authorization_purchase.mark_preorder_authorization_successful!
end
# Don't keep the preorder's association with an invalid object because its state transition will fail
self.purchases = [] unless authorization_purchase.persisted?
end
# Public: Charges the credit card associated with the preorder.
#
# NOTE: The caller is responsible for setting the state of the preorder.
#
# ip_address - The ip address of the buyer assuming this is not an automatic charge (update card scenario).
# browser_guid - The guid of the buyer assuming this is not an automatic charge (update card scenario).
# purchase_params - Purchase params to use with the purchase created when doing the charge. Items in this may be
# overwritten by the preorder logic.
#
# Returns the purchase object representing the charge, or nil if this preorder is not in a chargeable state.
def charge!(ip_address: nil, browser_guid: nil, purchase_params: {})
return nil if link.is_in_preorder_state || !is_authorization_successful?
return nil if purchases.in_progress_or_successful_including_test.any?
purchase_params.merge!(email: authorization_purchase.email,
price_range: authorization_purchase.displayed_price_cents / (preorder_link.link.single_unit_currency? ? 1 : 100.0),
perceived_price_cents: authorization_purchase.displayed_price_cents,
browser_guid: browser_guid || authorization_purchase.browser_guid,
ip_address: ip_address || authorization_purchase.ip_address,
ip_country: ip_address.present? ? GeoIp.lookup(ip_address).try(:country_name) : authorization_purchase.ip_country,
ip_state: ip_address.present? ? GeoIp.lookup(ip_address).try(:region_name) : authorization_purchase.ip_state,
referrer: authorization_purchase.referrer,
full_name: authorization_purchase.full_name,
street_address: authorization_purchase.street_address,
country: authorization_purchase.country,
state: authorization_purchase.state,
zip_code: authorization_purchase.zip_code,
city: authorization_purchase.city,
quantity: authorization_purchase.quantity,
was_product_recommended: authorization_purchase.was_product_recommended)
purchase = Purchase.new(purchase_params)
purchase.preorder = self
purchase.credit_card = credit_card
purchase.offer_code = authorization_purchase.offer_code
purchase.variant_attributes = authorization_purchase.variant_attributes
purchase.purchaser = purchaser
purchase.link = link
purchase.seller = seller
purchase.credit_card_zipcode = authorization_purchase.credit_card_zipcode
purchase.affiliate = authorization_purchase.affiliate if authorization_purchase.affiliate.try(:alive?)
authorization_purchase.purchase_custom_fields.each { purchase.purchase_custom_fields << _1.dup }
if authorization_purchase.purchase_sales_tax_info
purchase.business_vat_id = authorization_purchase.purchase_sales_tax_info.business_vat_id
elected_country_code = authorization_purchase.purchase_sales_tax_info.elected_country_code
purchase.sales_tax_country_code_election = elected_country_code if elected_country_code
end
purchase.ensure_completion do
purchase.process!
if purchase.errors.present?
begin
purchase.mark_failed!
rescue StateMachines::InvalidTransition => e
logger.error "Purchase for preorder error: Could not create purchase for preorder ID #{id} because #{e}"
end
else
purchase.update_balance_and_mark_successful!
after_commit do
ActivateIntegrationsWorker.perform_async(purchase.id)
end
end
end
# it is important that we link RecommendedPurchaseInfo with the charge purchase, successful or not, for metrics
if purchase.was_product_recommended
rec_purchase_info = authorization_purchase.recommended_purchase_info
rec_purchase_info.purchase = purchase
rec_purchase_info.save
end
purchases << purchase
purchase
end
def is_test_preorder?
seller == purchaser
end
def mobile_json_data
if charge_purchase_successful?
preorder_charge_purchase = purchases.last
return preorder_charge_purchase.url_redirect.product_json_data
end
result = link.as_json(mobile: true)
preorder_data = { external_id:, release_at: preorder_link.release_at }
result[:preorder_data] = preorder_data
if authorization_purchase
result[:purchase_id] = authorization_purchase.external_id
result[:purchased_at] = authorization_purchase.created_at
result[:user_id] = authorization_purchase.purchaser.external_id if authorization_purchase.purchaser
result[:product_updates_data] = authorization_purchase.update_json_data_for_mobile
result[:is_archived] = authorization_purchase.is_archived
end
result
end
private
def mark_authorization_purchase_as_concluded_successfully
authorization_purchase.mark_preorder_concluded_successfully
end
def mark_authorization_purchase_as_concluded_unsuccessfully
authorization_purchase.mark_preorder_concluded_unsuccessfully
end
def send_preorder_notifications
CustomerMailer.preorder_receipt(id).deliver_later(queue: "critical", wait: 3.seconds)
return unless seller.enable_payment_email?
ContactingCreatorMailer.notify(authorization_purchase.id, true).deliver_later(queue: "critical", wait: 3.seconds)
end
def associate_credit_card_to_preorder
self.credit_card = authorization_purchase.credit_card
end
def log_transition
logger.info "Preorder: preorder ID #{id} transitioned to #{state}"
end
def authorization_purchase_successful?
authorization_purchase.purchase_state == if is_test_preorder?
"test_preorder_successful"
else
"preorder_authorization_successful"
end
end
def charge_purchase_successful?
purchases.last.purchase_state == "successful"
end
def send_cancellation_emails(transition)
params = transition.args.first
return if params && params[:auto_cancelled]
CustomerLowPriorityMailer.preorder_cancelled(id).deliver_later(queue: "low")
ContactingCreatorMailer.preorder_cancelled(id).deliver_later(queue: "critical")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/discord_integration.rb | app/models/discord_integration.rb | # frozen_string_literal: true
class DiscordIntegration < Integration
INTEGRATION_DETAILS = %w[username server_id server_name]
INTEGRATION_DETAILS.each { |detail| attr_json_data_accessor detail }
def self.discord_user_id_for(purchase)
integration = purchase.find_enabled_integration(Integration::DISCORD)
return nil unless integration.present?
purchase.live_purchase_integrations.find_by(integration:).try(:discord_user_id)
end
def self.is_enabled_for(purchase)
purchase.find_enabled_integration(Integration::DISCORD).present?
end
def disconnect!
response = DiscordApi.new.disconnect(server_id)
response.code == 204
rescue Discordrb::Errors::UnknownServer => e
Rails.logger.info("DiscordIntegration: Attempting to disconnect from a deleted Discord server. Proceeding as a successful disconnection. DiscordIntegration ID #{self.id}. Error: #{e.class} => #{e.message}")
true
rescue Discordrb::Errors::CodeError
false
end
def same_connection?(integration)
integration.type == type && integration.try(:server_id) == server_id
end
def self.connection_settings
super + %w[keep_inactive_members]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/comment.rb | app/models/comment.rb | # frozen_string_literal: true
class Comment < ApplicationRecord
include ExternalId
include Deletable
include JsonData
COMMENT_TYPE_NOTE = "note"
COMMENT_TYPE_USER_SUBMITTED = "user_submitted"
COMMENT_TYPE_PAYOUT_NOTE = "payout_note"
COMMENT_TYPE_COMPLIANT = "compliant"
COMMENT_TYPE_ON_PROBATION = "on"
COMMENT_TYPE_FLAGGED = "flagged"
COMMENT_TYPE_FLAG_NOTE = "flag_note"
COMMENT_TYPE_SUSPENDED = "suspended"
COMMENT_TYPE_SUSPENSION_NOTE = "suspension_note"
COMMENT_TYPE_BALANCE_FORFEITED = "balance_forfeited"
COMMENT_TYPE_COUNTRY_CHANGED = "country_changed"
COMMENT_TYPE_PAYOUTS_PAUSED = "payouts_paused"
COMMENT_TYPE_PAYOUTS_RESUMED = "payouts_resumed"
RISK_STATE_COMMENT_TYPES = [COMMENT_TYPE_COMPLIANT, COMMENT_TYPE_ON_PROBATION, COMMENT_TYPE_FLAGGED, COMMENT_TYPE_SUSPENDED]
MAX_ALLOWED_DEPTH = 4 # Depth of a root comment starts with 0.
attr_json_data_accessor :was_alive_before_marking_subtree_deleted
has_ancestry cache_depth: true
has_paper_trail
belongs_to :commentable, polymorphic: true, optional: true
belongs_to :author, class_name: "User", optional: true
belongs_to :purchase, optional: true
validates_presence_of :commentable_id, :commentable_type, :comment_type, :content
validates :content, length: { maximum: 10_000 }
validates :depth, numericality: { only_integer: true, less_than_or_equal_to: MAX_ALLOWED_DEPTH }, on: :create
validate :commentable_object_exists, on: :create
validate :content_cannot_contain_adult_keywords, if: :content_changed?
validate :author_name_or_author_id_is_present
before_save :trim_extra_newlines, if: :content_changed?
after_commit :notify_seller_of_new_comment, on: :create
scope :with_type_note, -> { where(comment_type: COMMENT_TYPE_NOTE) }
scope :with_type_payout_note, -> { where(comment_type: COMMENT_TYPE_PAYOUT_NOTE) }
scope :with_type_on_probation, -> { where(comment_type: COMMENT_TYPE_ON_PROBATION) }
scope :with_type_payouts_paused, -> { where(comment_type: COMMENT_TYPE_PAYOUTS_PAUSED) }
scope :with_type_payouts_resumed, -> { where(comment_type: COMMENT_TYPE_PAYOUTS_RESUMED) }
scope :with_type_flagged, -> { where(comment_type: COMMENT_TYPE_FLAGGED) }
def mark_subtree_deleted!
transaction do
subtree.alive.each do |comment|
comment.was_alive_before_marking_subtree_deleted = true if comment.id != id
comment.mark_deleted!
end
end
end
def mark_subtree_undeleted!
transaction do
subtree.deleted.each do |comment|
comment.json_data.delete("was_alive_before_marking_subtree_deleted")
comment.mark_undeleted!
end
end
end
private
def commentable_object_exists
obj_exists = case commentable_type
when "Installment" then Installment.exists?(commentable_id)
when "Link" then Link.exists?(commentable_id)
when "Purchase" then Purchase.exists?(commentable_id)
when "User" then User.exists?(commentable_id)
else false
end
errors.add :base, "object to annotate does not exist" unless obj_exists
end
def author_name_or_author_id_is_present
errors.add :base, "author_name or author_id must be present" if author_name.blank? && author_id.blank?
end
def content_cannot_contain_adult_keywords
return if author&.is_team_member?
return if !author && author_name == "iffy"
errors.add(:base, "Adult keywords are not allowed") if AdultKeywordDetector.adult?(content)
end
def trim_extra_newlines
self.content = content.strip.gsub(/(\R){3,}/, '\1\1')
end
def notify_seller_of_new_comment
return unless user_submitted?
return unless root?
return if authored_by_seller?
return if commentable.seller.disable_comments_email?
CommentMailer.notify_seller_of_new_comment(id).deliver_later
end
def user_submitted?
comment_type == COMMENT_TYPE_USER_SUBMITTED
end
def authored_by_seller?
commentable.respond_to?(:seller_id) && commentable.seller_id == author_id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/base_variant_integration.rb | app/models/base_variant_integration.rb | # frozen_string_literal: true
class BaseVariantIntegration < ApplicationRecord
include Deletable
belongs_to :base_variant, optional: true
belongs_to :integration, optional: true
validates_presence_of :base_variant_id, :integration_id
validates_uniqueness_of :integration_id, scope: %i[base_variant_id deleted_at], unless: :deleted?
validate :variants_with_same_integration_are_from_a_single_product
private
def variants_with_same_integration_are_from_a_single_product
return unless BaseVariantIntegration.exists?(integration:)
BaseVariantIntegration.where(integration:).each do |base_variant_integration|
errors.add(:base, "Integration has already been taken by a variant from a different product.") if base_variant_integration.base_variant.link.id != base_variant.link.id
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/ach_account.rb | app/models/ach_account.rb | # frozen_string_literal: true
class AchAccount < BankAccount
include AchAccount::AccountType
BANK_ACCOUNT_TYPE = "ACH"
before_validation :set_default_account_type, on: :create, if: ->(ach_account) { ach_account.account_type.nil? }
validate :validate_bank_name
validate :validate_routing_number
validate :validate_account_number
validates :account_type, inclusion: { in: AccountType.all }
def routing_number=(routing_number)
self.bank_number = routing_number
end
def bank_name
bank = Bank.find_by(routing_number: bank_number)
return bank.name if bank.present?
super
end
# Public: Format account type for ACH providers.
# Returns single character representing account type
def account_type_for_csv
account_type ? account_type[0] : "c"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
private
def validate_bank_name
return unless bank_name.present? && ["GREEN DOT BANK", "METABANK MEMPHIS"].include?(bank_name)
errors.add :base, "Sorry, we don't support that bank account provider."
end
def validate_routing_number
errors.add :base, "The routing number is invalid." unless self.class.routing_number_valid?(routing_number)
end
def validate_account_number
return unless account_number_changed? && !self.class.account_number_valid?(account_number.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")))
errors.add :base, "The account number is invalid."
end
def set_default_account_type
self.account_type = AchAccount::AccountType::CHECKING
end
def self.routing_number_valid?(routing_number)
/^\d{9}$/.match(routing_number).present? && routing_number_check_digit_valid?(routing_number)
end
def self.routing_number_check_digit_valid?(routing_number)
# Ref: https://en.wikipedia.org/wiki/Routing_transit_number#Check_digit
check_digit =
(
7 * (routing_number[0].to_i + routing_number[3].to_i + routing_number[6].to_i) +
3 * (routing_number[1].to_i + routing_number[4].to_i + routing_number[7].to_i) +
9 * (routing_number[2].to_i + routing_number[5].to_i)
) % 10
check_digit == routing_number[8].to_i
end
def self.account_number_valid?(account_number)
/^\d{1,17}$/.match(account_number).present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/new_zealand_bank_account.rb | app/models/new_zealand_bank_account.rb | # frozen_string_literal: true
class NewZealandBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "NZ"
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{15,16}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
validate :validate_account_number
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::NZL.alpha2
end
def currency
Currency::NZD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/dropbox_file.rb | app/models/dropbox_file.rb | # frozen_string_literal: true
class DropboxFile < ApplicationRecord
include ExternalId
# A Dropbox file always belongs to a user. This is done because without it we could not fetch the dropbox files
# for the user when they visit an upload page.
belongs_to :user, optional: true
# A Dropbox file can belong to a product file if it was successfully transferred to s3 and submitted by the user in a
# product edit/product creation page. We need this to prevent rendering of dropbox files that have already been
# turned into product files on upload pages.
belongs_to :product_file, optional: true
# A Dropbox file can belong to a link if it was added to a product in product edit or was associated on product
# creation. We do this to prevent rendering of dropbox files on the product creation page that were added on the edit page.
# Dropbox files added to the edit page of a product should only appear for that product.
belongs_to :link, optional: true
include JsonData
after_commit :schedule_dropbox_file_analyze, on: :create
validates_presence_of :dropbox_url
scope :available, -> { where(deleted_at: nil, link_id: nil, product_file_id: nil) }
scope :available_for_product, -> { where(deleted_at: nil, product_file_id: nil) }
# Normal dropbox file transitions:
#
# in_progress → successfully_uploaded
#
# → cancelled (by user in ui)
#
# → failed (could never finish transfer)
#
# → deleted (by user in ui)
#
state_machine :state, initial: :in_progress do
after_transition any => %i[cancelled failed deleted], do: :update_deleted_at!
event :mark_successfully_uploaded do
transition in_progress: :successfully_uploaded
end
event :mark_cancelled do
transition in_progress: :cancelled
end
event :mark_failed do
transition in_progress: :failed
end
event :mark_deleted do
transition successfully_uploaded: :deleted
end
end
def deleted?
!in_progress? || deleted_at.present?
end
def update_deleted_at!
update!(deleted_at: Time.current)
end
def self.create_with_file_info(raw_file_info)
dropbox_file = DropboxFile.new
dropbox_file.dropbox_url = raw_file_info[:link]
# Dropbox direct file links expire after 4 hours. Dropbox does not provide a timestamp for the expiration so
# we are creating one here.
dropbox_file.expires_at = 4.hours.from_now
file_info = clean_file_info(raw_file_info)
dropbox_file.json_data = file_info
dropbox_file.save!
dropbox_file
end
def schedule_dropbox_file_analyze
TransferDropboxFileToS3Worker.perform_in(5.seconds, id)
end
def transfer_to_s3
return if cancelled? || deleted? || failed?
mark_failed! if Time.current > expires_at
extension = File.extname(dropbox_url).delete(".")
set_json_data_for_attr("filetype", extension)
FILE_REGEX.each do |file_type, regex|
if extension.match(regex)
set_json_data_for_attr("filegroup", file_type.split("_")[-1])
break
end
end
s3_guid = "db" + (SecureRandom.uuid.split("")[1..-1] - ["-"]).join
filename = json_data_for_attr("file_name")
multipart_transfer_to_s3(filename, s3_guid)
self
end
def multipart_transfer_to_s3(filename, s3_guid)
extname = File.extname(dropbox_url)
tempfile = Tempfile.new([s3_guid, extname], binmode: true)
HTTParty.get(dropbox_url, stream_body: true, follow_redirects: true) do |fragment|
tempfile.write(fragment)
end
tempfile.close
destination_key = "attachments/#{s3_guid}/original/#{filename}"
Aws::S3::Resource.new.bucket(S3_BUCKET).object(destination_key).upload_file(tempfile.path,
content_type: fetch_content_type)
self.s3_url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{destination_key}"
mark_successfully_uploaded!
end
def self.clean_file_info(raw_file_info)
cleaned_file_info = {}
cleaned_file_info[:file_name] = raw_file_info[:name]
cleaned_file_info[:file_size] = raw_file_info[:bytes].to_i
cleaned_file_info
end
def as_json(_options = {})
{
dropbox_url:,
external_id:,
s3_url:,
user_id: user.try(:external_id),
product_file_id: product_file.try(:external_id),
link_id: link.try(:external_id),
expires_at:,
name: json_data_for_attr("file_name"),
bytes: json_data_for_attr("file_size"),
state:
}
end
private
def fetch_content_type
MIME::Types.type_for(dropbox_url).first.to_s.presence
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/consumption_event.rb | app/models/consumption_event.rb | # frozen_string_literal: true
class ConsumptionEvent < ApplicationRecord
class << self
def create_event!(**kwargs)
ConsumptionEvent.create!(
event_type: kwargs.fetch(:event_type),
platform: kwargs.fetch(:platform),
url_redirect_id: kwargs.fetch(:url_redirect_id),
product_file_id: kwargs.fetch(:product_file_id, nil),
purchase_id: kwargs.fetch(:purchase_id, nil),
link_id: kwargs.fetch(:product_id, nil),
folder_id: kwargs.fetch(:folder_id, nil),
consumed_at: kwargs.fetch(:consumed_at, Time.current),
ip_address: kwargs.fetch(:ip_address)
)
end
def determine_platform(user_agent)
return Platform::OTHER if user_agent.blank?
return Platform::ANDROID if /android/i.match?(user_agent)
return Platform::IPHONE if /iosbuyer/i.match?(user_agent)
Platform::OTHER
end
end
include Platform
include TimestampScopes
include JsonData
EVENT_TYPES = %w[download download_all folder_download listen read view watch]
EVENT_TYPES.each do |event_type|
self.const_set("EVENT_TYPE_#{event_type.upcase}", event_type)
end
belongs_to :purchase, optional: true
attr_json_data_accessor :folder_id
attr_json_data_accessor :ip_address
validates_presence_of :folder_id, if: -> { event_type == EVENT_TYPE_FOLDER_DOWNLOAD }
validates_presence_of :url_redirect_id
validates :event_type, inclusion: { in: EVENT_TYPES }
validates :platform, inclusion: { in: Platform.all }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/upsell.rb | app/models/upsell.rb | # frozen_string_literal: true
class Upsell < ApplicationRecord
include Deletable, ExternalId, FlagShihTzu, Upsell::Sorting
has_paper_trail
has_flags 1 => :replace_selected_products,
2 => :is_content_upsell,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
belongs_to :seller, class_name: "User"
# For a cross-sell, this is the product that will be added to the cart if the buyer accepts the offer.
# For an upsell, this is the product on which the buyer is offered a version change.
belongs_to :product, class_name: "Link"
belongs_to :variant, class_name: "BaseVariant", optional: true
belongs_to :offer_code, optional: true, autosave: true
has_many :upsell_variants, autosave: true
has_many :upsell_purchases
has_many :purchases, through: :upsell_purchases
has_many :purchases_that_count_towards_volume, -> { counts_towards_volume }, through: :upsell_purchases, source: :purchase
has_and_belongs_to_many :selected_products, class_name: "Link", join_table: "upsells_selected_products", association_foreign_key: "selected_product_id"
validates_presence_of :seller, :product
validates_presence_of :name, unless: :is_content_upsell?
validate :selected_products_belong_to_seller
validate :product_belongs_to_seller
validate :variant_belongs_to_product
validate :offer_code_belongs_to_seller_and_product
validate :has_one_upsell_variant_per_selected_variant
validate :has_one_upsell_per_product
validate :product_is_not_call
scope :upsell, -> { where(cross_sell: false) }
scope :cross_sell, -> { where(cross_sell: true) }
scope :available_to_customers, -> { alive.where(paused: false) }
def as_json(options = {})
{
id: external_id,
name:,
cross_sell:,
replace_selected_products:,
universal:,
text:,
description:,
paused:,
product: {
id: product.external_id,
name: product.name,
currency_type: product.price_currency_type.downcase || "usd",
variant: variant.present? ? {
id: variant.external_id,
name: variant.name
} : nil,
},
discount: offer_code&.discount,
selected_products: selected_products.map do |product|
{
id: product.external_id,
name: product.name,
}
end,
upsell_variants: upsell_variants.alive.map do |upsell_variant|
{
id: upsell_variant.external_id,
selected_variant: {
id: upsell_variant.selected_variant.external_id,
name: upsell_variant.selected_variant.name
},
offered_variant: {
id: upsell_variant.offered_variant.external_id,
name: upsell_variant.offered_variant.name
},
}
end,
}
end
private
def selected_products_belong_to_seller
if selected_products.any? { _1.user != seller }
errors.add(:base, "All offered products must belong to the current seller.")
end
end
def product_belongs_to_seller
if product.user != seller
errors.add(:base, "The offered product must belong to the current seller.")
end
end
def variant_belongs_to_product
if variant.present? && variant.link != product
errors.add(:base, "The offered variant must belong to the offered product.")
end
end
def offer_code_belongs_to_seller_and_product
if offer_code.present? && (offer_code.user != seller || offer_code.products.exclude?(product))
errors.add(:base, "The offer code must belong to the seller and the offered product.")
end
end
def has_one_upsell_variant_per_selected_variant
if upsell_variants.group(:selected_variant_id).count.values.any? { |count| count > 1 }
errors.add(:base, "The upsell cannot have more than one upsell variant per selected variant.")
end
end
def has_one_upsell_per_product
if !cross_sell? && deleted_at.blank? && seller.upsells.upsell.alive.where(product:).where.not(id:).any?
errors.add(:base, "You can only create one upsell per product.")
end
end
def product_is_not_call
if product.native_type == Link::NATIVE_TYPE_CALL
errors.add(:base, "Calls cannot be offered as upsells.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/poland_bank_account.rb | app/models/poland_bank_account.rb | # frozen_string_literal: true
class PolandBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "PL"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::POL.alpha2
end
def currency
Currency::PLN
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/user_tax_form.rb | app/models/user_tax_form.rb | # frozen_string_literal: true
class UserTaxForm < ApplicationRecord
include JsonData
TAX_FORM_TYPES = ["us_1099_k", "us_1099_misc"].freeze
MIN_TAX_YEAR = 2020
belongs_to :user
attr_json_data_accessor :stripe_account_id
validates :tax_year, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: MIN_TAX_YEAR }
validates :tax_form_type, presence: true, inclusion: { in: TAX_FORM_TYPES }
validates :user_id, uniqueness: { scope: [:tax_year, :tax_form_type] }
scope :for_year, ->(year) { where(tax_year: year) }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/staff_picked_product.rb | app/models/staff_picked_product.rb | # frozen_string_literal: true
class StaffPickedProduct < ApplicationRecord
include TimestampStateFields
has_paper_trail
belongs_to :product, class_name: "Link"
validates :product, presence: true, uniqueness: true
timestamp_state_fields :deleted
after_commit :update_product_search_index
private
def update_product_search_index
product.enqueue_index_update_for(["staff_picked_at"])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/senegal_bank_account.rb | app/models/senegal_bank_account.rb | # frozen_string_literal: true
class SenegalBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "SN"
ACCOUNT_NUMBER_FORMAT_REGEX = /^SN([0-9SN]){20,26}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
validate :validate_account_number
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::SEN.alpha2
end
def currency
Currency::XOF
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/vietnam_bank_account.rb | app/models/vietnam_bank_account.rb | # frozen_string_literal: true
class VietnamBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "VN"
BANK_CODE_FORMAT_REGEX = /\A[0-9]{8}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{1,17}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::VNM.alpha2
end
def currency
Currency::VND
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sales_export_chunk.rb | app/models/sales_export_chunk.rb | # frozen_string_literal: true
class SalesExportChunk < ApplicationRecord
belongs_to :export, class_name: "SalesExport"
serialize :purchase_ids, type: Array, coder: YAML
serialize :custom_fields, type: Array, coder: YAML
serialize :purchases_data, type: Array, coder: YAML
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/resource_subscription.rb | app/models/resource_subscription.rb | # frozen_string_literal: true
class ResourceSubscription < ApplicationRecord
include ExternalId
include Deletable
SALE_RESOURCE_NAME = "sale"
CANCELLED_RESOURCE_NAME = "cancellation"
SUBSCRIPTION_ENDED_RESOURCE_NAME = "subscription_ended"
SUBSCRIPTION_RESTARTED_RESOURCE_NAME = "subscription_restarted"
SUBSCRIPTION_UPDATED_RESOURCE_NAME = "subscription_updated"
REFUNDED_RESOURCE_NAME = "refund"
DISPUTE_RESOURCE_NAME = "dispute"
DISPUTE_WON_RESOURCE_NAME = "dispute_won"
VALID_RESOURCE_NAMES = [SALE_RESOURCE_NAME,
CANCELLED_RESOURCE_NAME,
SUBSCRIPTION_ENDED_RESOURCE_NAME,
SUBSCRIPTION_RESTARTED_RESOURCE_NAME,
SUBSCRIPTION_UPDATED_RESOURCE_NAME,
REFUNDED_RESOURCE_NAME,
DISPUTE_RESOURCE_NAME,
DISPUTE_WON_RESOURCE_NAME].freeze
INVALID_POST_URL_HOSTS = %w(127.0.0.1 localhost 0.0.0.0)
belongs_to :user, optional: true
belongs_to :oauth_application, optional: true
validates_presence_of :user, :oauth_application, :resource_name
before_create :assign_content_type_to_json_for_zapier
def as_json(_options = {})
{
"id" => external_id,
"resource_name" => resource_name,
"post_url" => post_url
}
end
def self.valid_resource_name?(resource_name)
VALID_RESOURCE_NAMES.include?(resource_name)
end
def self.valid_post_url?(post_url)
uri = URI.parse(post_url)
uri.kind_of?(URI::HTTP) && INVALID_POST_URL_HOSTS.exclude?(uri.host)
rescue URI::InvalidURIError
false
end
private
def assign_content_type_to_json_for_zapier
self.content_type = Mime[:json] if URI.parse(post_url).host.ends_with?("zapier.com")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_profile_subscribe_section.rb | app/models/seller_profile_subscribe_section.rb | # frozen_string_literal: true
class SellerProfileSubscribeSection < SellerProfileSection
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/signup_event.rb | app/models/signup_event.rb | # frozen_string_literal: true
class SignupEvent < Event
belongs_to :user, optional: true
self.table_name = "signup_events"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/upsell_purchase.rb | app/models/upsell_purchase.rb | # frozen_string_literal: true
class UpsellPurchase < ApplicationRecord
belongs_to :purchase
belongs_to :upsell
belongs_to :selected_product, class_name: "Link", optional: true
belongs_to :upsell_variant, optional: true
validates :purchase, presence: true, uniqueness: true
validates_presence_of :upsell
validate :upsell_must_belong_to_purchase_product
validate :must_have_upsell_variant_for_upsell
def as_json
{
name: upsell.name,
discount: purchase.original_offer_code&.displayed_amount_off(purchase.link.price_currency_type, with_symbol: true),
selected_product: selected_product&.name,
selected_version: upsell_variant&.selected_variant&.name,
}
end
private
def upsell_must_belong_to_purchase_product
if purchase.link != upsell.product
errors.add(:base, "The upsell must belong to the product being purchased.")
end
end
def must_have_upsell_variant_for_upsell
if !upsell.cross_sell? && upsell_variant.blank?
errors.add(:base, "The upsell purchase must have an associated upsell variant.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/confirmed_follower_event.rb | app/models/confirmed_follower_event.rb | # frozen_string_literal: true
class ConfirmedFollowerEvent
include Elasticsearch::Model
index_name "confirmed_follower_events"
settings(
number_of_shards: 1,
number_of_replicas: 0,
sort: { field: :timestamp, order: :asc }
)
mapping dynamic: :strict do
indexes :name, type: :keyword
indexes :timestamp, type: :date
indexes :follower_id, type: :long
indexes :followed_user_id, type: :long
indexes :follower_user_id, type: :long
indexes :email, type: :keyword
end
module Events
ADDED = "added"
REMOVED = "removed"
ADDED_AND_REMOVED = [ADDED, REMOVED]
end
module FollowerCallbacks
extend ActiveSupport::Concern
include ConfirmedFollowerEvent::Events
included do
after_commit :create_confirmed_follower_event
end
def create_confirmed_follower_event
# This method only handles the change of confirmation state
return unless confirmed_at_previous_change&.any?(&:nil?)
job_params = {
class_name: "ConfirmedFollowerEvent",
id: SecureRandom.uuid,
body: {
follower_id: id,
followed_user_id: followed_id,
follower_user_id:,
email:
}
}
if confirmed_at_previously_was.blank?
job_params[:body].merge!(name: ADDED, timestamp: confirmed_at.iso8601)
else
job_params[:body].merge!(name: REMOVED, timestamp: deleted_at.iso8601)
end
ElasticsearchIndexerWorker.perform_async("index", job_params.deep_stringify_keys)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/gumroad_daily_analytic.rb | app/models/gumroad_daily_analytic.rb | # frozen_string_literal: true
class GumroadDailyAnalytic < ApplicationRecord
validates :period_ended_at, :gumroad_price_cents, :gumroad_fee_cents, :creators_with_sales, :gumroad_discover_price_cents, presence: true
def self.import(date)
date_range = date.all_day
analytic = GumroadDailyAnalytic.find_or_initialize_by(period_ended_at: date_range.last)
analytic.gumroad_price_cents = GumroadDailyAnalyticsCompiler.compile_gumroad_price_cents(between: date_range)
analytic.gumroad_fee_cents = GumroadDailyAnalyticsCompiler.compile_gumroad_fee_cents(between: date_range)
analytic.creators_with_sales = GumroadDailyAnalyticsCompiler.compile_creators_with_sales(between: date_range)
analytic.gumroad_discover_price_cents = GumroadDailyAnalyticsCompiler.compile_gumroad_discover_price_cents(between: date_range)
analytic.save!
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/tunisia_bank_account.rb | app/models/tunisia_bank_account.rb | # frozen_string_literal: true
class TunisiaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "TN"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::TUN.alpha2
end
def currency
Currency::TND
end
def account_number_visual
"#{country}******#{account_number_last_four}"
end
def to_hash
{
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/google_calendar_integration.rb | app/models/google_calendar_integration.rb | # frozen_string_literal: true
class GoogleCalendarIntegration < Integration
INTEGRATION_DETAILS = %w[access_token refresh_token calendar_id calendar_summary email]
INTEGRATION_DETAILS.each { |detail| attr_json_data_accessor detail }
def self.is_enabled_for(purchase)
purchase.find_enabled_integration(Integration::GOOGLE_CALENDAR).present?
end
def same_connection?(integration)
integration.type == type && integration.email == email
end
def disconnect!
response = GoogleCalendarApi.new.disconnect(access_token)
response.code == 200 || response.body.include?("invalid_token") || response.body.include?("Token is not revocable")
rescue RestClient::NotFound
false
end
def self.connection_settings
super + %w[keep_inactive_members]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/affiliate_partial_refund.rb | app/models/affiliate_partial_refund.rb | # frozen_string_literal: true
class AffiliatePartialRefund < ApplicationRecord
include Purchase::Searchable::AffiliatePartialRefundCallbacks
belongs_to :affiliate_user, class_name: "User", optional: true
belongs_to :affiliate_credit, optional: true
belongs_to :seller, class_name: "User", optional: true
belongs_to :purchase, optional: true
belongs_to :affiliate, optional: true
belongs_to :balance, optional: true
validates_presence_of :affiliate_user, :affiliate_credit, :seller, :purchase, :affiliate, :balance
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/creator_contacting_customers_email_info.rb | app/models/creator_contacting_customers_email_info.rb | # frozen_string_literal: true
class CreatorContactingCustomersEmailInfo < EmailInfo
EMAIL_INFO_TYPE = "creator_contacting_customers"
validates_presence_of :installment
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/yearly_stat.rb | app/models/yearly_stat.rb | # frozen_string_literal: true
class YearlyStat < ApplicationRecord
belongs_to :user
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/creator_email_click_event.rb | app/models/creator_email_click_event.rb | # frozen_string_literal: true
class CreatorEmailClickEvent
include Mongoid::Document
include Mongoid::Timestamps
# This is a key that represents the link by which to view attached files on an installment
VIEW_ATTACHMENTS_URL = "view_attachments_url"
index({ installment_id: 1, mailer_method: 1, mailer_args: 1, click_url: 1 }, { unique: true, name: "click_index" })
field :mailer_method, type: String
field :mailer_args, type: String
field :installment_id, type: Integer
field :click_url, type: String
field :click_timestamps, type: Array
field :click_count, type: Integer
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_custom_field.rb | app/models/purchase_custom_field.rb | # frozen_string_literal: true
class PurchaseCustomField < ApplicationRecord
include FlagShihTzu
has_flags 1 => :is_post_purchase,
flag_query_mode: :bit_operator,
check_for_column: false
def self.build_from_custom_field(custom_field:, value:, bundle_product: nil)
build(custom_field:, value:, bundle_product:, name: custom_field.name, field_type: custom_field.type, custom_field_id: custom_field.id, is_post_purchase: custom_field.is_post_purchase?)
end
belongs_to :purchase
# Normally this is a temporary association, only used until the custom fields are moved to the
# product purchases by Purchase::CreateBundleProductPurchaseService. However, if the purchase is
# created but later fails (e.g. SCA abandoned) the custom fields will stay linked to the bundle purchase.
belongs_to :bundle_product, optional: true
alias_attribute :type, :field_type
normalizes :value, with: -> { _1&.strip&.squeeze(" ").presence }
before_validation :normalize_boolean_value, if: -> { CustomField::BOOLEAN_TYPES.include?(field_type) }
validates :field_type, inclusion: { in: CustomField::TYPES }
validates :name, presence: true
validate :value_valid_for_custom_field, if: :custom_field
has_many_attached :files
belongs_to :custom_field, optional: true
def value
# The `value` column is a string; for it to match the field_type we need to cast it.
CustomField::BOOLEAN_TYPES.include?(field_type) ? ActiveModel::Type::Boolean.new.cast(read_attribute(:value)) : read_attribute(:value).to_s
end
private
def normalize_boolean_value
self.value = !!value
end
def value_valid_for_custom_field
case custom_field.type
when CustomField::TYPE_TEXT, CustomField::TYPE_LONG_TEXT
errors.add(:value, :blank) if custom_field.required? && value.blank?
when CustomField::TYPE_TERMS
errors.add(:value, :blank) if value != true
when CustomField::TYPE_CHECKBOX
errors.add(:value, :blank) if custom_field.required? && value != true
when CustomField::TYPE_FILE
errors.add(:value, :blank) if custom_field.required? && files.none?
errors.add(:value, "cannot be set for file custom field") if value.present?
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/email_info_charge.rb | app/models/email_info_charge.rb | # frozen_string_literal: true
class EmailInfoCharge < ApplicationRecord
belongs_to :email_info
belongs_to :charge
validates :email_info, presence: true, uniqueness: true
validates :charge, presence: true, uniqueness: true
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/cached_sales_related_products_info.rb | app/models/cached_sales_related_products_info.rb | # frozen_string_literal: true
class CachedSalesRelatedProductsInfo < ApplicationRecord
belongs_to :product, class_name: "Link"
after_initialize :assign_default_counts_value
validate :counts_has_valid_format
def normalized_counts = counts&.transform_keys(&:to_i)
private
def assign_default_counts_value
return if persisted?
self.counts ||= {}
end
def counts_has_valid_format
# `counts` must be a hash of { product_id => sales count }
# The json format forces the keys to be strings, so we need to check that the keys are actually integers.
return if counts.is_a?(Hash) && counts.all? { _1.to_s == _1.to_i.to_s && _2.is_a?(Integer) }
errors.add(:counts, "has invalid format")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/chile_bank_account.rb | app/models/chile_bank_account.rb | # frozen_string_literal: true
class ChileBankAccount < BankAccount
include ChileBankAccount::AccountType
BANK_ACCOUNT_TYPE = "CL"
BANK_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{5,25}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
before_validation :set_default_account_type, on: :create, if: ->(chile_bank_account) { chile_bank_account.account_type.nil? }
validate :validate_bank_code
validate :validate_account_number
validates :account_type, inclusion: { in: AccountType.all }
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::CHL.alpha2
end
def currency
Currency::CLP
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
end
def set_default_account_type
self.account_type = AccountType::CHECKING
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/application_record.rb | app/models/application_record.rb | # frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
include StrippedFields
self.abstract_class = true
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/qatar_bank_account.rb | app/models/qatar_bank_account.rb | # frozen_string_literal: true
class QatarBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "QA"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{29}$/
private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::QAT.alpha2
end
def currency
Currency::QAR
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid." unless account_number_decrypted.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_files_archive.rb | app/models/product_files_archive.rb | # frozen_string_literal: true
class ProductFilesArchive < ApplicationRecord
include ExternalId, S3Retrievable, SignedUrlHelper, Deletable, CdnDeletable
has_paper_trail
belongs_to :link, optional: true
belongs_to :installment, optional: true
belongs_to :variant, optional: true
has_and_belongs_to_many :product_files
after_create_commit :generate_zip_archive!
state_machine :product_files_archive_state, initial: :queueing do
before_transition any => :in_progress, do: :set_digest
event :mark_failed do
transition all => :failed
end
event :mark_in_progress do
transition all => :in_progress
end
event :mark_ready do
transition [:in_progress] => :ready
end
end
validate :belongs_to_product_or_installment_or_variant
has_s3_fields :url
scope :ready, -> { where(product_files_archive_state: "ready") }
scope :folder_archives, -> { where.not(folder_id: nil) }
scope :entity_archives, -> { where(folder_id: nil) }
delegate :user, to: :with_product_files_owner
def has_alive_duplicate_files?
false
end
def self.latest_ready_entity_archive
entity_archives.alive.ready.last
end
def self.latest_ready_folder_archive(folder_id)
folder_archives.alive.ready.where(folder_id:).last
end
def has_cdn_url?
url&.starts_with?(S3_BASE_URL)
end
def folder_archive?
folder_id.present?
end
def with_product_files_owner
link || installment || variant
end
def generate_zip_archive!
UpdateProductFilesArchiveWorker.perform_in(5.seconds, id)
end
# Overrides S3Retrievable s3_directory_uri
def s3_directory_uri
return unless s3?
s3_url.split("/")[4, 4].join("/")
end
def set_url_if_not_present
self.url ||= construct_url
end
def needs_updating?(new_product_files)
new_files = new_product_files.archivable
existing_files = product_files.archivable
return true if rich_content_provider.nil? && (new_files.size != existing_files.size || new_files.in_order != existing_files.in_order)
# Update if folder / file renamed or files re-arranged into different folders
digest != files_digest(new_files)
end
def rich_content_provider
link || variant
end
private
def set_digest
self.digest = files_digest(product_files.archivable)
end
def files_digest(files)
rich_content_files = rich_content_provider&.map_rich_content_files_and_folders
file_list = if rich_content_files.blank?
files.map { |file| [file.folder&.external_id, file.folder&.name, file.external_id, file.name_displayable].compact.join("/") }.sort
else
rich_content_files = rich_content_files.select { |key, value| value[:folder_id] == folder_id } if folder_archive?
rich_content_files.values.map do |info|
page_info = folder_archive? ? [] : [info[:page_id], info[:page_title]]
page_info.concat([info[:folder_id], info[:folder_name], info[:file_id], info[:file_name]]).flatten.compact.join("/")
end.sort
end
Digest::SHA1.hexdigest(file_list.join("\n"))
end
def belongs_to_product_or_installment_or_variant
return if [link, installment, variant].compact.length == 1
errors.add(:base, "A product files archive needs to belong to an installment, a product or a variant")
end
def construct_url
archive_filename = (folder_archive? ? (rich_content_provider.rich_content_folder_name(folder_id).presence || "Untitled") : with_product_files_owner.name).gsub(/\s+/, "_").tr("/", "-")
s3_key = ["attachments_zipped", with_product_files_owner.user.external_id,
with_product_files_owner.external_id, external_id, archive_filename].join("/")
url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{s3_key}"
# NOTE: Total url length must be 255 characters or less to fit MySQL column
url.first(251) + ".zip"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_sort_key.rb | app/models/product_sort_key.rb | # frozen_string_literal: true
class ProductSortKey
FEATURED = "featured"
BEST_SELLERS = "best_sellers"
CURATED = "curated"
NEWEST = "newest"
PRICE_ASCENDING = "price_asc"
PRICE_DESCENDING = "price_desc"
AVAILABLE_PRICE_ASCENDING = "available_price_asc"
AVAILABLE_PRICE_DESCENDING = "available_price_desc"
MOST_REVIEWED = "most_reviewed"
HIGHEST_RATED = "highest_rated"
PAGE_LAYOUT = "page_layout"
RECENTLY_UPDATED = "recently_updated"
HOT_AND_NEW = "hot_and_new"
STAFF_PICKED = "staff_picked"
REVENUE_ASCENDING = "sales_volume_asc"
REVENUE_DESCENDING = "sales_volume_desc"
IS_RECOMMENDABLE_ASCENDING = "recommendable_asc"
IS_RECOMMENDABLE_DESCENDING = "recommendable_desc"
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/australia_backtax_email_info.rb | app/models/australia_backtax_email_info.rb | # frozen_string_literal: true
class AustraliaBacktaxEmailInfo < ApplicationRecord
belongs_to :user
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/el_salvador_bank_account.rb | app/models/el_salvador_bank_account.rb | # frozen_string_literal: true
class ElSalvadorBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "SV"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
bank_code
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::SLV.alpha2
end
def currency
Currency::USD
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if Ibandit::IBAN.new(account_number_decrypted).valid?
errors.add :base, "The account number is invalid."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/dispute_evidence.rb | app/models/dispute_evidence.rb | # frozen_string_literal: true
class DisputeEvidence < ApplicationRecord
def self.create_from_dispute!(dispute)
DisputeEvidence::CreateFromDisputeService.new(dispute).perform!
end
has_paper_trail
include ExternalId, TimestampStateFields
delegate :disputable, to: :dispute
stripped_fields \
:customer_purchase_ip,
:customer_email,
:customer_name,
:billing_address,
:product_description,
:refund_policy_disclosure,
:cancellation_policy_disclosure,
:shipping_address,
:shipping_carrier,
:shipping_tracking_number,
:uncategorized_text,
:cancellation_rebuttal,
:refund_refusal_explanation,
:reason_for_winning
timestamp_state_fields :created, :seller_contacted, :seller_submitted, :resolved
belongs_to :dispute
SUBMIT_EVIDENCE_WINDOW_DURATION_IN_HOURS = 72
STRIPE_MAX_COMBINED_FILE_SIZE = 5_000_000.bytes
MINIMUM_RECOMMENDED_CUSTOMER_COMMUNICATION_FILE_SIZE = 1_000_000.bytes
ALLOWED_FILE_CONTENT_TYPES = %w[image/jpeg image/png application/pdf].freeze
RESOLUTIONS = %w(unknown submitted rejected).freeze
RESOLUTIONS.each do |resolution|
self.const_set("RESOLUTION_#{resolution.upcase}", resolution)
end
has_one_attached :cancellation_policy_image
has_one_attached :refund_policy_image
has_one_attached :receipt_image
has_one_attached :customer_communication_file
validates_presence_of :dispute
validates :cancellation_rebuttal, :reason_for_winning, :refund_refusal_explanation, length: { maximum: 3_000 }
validate :customer_communication_file_size
validate :customer_communication_file_type
validate :all_files_size_within_limit
def policy_disclosure=(value)
policy_disclosure_attribute = for_subscription_purchase? ? :cancellation_policy_disclosure : :refund_policy_disclosure
self.assign_attributes(policy_disclosure_attribute => value)
end
def policy_image
for_subscription_purchase? ? cancellation_policy_image : refund_policy_image
end
def for_subscription_purchase?
@_subscription_purchase ||= disputable.disputed_purchases.any? { _1.subscription.present? }
end
def customer_communication_file_size
return unless customer_communication_file.attached?
return if customer_communication_file.byte_size <= customer_communication_file_max_size
errors.add(:base, "The file exceeds the maximum size allowed.")
end
def customer_communication_file_type
return unless customer_communication_file.attached?
return if customer_communication_file.content_type.in?(ALLOWED_FILE_CONTENT_TYPES)
errors.add(:base, "Invalid file type.")
end
def hours_left_to_submit_evidence
return 0 unless seller_contacted?
(SUBMIT_EVIDENCE_WINDOW_DURATION_IN_HOURS - (Time.current - seller_contacted_at) / 1.hour).round
end
def all_files_size_within_limit
all_files_size = receipt_image.byte_size.to_i +
policy_image.byte_size.to_i +
customer_communication_file.byte_size.to_i
return if STRIPE_MAX_COMBINED_FILE_SIZE >= all_files_size
errors.add(:base, "Uploaded files exceed the maximum size allowed by Stripe.")
end
def customer_communication_file_max_size
@_customer_communication_file_max_size = STRIPE_MAX_COMBINED_FILE_SIZE -
receipt_image.byte_size.to_i -
policy_image.byte_size.to_i
end
def policy_image_max_size
@_policy_image_max_size = STRIPE_MAX_COMBINED_FILE_SIZE -
MINIMUM_RECOMMENDED_CUSTOMER_COMMUNICATION_FILE_SIZE -
receipt_image.byte_size.to_i
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/video_file.rb | app/models/video_file.rb | # frozen_string_literal: true
class VideoFile < ApplicationRecord
include WithFileProperties
include Deletable
include S3Retrievable
include CdnDeletable, CdnUrlHelper
include SignedUrlHelper
include FlagShihTzu
include VideoFile::HasThumbnail
has_s3_fields :url
belongs_to :record, polymorphic: true
belongs_to :user
has_flags 1 => :is_transcoded_for_hls,
2 => :analyze_completed,
:flag_query_mode => :bit_operator
validates :url, presence: true
validate :url_is_s3
before_save :set_filetype
after_create_commit :schedule_file_analysis
def smil_xml
smil_xml = ::Builder::XmlMarkup.new
smil_xml.smil do |smil|
smil.body do |body|
body.switch do |switch|
switch.video(src: signed_cloudfront_url(s3_key, is_video: true))
end
end
end
end
def signed_download_url
signed_download_url_for_s3_key_and_filename(s3_key, s3_filename, is_video: true)
end
# Compatibility with WithFileProperties.
attr_accessor :pagelength
attr_writer :filegroup
def filegroup
"video"
end
private
def set_filetype
self.filetype = s3_extension.delete_prefix(".")
end
def schedule_file_analysis
AnalyzeFileWorker.perform_async(id, self.class.name)
end
def url_is_s3
errors.add(:url, "must be an S3 URL") unless s3?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/ethiopia_bank_account.rb | app/models/ethiopia_bank_account.rb | # frozen_string_literal: true
class EthiopiaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "ET"
BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9a-zA-Z]{13,16}$/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_account_number
def routing_number
"#{bank_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::ETH.alpha2
end
def currency
Currency::ETB
end
def account_number_visual
"******#{account_number_last_four}"
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_bank_code
return if BANK_CODE_FORMAT_REGEX.match?(bank_code)
errors.add :base, "The bank code is invalid."
end
def validate_account_number
return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted)
errors.add :base, "The account number is invalid."
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.