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/controllers/wishlists/followers_controller.rb | app/controllers/wishlists/followers_controller.rb | # frozen_string_literal: true
class Wishlists::FollowersController < ApplicationController
before_action :authenticate_user!, except: :unsubscribe
after_action :verify_authorized, except: :unsubscribe
before_action { e404 if Feature.inactive?(:follow_wishlists, current_seller) }
def create
wishlist = Wishlist.find_by_external_id!(params[:wishlist_id])
authorize WishlistFollower
wishlist_follower = wishlist.wishlist_followers.build(follower_user: current_seller)
if wishlist_follower.save
head :created
else
render json: { error: wishlist_follower.errors.full_messages.first }, status: :unprocessable_entity
end
end
def destroy
wishlist = Wishlist.find_by_external_id!(params[:wishlist_id])
wishlist_follower = wishlist.wishlist_followers.alive.find_by(follower_user: current_seller)
e404 if wishlist_follower.blank?
authorize wishlist_follower
wishlist_follower.mark_deleted!
head :no_content
end
def unsubscribe
wishlist_follower = WishlistFollower.find_by_external_id!(params[:follower_id])
wishlist_follower.mark_deleted!
flash[:notice] = "You are no longer following #{wishlist_follower.wishlist.name}."
redirect_to wishlist_url(wishlist_follower.wishlist.url_slug, host: wishlist_follower.wishlist.user.subdomain_with_protocol), allow_other_host: true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/wishlists/products_controller.rb | app/controllers/wishlists/products_controller.rb | # frozen_string_literal: true
class Wishlists::ProductsController < ApplicationController
before_action :authenticate_user!, except: :index
after_action :verify_authorized, except: :index
def index
wishlist = Wishlist.find_by_external_id!(params[:wishlist_id])
render json: WishlistPresenter.new(wishlist:).public_items(request:, pundit_user:, page: params[:page])
end
def create
wishlist = current_seller.wishlists.find_by_external_id!(params[:wishlist_id])
authorize wishlist
authorize WishlistProduct
attributes = permitted_attributes(WishlistProduct)
product = Link.find_by_external_id!(attributes.delete(:product_id))
option_id = attributes.delete(:option_id)
variant = option_id.presence && product.variants_or_skus.find_by_external_id!(option_id)
wishlist_product = wishlist.alive_wishlist_products
.find_or_initialize_by(product:, variant:, recurrence: attributes.delete(:recurrence))
if wishlist_product.update(attributes)
if wishlist.wishlist_followers.alive.exists?
SendWishlistUpdatedEmailsJob.perform_in(8.hours, wishlist.id, wishlist.wishlist_products_for_email.pluck(:id))
end
head :created
else
render json: { error: wishlist_product.errors.full_messages.first }, status: :unprocessable_entity
end
end
def destroy
wishlist_product = WishlistProduct.alive.find_by_external_id!(params[:id])
authorize wishlist_product
wishlist_product.mark_deleted!
head :no_content
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/wishlists/following_controller.rb | app/controllers/wishlists/following_controller.rb | # frozen_string_literal: true
class Wishlists::FollowingController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
before_action { e404 if Feature.inactive?(:follow_wishlists, current_seller) }
layout "inertia"
def index
authorize Wishlist
@title = "Following"
wishlists_props = WishlistPresenter.library_props(
wishlists: current_seller.alive_following_wishlists,
is_wishlist_creator: false
)
render inertia: "Wishlists/Following/Index", props: {
wishlists: wishlists_props,
reviews_page_enabled: Feature.active?(:reviews_page, current_seller),
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_affiliate.rb | app/models/product_affiliate.rb | # frozen_string_literal: true
class ProductAffiliate < ApplicationRecord
include FlagShihTzu
self.table_name = "affiliates_links"
belongs_to :affiliate
belongs_to :product, class_name: "Link", foreign_key: :link_id
validates :affiliate, uniqueness: { scope: :product }
validates :affiliate_basis_points, presence: true, if: -> { affiliate.is_a?(Collaborator) && !affiliate.apply_to_all_products? }
validates :affiliate_basis_points, numericality: { greater_than_or_equal_to: Collaborator::MIN_PERCENT_COMMISSION * 100,
less_than_or_equal_to: Collaborator::MAX_PERCENT_COMMISSION * 100,
allow_nil: true }, if: -> { affiliate.is_a?(Collaborator) }
validate :product_is_eligible_for_collabs, if: -> { affiliate.is_a?(Collaborator) }
validate :product_is_not_a_collab, if: -> { affiliate.is_a?(DirectAffiliate) }
after_create :enable_product_collaborator_flag_and_disable_affiliates, if: -> { affiliate.is_a?(Collaborator) }
after_destroy :disable_product_collaborator_flag, if: -> { affiliate.is_a?(Collaborator) }
after_create :update_audience_member_with_added_product
after_destroy :update_audience_member_with_removed_product
has_flags 1 => :dont_show_as_co_creator
def affiliate_percentage
return unless affiliate_basis_points.present?
affiliate_basis_points / 100
end
private
def enable_product_collaborator_flag_and_disable_affiliates
product.update!(is_collab: true)
product.self_service_affiliate_products.map { _1.update!(enabled: false) }
product.product_affiliates.where.not(id:).joins(:affiliate).merge(Affiliate.direct_affiliates).map { _1.destroy! }
end
def disable_product_collaborator_flag
product.update!(is_collab: false)
end
def update_audience_member_with_added_product
affiliate.update_audience_member_with_added_product(link_id)
end
def update_audience_member_with_removed_product
affiliate.update_audience_member_with_removed_product(link_id)
end
def product_is_eligible_for_collabs
return unless product.has_another_collaborator?(collaborator: affiliate)
errors.add :base, "This product is not eligible for the Gumroad Affiliate Program."
end
def product_is_not_a_collab
return unless product.is_collab?
errors.add :base, "Collab products cannot have affiliates"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/pakistan_bank_account.rb | app/models/pakistan_bank_account.rb | # frozen_string_literal: true
class PakistanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "PK"
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::PAK.alpha2
end
def currency
Currency::PKR
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/mozambique_bank_account.rb | app/models/mozambique_bank_account.rb | # frozen_string_literal: true
class MozambiqueBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MZ"
BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^([0-9a-zA-Z]){21}$/
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::MOZ.alpha2
end
def currency
Currency::MZN
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/turkey_bank_account.rb | app/models/turkey_bank_account.rb | # frozen_string_literal: true
class TurkeyBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "TR"
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::TUR.alpha2
end
def currency
Currency::TRY
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/oman_bank_account.rb | app/models/oman_bank_account.rb | # frozen_string_literal: true
class OmanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "OM"
BANK_CODE_FORMAT_REGEX = /^[A-Z]{4}OM[A-Z0-9]{2,5}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9]{6,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::OMN.alpha2
end
def currency
Currency::OMR
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)
iban = Ibandit::IBAN.new(account_number_decrypted)
return if iban.valid? && iban.country_code == "OM"
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/recurring_service.rb | app/models/recurring_service.rb | # frozen_string_literal: true
class RecurringService < ApplicationRecord
include ExternalId
include JsonData
include DiscountCode
include RecurringService::Recurrence
include RecurringService::Tiers
belongs_to :user, optional: true
has_many :charges, class_name: "ServiceCharge"
has_one :latest_charge, -> { order(id: :desc) }, class_name: "ServiceCharge"
enum recurrence: %i[monthly yearly]
validates_presence_of :user, :price_cents
validates_associated :user
def humanized_renewal_at
renewal_at.strftime("%B #{renewal_at.day.ordinalize}, %Y")
end
def cancelled_or_failed?
cancelled_at.present? || failed_at.present?
end
def renewal_at
charges.successful.last.succeeded_at + recurrence_duration
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/tag.rb | app/models/tag.rb | # frozen_string_literal: true
class Tag < ApplicationRecord
before_validation :clean_name, if: :name_changed?
has_many :product_taggings, dependent: :destroy
has_many :products, through: :product_taggings, class_name: "Link"
validates :name,
presence: true,
uniqueness: { case_sensitive: true },
length: { minimum: 2, too_short: "A tag is too short. Please try again with a longer one, above 2 characters.",
maximum: 20, too_long: "A tag is too long. Please try again with a shorter one, under 20 characters." },
format: { with: /\A[^#,][^,]+\z/, message: "A tag cannot start with hashes or contain commas." }
scope :by_text, lambda { |text: "", limit: 10|
select("tags.*, COUNT(product_taggings.id) AS uses")
.where("tags.name LIKE ?", "#{text.downcase}%")
.joins("LEFT OUTER JOIN product_taggings ON product_taggings.tag_id = tags.id")
.order("uses DESC")
.order("tags.name ASC")
.group("tags.id")
.limit(limit)
}
def as_json(opts = {})
if opts[:admin]
{ name:, humanized_name:, flagged: flagged?, id:, uses: product_taggings.count }
else
super(opts)
end
end
def humanized_name
self[:humanized_name] || name.titleize
end
def flag!
self.flagged_at = Time.current
save!
end
def flagged?
flagged_at.present?
end
def unflag!
self.flagged_at = nil
save!
end
private
def clean_name
return if name.nil?
self.name = name.downcase.strip.gsub(/[[:space:]]+/, " ")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/liechtenstein_bank_account.rb | app/models/liechtenstein_bank_account.rb | # frozen_string_literal: true
class LiechtensteinBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "LI"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::LIE.alpha2
end
def currency
Currency::CHF
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 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_compliance_info.rb | app/models/user_compliance_info.rb | # frozen_string_literal: true
class UserComplianceInfo < ApplicationRecord
self.table_name = "user_compliance_info"
include ExternalId
include Immutable
include UserComplianceInfo::BusinessTypes
include JsonData
stripped_fields :first_name, :last_name, :street_address, :city, :zip_code, :business_name, :business_street_address, :business_city, :business_zip_code, on: :create
MINIMUM_DATE_OF_BIRTH_AGE = 13
belongs_to :user, optional: true
validates_presence_of :user
encrypt_with_public_key :individual_tax_id,
symmetric: :never,
public_key: OpenSSL::PKey.read(GlobalConfig.get("STRONGBOX_GENERAL"),
GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")).public_key,
private_key: GlobalConfig.get("STRONGBOX_GENERAL")
encrypt_with_public_key :business_tax_id,
symmetric: :never,
public_key: OpenSSL::PKey.read(GlobalConfig.get("STRONGBOX_GENERAL"),
GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")).public_key,
private_key: GlobalConfig.get("STRONGBOX_GENERAL")
serialize :verticals, type: Array, coder: YAML
validate :birthday_is_over_minimum_age
after_create_commit :handle_stripe_compliance_info
after_create_commit :handle_compliance_info_request
scope :country, ->(country) { where(country:) }
attr_accessor :skip_stripe_job_on_create
attr_json_data_accessor :phone
attr_json_data_accessor :business_phone
attr_json_data_accessor :job_title
attr_json_data_accessor :stripe_company_document_id
attr_json_data_accessor :stripe_additional_document_id
attr_json_data_accessor :nationality
attr_json_data_accessor :business_vat_id_number
attr_json_data_accessor :first_name_kanji
attr_json_data_accessor :last_name_kanji
attr_json_data_accessor :first_name_kana
attr_json_data_accessor :last_name_kana
attr_json_data_accessor :building_number
attr_json_data_accessor :street_address_kanji
attr_json_data_accessor :street_address_kana
attr_json_data_accessor :business_name_kanji
attr_json_data_accessor :business_name_kana
attr_json_data_accessor :business_building_number
attr_json_data_accessor :business_street_address_kanji
attr_json_data_accessor :business_street_address_kana
def is_individual?
!is_business?
end
# Public: Returns if the UserComplianceInfo record has all it's critical compliance related fields completed, these are:
# Individual: First Name, Last Name, Address, DOB
# Business: First Name, Last Name, Address, DOB, Business Name, Business Type, Business Address
def has_completed_compliance_info?
first_name.present? &&
last_name.present? &&
birthday.present? &&
street_address.present? &&
city.present? &&
state.present? &&
zip_code.present? &&
country.present? &&
individual_tax_id.present? &&
(
!is_business ||
(
business_tax_id.present? &&
business_name.present? &&
business_type.present? &&
business_street_address.present? &&
business_city.present? &&
business_state.present? &&
business_zip_code.present?
)
)
end
# Public: Returns the ISO_3166-1 Alpha-2 country code for the country stored in this compliance info.
#
# Example: US = United States of America
#
# Full list of countries: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
#
# Note 1: At some point in the future we will store country code, and can realize name from the code
# rather than the reverse that we are doing now.
def country_code
Compliance::Countries.find_by_name(country)&.alpha2
end
def business_country_code
Compliance::Countries.find_by_name(business_country)&.alpha2
end
def state_code
Compliance::Countries.find_subdivision_code(country_code, state)
end
def business_state_code
Compliance::Countries.find_subdivision_code(country_code, business_state)
end
def legal_entity_business_type
is_business? ? business_type : BusinessTypes::SOLE_PROPRIETORSHIP
end
def legal_entity_payable_business_type
payable_type_map[legal_entity_business_type] || payable_type_map[BusinessTypes::SOLE_PROPRIETORSHIP]
end
def first_and_last_name
"#{first_name} #{last_name}".squeeze(" ").strip
end
def legal_entity_name
is_business? ? business_name : first_and_last_name
end
def legal_entity_dba
dba.presence || legal_entity_name
end
def legal_entity_street_address
is_business? ? business_street_address : street_address
end
def legal_entity_city
is_business? ? business_city : city
end
def legal_entity_state
is_business? ? business_state : state
end
def legal_entity_state_code
is_business? ? business_state_code : state_code
end
def legal_entity_zip_code
is_business? ? business_zip_code : zip_code
end
def legal_entity_country
(business_country if is_business?) || country
end
def legal_entity_country_code
(business_country_code if is_business?) || country_code
end
def legal_entity_tax_id
is_business? ? business_tax_id : individual_tax_id
end
def has_individual_tax_id?
individual_tax_id.present?
end
alias_method :has_individual_tax_id, :has_individual_tax_id?
def has_business_tax_id?
business_tax_id.present?
end
alias_method :has_business_tax_id, :has_business_tax_id?
private
def handle_stripe_compliance_info
HandleNewUserComplianceInfoWorker.perform_in(5.seconds, id) unless skip_stripe_job_on_create
end
def handle_compliance_info_request
UserComplianceInfoRequest.handle_new_user_compliance_info(self)
end
def birthday_is_over_minimum_age
errors.add :base, "You must be 13 years old to use Gumroad." if birthday && birthday > MINIMUM_DATE_OF_BIRTH_AGE.years.ago
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/self_service_affiliate_product.rb | app/models/self_service_affiliate_product.rb | # frozen_string_literal: true
class SelfServiceAffiliateProduct < ApplicationRecord
include Affiliate::BasisPointsValidations
include Affiliate::DestinationUrlValidations
belongs_to :seller, class_name: "User", optional: true
belongs_to :product, class_name: "Link", optional: true
validates :seller, :product, presence: true
validates :affiliate_basis_points, presence: true, if: :enabled?
validate :affiliate_basis_points_must_fall_in_an_acceptable_range, if: :enabled?
validate :product_is_not_a_collab, if: :enabled?
validate :product_user_and_seller_is_same
scope :enabled, -> { where(enabled: true) }
def self.bulk_upsert!(products_with_details, seller_id)
transaction do
products_with_details.each do |product_details|
self_service_affiliate_product = find_or_initialize_by(product_id: ObfuscateIds.decrypt_numeric(product_details[:id].to_i))
self_service_affiliate_product.enabled = product_details[:enabled]
self_service_affiliate_product.seller_id = seller_id
self_service_affiliate_product.affiliate_basis_points = product_details[:fee_percent] ? product_details[:fee_percent].to_i * 100 : 0
self_service_affiliate_product.destination_url = product_details[:destination_url]
self_service_affiliate_product.save!
end
end
end
private
def product_is_not_a_collab
return unless product.present? && product.is_collab?
errors.add :base, "Collab products cannot have affiliates"
end
def product_user_and_seller_is_same
return if product_id.nil? || seller_id.nil?
return if product.user == seller
errors.add(:base, "The product '#{product.name}' does not belong to you (#{seller.email}).")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/subscription.rb | app/models/subscription.rb | # frozen_string_literal: true
class Subscription < ApplicationRecord
class DoubleChargeAttemptError < GumroadRuntimeError
def initialize(subscription_id, purchase_id)
super("Attempted to double charge subscription: #{subscription_id}, while purchase #{purchase_id} was in progress")
end
end
class UpdateFailed < StandardError; end
has_paper_trail
include ExternalId
include FlagShihTzu
include Subscription::PingNotification
include Purchase::Searchable::SubscriptionCallbacks
include AfterCommitEverywhere
# time allowed after card declined for buyer to have a successful charge before ending the subscription
ALLOWED_TIME_BEFORE_FAIL_AND_UNSUBSCRIBE = 5.days
# time before subscription fails to send reminder about card declined
CHARGE_DECLINED_REMINDER_EMAIL = 2.days
# time before free trial expires to send reminder email
FREE_TRIAL_EXPIRING_REMINDER_EMAIL = 2.days
# time to access membership manage page after requesting magic link
TOKEN_VALIDITY = 24.hours
ALLOWED_TIME_BEFORE_SENDING_REPEATED_CANCELLATION_EMAIL_TO_CREATOR = 7.days
module ResubscriptionReason
PAYMENT_ISSUE_RESOLVED = "payment_issue_resolved"
end
has_flags 1 => :is_test_subscription,
2 => :cancelled_by_buyer,
3 => :cancelled_by_admin,
4 => :flat_fee_applicable,
5 => :is_resubscription_pending_confirmation,
6 => :mor_fee_applicable,
7 => :is_installment_plan,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
belongs_to :link, optional: true
belongs_to :user, optional: true
belongs_to :seller, class_name: "User"
belongs_to :credit_card, optional: true
belongs_to :last_payment_option, class_name: "PaymentOption", optional: true
has_many :purchases
has_one :original_purchase, -> { is_original_subscription_purchase.not_is_archived_original_subscription_purchase }, class_name: "Purchase"
has_one :true_original_purchase, -> { is_original_subscription_purchase.order(:id) }, class_name: "Purchase"
has_one :last_successful_purchase, -> { successful.order(created_at: :desc) }, class_name: "Purchase"
has_many :url_redirects
has_many :payment_options
has_many :subscription_plan_changes
has_one :latest_plan_change, -> { alive.order(created_at: :desc) }, class_name: "SubscriptionPlanChange"
has_one :latest_applicable_plan_change, -> { alive.currently_applicable.order(created_at: :desc) }, class_name: "SubscriptionPlanChange"
has_one :offer_code, through: :original_purchase
has_many :subscription_events
before_validation :assign_seller, on: :create
validate :must_have_payment_option
validate :installment_plans_cannot_be_cancelled_by_buyer
before_create :enable_flat_fee
before_create :enable_mor_fee
after_create :update_last_payment_option
after_save :create_interruption_event, if: -> { deactivated_at_previously_changed? }
after_create :create_interruption_event, if: -> { deactivated_at.present? } # needed in addition to the `after_save`. See https://github.com/gumroad/web/pull/26305#discussion_r1336425626
after_commit :send_ended_notification_webhook, if: Proc.new { |subscription|
subscription.deactivated_at.present? &&
subscription.deactivated_at_previously_changed? &&
subscription.deactivated_at_previous_change.first.nil?
}
attr_writer :price
# An active subscription is one that should be delivered content to and counted towards customer count. Subscriptions that are pending cancellation
# are active subscriptions.
scope :active, lambda {
where("subscriptions.flags & ? = 0 and failed_at is null and ended_at is null and (cancelled_at is null or cancelled_at > ?)",
flag_mapping["flags"][:is_test_subscription], Time.current)
}
scope :active_without_pending_cancel, -> {
where("subscriptions.flags & ? = 0 and failed_at is null and ended_at is null and cancelled_at is null",
flag_mapping["flags"][:is_test_subscription])
}
delegate :custom_fields, to: :original_purchase, allow_nil: true
delegate :original_offer_code, to: :original_purchase, allow_nil: true
def as_json(*)
json = {
id: external_id,
email:,
product_id: link.external_id,
product_name: link.name,
user_id: user.try(:external_id),
user_email: user.try(:email),
purchase_ids: purchases.for_sales_api.map(&:external_id),
created_at:,
user_requested_cancellation_at:,
charge_occurrence_count:,
recurrence:,
cancelled_at:,
ended_at:,
failed_at:,
free_trial_ends_at:,
status:
}
json[:license_key] = license_key if license_key.present?
json
end
# An alive subscription is always an active subscription. However, since there are 3 states to a subscription (active, pending cancellation, and
# ended), there are few instances where we want pending cancellation subscriptions to not be considered alive and in those instances, the caller
# sets include_pending_cancellation as false and those subscriptions will not be considered alive. This is named different from active to avoid confusion.
def alive?(include_pending_cancellation: true)
return false if failed_at.present? || ended_at.present?
return true if cancelled_at.nil?
include_pending_cancellation && cancelled_at.future?
end
def alive_at?(time)
start_time = true_original_purchase.created_at
end_time = next_event_at(:deactivated, start_time) || deactivated_at
while start_time do
return true if end_time.nil? && time > start_time
return true if end_time.present? && time >= start_time && time <= end_time
start_time = next_event_at(:restarted, end_time)
end_time = next_event_at(:deactivated, start_time) || deactivated_at
end
false
end
def grant_access_to_product?
if is_installment_plan?
!cancelled_or_failed?
else
alive? || !link.block_access_after_membership_cancellation
end
end
def license_key
@_license_key ||= original_purchase.license_key
end
def credit_card_to_charge
return if is_test_subscription?
if credit_card.present?
credit_card
elsif user.present?
user.credit_card
end
end
def installments
# do not include workflow installments as that is gathered separately for the library view since it depends on date of purchase and workflow timeline
installments = link.installments.not_workflow_installment.alive.published.where("published_at >= ?", created_at)
installments = installments.where("published_at <= ?", cancelled_at) if cancelled_at.present?
installments = installments.where("published_at <= ?", failed_at) if failed_at.present?
# The buyer's library should include the last installment that was published before they subscribed
last_installment_before_subscription_began = nil
if link.should_include_last_post
last_installment_before_subscription_began =
link.installments.alive.published.where("published_at < ?", created_at).order("published_at DESC").first
end
last_installment_before_subscription_began ? installments.to_a.unshift(last_installment_before_subscription_began) : installments
end
def email
user&.form_email.presence || (gift? ? true_original_purchase.giftee_email : original_purchase.email)
end
def emails
{
subscription: email,
purchase: gift? ? true_original_purchase.giftee_email : original_purchase.email,
user: user&.email,
}
end
def price
payment_option = last_payment_option || fetch_last_payment_option
payment_option.price
end
def current_subscription_price_cents
if is_installment_plan
original_purchase.minimum_paid_price_cents
else
discount_applies_to_next_charge? ?
original_purchase.displayed_price_cents :
original_purchase.displayed_price_cents_before_offer_code(include_deleted: true)
end
end
def current_plan_displayed_price_cents
# For PWYW subscriptions, show tier minimum price if tier price is less than
# current subscription price. Otherwise, show current subscription price.
if tier&.customizable_price? && tier_price.present? && tier_price.price_cents <= current_subscription_price_cents
tier_price.price_cents
else
original_purchase.displayed_price_cents_before_offer_code || original_purchase.displayed_price_cents
end
end
def update_last_payment_option
self.last_payment_option = fetch_last_payment_option
save! if persisted?
end
def build_purchase(override_params: {}, from_failed_charge_email: false)
perceived_price_cents = override_params.delete(:perceived_price_cents)
perceived_price_cents ||= current_subscription_price_cents
is_upgrade_purchase = override_params.delete(:is_upgrade_purchase)
purchase_params = { price_range: perceived_price_cents / (link.single_unit_currency? ? 1 : 100.0),
perceived_price_cents:,
email:,
full_name: original_purchase.full_name,
street_address: original_purchase.street_address,
country: original_purchase.country,
state: original_purchase.state,
zip_code: original_purchase.zip_code,
city: original_purchase.city,
ip_address: original_purchase.ip_address,
ip_state: original_purchase.ip_state,
ip_country: original_purchase.ip_country,
browser_guid: original_purchase.browser_guid,
variant_attributes: original_purchase.variant_attributes,
subscription: self,
referrer: original_purchase.referrer,
quantity: original_purchase.quantity,
was_product_recommended: original_purchase.was_product_recommended,
is_installment_payment: original_purchase.is_installment_payment }
purchase_params.merge!(override_params)
purchase = Purchase.new(purchase_params)
purchase.variant_attributes = original_purchase.variant_attributes
purchase.offer_code = original_purchase.offer_code if discount_applies_to_next_charge?
purchase.purchaser = user
purchase.link = link
purchase.seller = original_purchase.seller
purchase.credit_card_zipcode = original_purchase.credit_card_zipcode
if !from_failed_charge_email
if credit_card_id.present?
purchase.credit_card_id = credit_card_id
elsif purchase.purchaser.present? && purchase.purchaser_card_supported?
purchase.credit_card_id = purchase.purchaser.credit_card_id
end
end
purchase.affiliate = original_purchase.affiliate if original_purchase.affiliate.try(:eligible_for_credit?)
purchase.is_upgrade_purchase = is_upgrade_purchase if is_upgrade_purchase
get_vat_id_from_original_purchase(purchase)
purchase
end
def process_purchase!(purchase, from_failed_charge_email = false, off_session: true)
purchase.ensure_completion do
purchase.process!(off_session:)
error_messages = purchase.errors.messages.dup
if purchase.errors.present? || purchase.error_code.present? || purchase.stripe_error_code.present?
unless from_failed_charge_email
if purchase.has_payment_network_error?
schedule_charge(1.hour.from_now)
else
if purchase.has_payment_error?
CustomerLowPriorityMailer.subscription_card_declined(id).deliver_later(queue: "low")
ChargeDeclinedReminderWorker.perform_in(ALLOWED_TIME_BEFORE_FAIL_AND_UNSUBSCRIBE - CHARGE_DECLINED_REMINDER_EMAIL, id)
else
CustomerLowPriorityMailer.subscription_charge_failed(id).deliver_later(queue: "low")
end
schedule_charge(1.day.from_now) if purchase.has_retryable_payment_error?
end
end
# schedule for termination 5 days after subscription is overdue for a charge
UnsubscribeAndFailWorker.perform_in(terminate_by > (Time.current + 1.minute) ? terminate_by : 1.minute, id)
purchase.mark_failed!
elsif purchase.in_progress? && purchase.charge_intent.is_a?(StripeChargeIntent) && (purchase.charge_intent&.processing? || purchase.charge_intent.requires_action?)
# For recurring charges on Indian cards, the charge goes into processing state for 26 hours.
# We'll receive a webhook once the charge succeeds/fails, and we'll transition the purchase
# to terminal (successful/failed) state when we receive that webhook.
# Check back later to see if the purchase has been completed. If not, transition to a failed state.
FailAbandonedPurchaseWorker.perform_in(ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase.id)
else
handle_purchase_success(purchase)
end
purchase.save!
error_messages.each do |key, messages|
messages.each do |message|
purchase.errors.add(key, message)
end
end
purchase
end
end
def handle_purchase_success(purchase, succeeded_at: nil)
purchase.succeeded_at = succeeded_at if succeeded_at.present?
purchase.update_balance_and_mark_successful!
original_purchase.update!(should_exclude_product_review: false) if original_purchase.should_exclude_product_review?
self.credit_card_id = purchase.credit_card_id
save!
create_purchase_event(purchase)
if purchase.was_product_recommended
recommendation_type = original_purchase.recommended_purchase_info.try(:recommendation_type)
original_link = original_purchase.recommended_purchase_info.try(:recommended_by_link)
RecommendedPurchaseInfo.create!(purchase:,
recommended_link: link,
recommended_by_link: original_link,
recommendation_type:,
is_recurring_purchase: true,
discover_fee_per_thousand: original_purchase.discover_fee_per_thousand)
end
end
def handle_purchase_failure(purchase)
CustomerLowPriorityMailer.subscription_card_declined(id).deliver_later(queue: "low")
ChargeDeclinedReminderWorker.perform_in(ALLOWED_TIME_BEFORE_FAIL_AND_UNSUBSCRIBE - CHARGE_DECLINED_REMINDER_EMAIL, id)
# schedule for termination 5 days after subscription is overdue for a charge
UnsubscribeAndFailWorker.perform_in(terminate_by > (Time.current + 1.minute) ? terminate_by : 1.minute, id)
purchase.mark_failed!
end
# Public: Charge the user and create a new purchase
# Returns the new `Purchase` object
def charge!(override_params: {}, from_failed_charge_email: false, off_session: true)
purchase = build_purchase(override_params:, from_failed_charge_email:)
process_purchase!(purchase, from_failed_charge_email, off_session:)
end
def schedule_charge(scheduled_time)
RecurringChargeWorker.perform_at(scheduled_time, id)
Rails.logger.info("Scheduled RecurringChargeWorker(#{id}) to run at #{scheduled_time}")
end
def schedule_renewal_reminder
return unless send_renewal_reminders?
RecurringChargeReminderWorker.perform_at(send_renewal_reminder_at, id)
end
def send_renewal_reminders?
Feature.active?(:membership_renewal_reminders, seller)
end
def unsubscribe_and_fail!
with_lock do
return if failed_at.present?
was_recently_failed = purchases.failed.where("created_at > ?", ALLOWED_TIME_BEFORE_SENDING_REPEATED_CANCELLATION_EMAIL_TO_CREATOR.ago).exists?
self.failed_at = Time.current
self.deactivate!
CustomerLowPriorityMailer.subscription_autocancelled(id).deliver_later(queue: "low")
if seller.enable_payment_email? && !was_recently_failed
ContactingCreatorMailer.subscription_autocancelled(id).deliver_later(queue: "critical")
end
send_cancelled_notification_webhook
end
end
def cancel!(by_seller: true, by_admin: false)
with_lock do
return if cancelled_at.present?
self.user_requested_cancellation_at = Time.current
self.cancelled_at = end_time_of_subscription
self.cancelled_by_buyer = !by_seller
self.cancelled_by_admin = by_admin
save!
if cancelled_by_buyer?
CustomerLowPriorityMailer.subscription_cancelled(id).deliver_later(queue: "low")
ContactingCreatorMailer.subscription_cancelled_by_customer(id).deliver_later(queue: "critical") if seller.enable_payment_email?
else
CustomerLowPriorityMailer.subscription_cancelled_by_seller(id).deliver_later(queue: "low")
ContactingCreatorMailer.subscription_cancelled(id).deliver_later(queue: "critical") if seller.enable_payment_email?
end
send_cancelled_notification_webhook
end
end
def deactivate!
self.deactivated_at = Time.current
save!
original_purchase&.remove_from_audience_member_details
after_commit do
DeactivateIntegrationsWorker.perform_async(original_purchase.id)
end
schedule_member_cancellation_workflow_jobs if cancelled?
end
# Cancels subscription immediately, cancelled_at is now instead of at end of billing period. There are 2 cases for this,
# product deletion and chargeback(by_buyer). If chargeback, don't send the email and mark cancelled_by_buyer as true.
def cancel_effective_immediately!(by_buyer: false)
with_lock do
self.user_requested_cancellation_at = Time.current
self.cancelled_at = Time.current
self.cancelled_by_buyer = by_buyer
self.deactivate!
send_cancelled_notification_webhook
CustomerLowPriorityMailer.subscription_product_deleted(id).deliver_later(queue: "low") unless by_buyer
end
end
def end_subscription!
with_lock do
return if ended_at.present?
self.ended_at = Time.current
self.deactivate!
CustomerLowPriorityMailer.subscription_ended(id).deliver_later(queue: "low")
ContactingCreatorMailer.subscription_ended(id).deliver_later(queue: "critical") if seller.enable_payment_email?
end
end
# creates a new original subscription purchase & archives the existing one.
# Any changes to the subscription made here must be reverted in `Subscription::UpdaterService#restore_original_purchase`
def update_current_plan!(new_variants:, new_price:, new_quantity: nil, perceived_price_cents: nil, is_applying_plan_change: false, skip_preparing_for_charge: false)
raise Subscription::UpdateFailed, "Installment plans cannot be updated." if is_installment_plan?
raise Subscription::UpdateFailed, "Changing plans for fixed-length subscriptions is not currently supported." if has_fixed_length?
ActiveRecord::Base.transaction do
payment_option = last_payment_option
# build new original subscription purchase
new_purchase = build_purchase(override_params: { is_original_subscription_purchase: true,
email: original_purchase.email,
is_free_trial_purchase: original_purchase.is_free_trial_purchase })
# avoid failing `Purchase#variants_available` validation if reverting back to the original set of variants & those variants are unavailable
new_purchase.original_variant_attributes = original_purchase.variant_attributes
# avoid failing `Purchase#price_not_too_low` validation if reverting back to the original subscription price & price has been deleted
new_purchase.original_price = price
# avoid `Purchase#not_double_charged` and sold out validations
new_purchase.is_updated_original_subscription_purchase = true
# avoid price validation failures when applying a pre-existing plan change (i.e. a downgrade)
new_purchase.is_applying_plan_change = is_applying_plan_change
# avoid preparing chargeable, in cases where we simply want to calculate the new price
new_purchase.skip_preparing_for_charge = skip_preparing_for_charge
new_purchase.variant_attributes = link.is_tiered_membership? ? new_variants : original_purchase.variant_attributes
new_purchase.is_original_subscription_purchase = true
new_purchase.perceived_price_cents = perceived_price_cents
new_purchase.price_range = perceived_price_cents.present? ? perceived_price_cents / (link.single_unit_currency? ? 1 : 100.0) : nil
new_purchase.business_vat_id = original_purchase.purchase_sales_tax_info&.business_vat_id
new_purchase.quantity = new_quantity if new_quantity.present?
original_purchase.purchase_custom_fields.each { new_purchase.purchase_custom_fields << _1.dup }
license = original_purchase.license
license.purchase = new_purchase if license.present?
# update price
self.price = new_price
payment_option.price = new_price
payment_option.save!
# archive old original subscription purchase
original_purchase.is_archived_original_subscription_purchase = true
original_purchase.save!
if new_purchase.offer_code.present? && original_discount = original_purchase.purchase_offer_code_discount
new_purchase.build_purchase_offer_code_discount(offer_code: new_purchase.offer_code, offer_code_amount: original_discount.offer_code_amount,
offer_code_is_percent: original_discount.offer_code_is_percent,
pre_discount_minimum_price_cents: new_purchase.minimum_paid_price_cents_per_unit_before_discount)
end
if original_purchase.recommended_purchase_info.present?
original_recommended_purchase_info = original_purchase.recommended_purchase_info
new_purchase.build_recommended_purchase_info({
recommended_link_id: original_recommended_purchase_info.recommended_link_id,
recommended_by_link_id: original_recommended_purchase_info.recommended_by_link_id,
recommendation_type: original_recommended_purchase_info.recommendation_type,
discover_fee_per_thousand: original_recommended_purchase_info.discover_fee_per_thousand,
is_recurring_purchase: original_recommended_purchase_info.is_recurring_purchase
})
end
# update price, fees, etc. on new purchase
new_purchase.prepare_for_charge!
raise Subscription::UpdateFailed, new_purchase.errors.full_messages.first if new_purchase.errors.present?
# update email infos once new_purchase is successfully saved
email_infos = original_purchase.email_infos
email_infos.each { |email| email.update!(purchase_id: new_purchase.id) }
# update the purchase associated with comments
Comment.where(purchase: original_purchase).update_all(purchase_id: new_purchase.id)
# new original subscription purchase will never be charged and should not
# be treated as a 'successful' purchase in most instances
if new_purchase.is_test_purchase?
new_purchase.mark_test_successful!
elsif !new_purchase.not_charged?
new_purchase.mark_not_charged!
end
new_purchase.create_url_redirect!
create_purchase_event(new_purchase, template_purchase: original_purchase)
new_purchase
end
end
def for_tier?(product_tier)
tier == product_tier || latest_plan_change&.tier == product_tier
end
def cancelled_or_failed?
cancelled_at.present? || failed_at.present?
end
def ended?
ended_at.present?
end
def pending_cancellation?
alive? && cancelled_at.present?
end
def cancelled?(treat_pending_cancellation_as_live: true)
!alive?(include_pending_cancellation: treat_pending_cancellation_as_live) && cancelled_at.present?
end
def deactivated?
deactivated_at.present?
end
def cancelled_by_seller?
cancelled?(treat_pending_cancellation_as_live: false) && !cancelled_by_buyer?
end
def first_successful_charge
successful_purchases.first
end
def last_successful_charge
successful_purchases.last
end
def last_successful_charge_at
last_successful_charge&.succeeded_at
end
def last_purchase
last_successful_charge || purchases.is_free_trial_purchase.last
end
def last_purchase_at
last_purchase&.succeeded_at || last_purchase&.created_at
end
def end_time_of_subscription
return free_trial_ends_at if free_trial_ends_at.present? && last_purchase&.is_free_trial_purchase?
return end_time_of_last_paid_period if end_time_of_last_paid_period.present? && end_time_of_last_paid_period > Time.current
return Time.current if purchases.last.chargedback_not_reversed_or_refunded? || last_purchase_at.nil?
last_purchase_at + period
end
def end_time_of_last_paid_period
if last_successful_not_reversed_or_refunded_charge_at.present?
last_successful_not_reversed_or_refunded_charge_at + period
else
free_trial_ends_at
end
end
def expected_completion_time
return nil unless has_fixed_length?
end_time_of_last_paid_period + period * remaining_charges_count
end
def send_renewal_reminder_at
[end_time_of_subscription - BasePrice::Recurrence.renewal_reminder_email_days(recurrence), Time.current].max
end
def overdue_for_charge?
end_time_of_subscription <= Time.current
end
def seconds_overdue_for_charge
return 0 unless overdue_for_charge? && end_time_of_last_paid_period.present?
(Time.current - end_time_of_last_paid_period).to_i
end
def has_a_charge_in_progress?
purchases.in_progress.exists?
end
# How much of a discount the user will receive when upgrading to a more
# expensive plan, based on the time remaining in the current billing period.
# Defaults to calculating time remaining as of the end of today.
def prorated_discount_price_cents(calculate_as_of: Time.current.end_of_day)
return 0 if last_successful_charge_at.nil?
seconds_since_last_billed = calculate_as_of - last_successful_charge_at
percent_of_current_period_remaining = [(current_billing_period_seconds - seconds_since_last_billed), 0].max / current_billing_period_seconds
(percent_of_current_period_remaining * original_purchase.displayed_price_cents).round
end
def current_billing_period_seconds
return 0 unless last_purchase_at.present?
(end_time_of_subscription - last_purchase_at).to_i
end
def formatted_end_time_of_subscription
formatted_time = end_time_of_subscription
formatted_time = formatted_time.in_time_zone(user.timezone) if user
formatted_time.to_fs(:formatted_date_full_month)
end
def recurrence
return price.recurrence unless is_installment_plan
return last_payment_option.installment_plan.recurrence unless last_payment_option&.installment_plan_snapshot
last_payment_option.installment_plan_snapshot.recurrence
end
def period
BasePrice::Recurrence.seconds_in_recurrence(recurrence)
end
def subscription_mobile_json_data
return nil unless alive?
json_data = link.as_json(mobile: true)
subscription_data = {
subscribed_at: created_at,
external_id:,
recurring_amount: original_purchase.formatted_display_price
}
json_data[:subscription_data] = subscription_data
purchase = original_purchase
if purchase
json_data[:purchase_id] = purchase.external_id
json_data[:purchased_at] = purchase.created_at
json_data[:user_id] = purchase.purchaser.external_id if purchase.purchaser
json_data[:can_contact] = purchase.can_contact
end
json_data[:updates_data] = updates_mobile_json_data
json_data
end
def updates_mobile_json_data
original_purchase.product_installments.map { |installment| installment.installment_mobile_json_data(purchase: original_purchase, subscription: self) }
end
# Returns true if no new charge is needed else false
def resubscribe!
with_lock do
now = Time.current
pending_cancellation = cancelled_at.present? && cancelled_at > now
is_deactivated = deactivated_at.present?
self.user_requested_cancellation_at = nil
self.cancelled_at = nil
self.deactivated_at = nil
self.cancelled_by_admin = false
self.cancelled_by_buyer = false
self.failed_at = nil unless pending_cancellation
save!
original_purchase&.add_to_audience_member_details
if is_deactivated
# Calculate by how much time do we need to delay the workflow installments
send_delay = (now - last_deactivated_at).to_i
original_purchase.reschedule_workflow_installments(send_delay:)
after_commit do
ActivateIntegrationsWorker.perform_async(original_purchase.id)
end
end
pending_cancellation ? true : false
end
end
def last_resubscribed_at
if defined?(@_last_resubscribed_at)
@_last_resubscribed_at
else
@_last_resubscribed_at = subscription_events.restarted
.order(occurred_at: :desc)
.take
&.occurred_at
end
end
def last_deactivated_at
return deactivated_at if deactivated_at.present?
if defined?(@_last_deactivated_at)
@_last_deactivated_at
else
@_last_deactivated_at = subscription_events.deactivated
.order(occurred_at: :desc)
.take
&.occurred_at
end
end
def send_restart_notifications!(reason = nil)
CustomerMailer.subscription_restarted(id, reason).deliver_later(queue: "critical")
ContactingCreatorMailer.subscription_restarted(id).deliver_later(queue: "critical")
send_restarted_notification_webhook
end
def resubscribed?
last_resubscribed_at.present? && last_deactivated_at.present?
end
def has_fixed_length?
charge_occurrence_count.present?
end
def charges_completed?
has_fixed_length? && purchases.successful.count == charge_occurrence_count
end
def remaining_charges_count
has_fixed_length? ? charge_occurrence_count - purchases.successful.count : 0
end
# Certain events should transition the subscription from pending cancellation to cancelled thus not allowing the customer access to updates.
def cancel_immediately_if_pending_cancellation!
with_lock do
return unless pending_cancellation?
self.cancelled_at = Time.current
self.deactivate!
end
end
def termination_date
(ended_at || cancelled_at || failed_at || deactivated_at).try(:to_date)
end
def termination_reason
return unless deactivated_at.present?
if failed_at.present?
"failed_payment"
elsif ended_at.present?
"fixed_subscription_period_ended"
elsif cancelled_at.present?
"cancelled"
end
end
def send_cancelled_notification_webhook
send_notification_webhook(resource_name: ResourceSubscription::CANCELLED_RESOURCE_NAME)
end
def send_ended_notification_webhook
send_notification_webhook(resource_name: ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME)
end
def send_restarted_notification_webhook
params = {
restarted_at: Time.current.as_json
}
send_notification_webhook(resource_name: ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME, params:)
end
def create_interruption_event
event_type = deactivated_at.present? ? :deactivated : :restarted
return if subscription_events.order(:occurred_at, :id).last&.event_type == event_type.to_s
subscription_events.create!(event_type:, occurred_at: deactivated_at || Time.current)
end
def send_updated_notifification_webhook(plan_change_type:, old_recurrence:, new_recurrence:, old_tier:, new_tier:, old_price:, new_price:, effective_as_of:, old_quantity:, new_quantity:)
return unless plan_change_type.in?(["upgrade", "downgrade"])
params = {
type: plan_change_type,
effective_as_of: effective_as_of&.as_json,
old_plan: {
tier: { id: old_tier.external_id, name: old_tier.name },
recurrence: old_recurrence,
price_cents: old_price,
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mexico_bank_account.rb | app/models/mexico_bank_account.rb | # frozen_string_literal: true
class MexicoBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MX"
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{18}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
validate :validate_account_number
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::MEX.alpha2
end
def currency
Currency::MXN
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/call_availability.rb | app/models/call_availability.rb | # frozen_string_literal: true
class CallAvailability < ApplicationRecord
include ExternalId
belongs_to :call, class_name: "Link"
normalizes :start_time, :end_time, with: -> { _1.change(sec: 0) }
validates_presence_of :call, :start_time, :end_time
validate :start_time_is_before_end_time
scope :upcoming, -> { where(end_time: Time.current..) }
scope :ordered_chronologically, -> { order(start_time: :asc, end_time: :asc) }
scope :containing, ->(start_time, end_time) { where("start_time <= ? AND ? <= end_time", start_time, end_time) }
private
def start_time_is_before_end_time
if start_time >= end_time
errors.add(:base, "Start time must be before end time.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/price.rb | app/models/price.rb | # frozen_string_literal: true
class Price < BasePrice
belongs_to :link, optional: true
validates :link, presence: true
validate :recurrence_validation
after_commit :invalidate_product_cache
def as_json(*)
json = {
id: external_id,
price_cents:,
recurrence:
}
if recurrence.present?
recurrence_formatted = " #{recurrence_long_indicator(recurrence)}"
recurrence_formatted += " x #{link.duration_in_months / BasePrice::Recurrence.number_of_months_in_recurrence(recurrence)}" if link.duration_in_months
json[:recurrence_formatted] = recurrence_formatted
end
json
end
private
def recurrence_validation
return unless link&.is_recurring_billing
return if recurrence.in?(ALLOWED_RECURRENCES)
errors.add(:base, "Invalid recurrence")
end
def invalidate_product_cache
link.invalidate_cache if link.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/public_file.rb | app/models/public_file.rb | # frozen_string_literal: true
class PublicFile < ApplicationRecord
include Deletable
DELETE_UNUSED_FILES_AFTER_DAYS = 10
belongs_to :seller, optional: true, class_name: "User"
belongs_to :resource, polymorphic: true
has_one_attached :file
validates :public_id, presence: true, format: { with: /\A[a-z0-9]{16}\z/ }, uniqueness: { case_sensitive: false }
validates :original_file_name, presence: true
validates :display_name, presence: true
before_validation :set_original_file_name
before_validation :set_default_display_name
before_validation :set_file_group_and_file_type
before_validation :set_public_id
scope :attached, -> { with_attached_file.where(active_storage_attachments: { record_type: "PublicFile" }) }
def blob
file&.blob
end
def analyzed?
blob&.analyzed? || false
end
def file_size
blob&.byte_size
end
def metadata
blob&.metadata || {}
end
def scheduled_for_deletion?
scheduled_for_deletion_at.present?
end
def schedule_for_deletion!
update!(scheduled_for_deletion_at: DELETE_UNUSED_FILES_AFTER_DAYS.days.from_now)
end
def self.generate_public_id(max_retries: 10)
retries = 0
candidate = SecureRandom.alphanumeric.downcase
while self.exists?(public_id: candidate)
retries += 1
raise "Failed to generate unique public_id after #{max_retries} attempts" if retries >= max_retries
candidate = SecureRandom.alphanumeric.downcase
end
candidate
end
private
def set_file_group_and_file_type
return if original_file_name.blank?
self.file_type ||= original_file_name.split(".").last
self.file_group ||= FILE_REGEX.find { |_k, v| v.match?(file_type) }&.first&.split("_")&.last
end
def set_original_file_name
return unless file.attached?
self.original_file_name ||= file.filename.to_s
end
def set_default_display_name
return if display_name.present?
return unless file.attached?
self.display_name = original_file_name.split(".").first.presence || "Untitled"
end
def set_public_id
return if public_id.present?
self.public_id = self.class.generate_public_id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/charge_purchase.rb | app/models/charge_purchase.rb | # frozen_string_literal: true
class ChargePurchase < ApplicationRecord
belongs_to :charge
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/purchasing_power_parity_info.rb | app/models/purchasing_power_parity_info.rb | # frozen_string_literal: true
class PurchasingPowerParityInfo < ApplicationRecord
belongs_to :purchase
validates :purchase, presence: true, uniqueness: true
def factor
super / 100.0
end
def factor=(new_factor)
super(new_factor * 100)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/japan_bank_account.rb | app/models/japan_bank_account.rb | # frozen_string_literal: true
class JapanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "JP"
BANK_CODE_FORMAT_REGEX = /\A[0-9]{4}\z/
private_constant :BANK_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]{4,8}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_branch_code
validate :validate_account_number
def routing_number
"#{bank_code}#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::JPN.alpha2
end
def currency
Currency::JPY
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_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/merchant_account.rb | app/models/merchant_account.rb | # frozen_string_literal: true
class MerchantAccount < ApplicationRecord
include Deletable
include ExternalId
include JsonData
include ChargeProcessable
belongs_to :user, optional: true
has_many :purchases
has_many :credits
has_many :balances
has_many :balance_transactions
has_many :charges
attr_json_data_accessor :meta
validates :charge_processor_id, presence: true
validates :charge_processor_merchant_id, presence: true, if: -> { user && charge_processor_alive? }
validates :charge_processor_merchant_id, uniqueness: { case_sensitive: true, message: "This account is already connected with another Gumroad account" }, allow_blank: true, if: proc { |ma| ma.is_a_gumroad_managed_stripe_account? }
scope :charge_processor_alive, -> { where.not(charge_processor_alive_at: nil).where(charge_processor_deleted_at: nil) }
scope :charge_processor_verified, -> { where.not(charge_processor_verified_at: nil) }
scope :charge_processor_unverified, -> { where(charge_processor_verified_at: nil) }
scope :charge_processor_deleted, -> { where.not(charge_processor_deleted_at: nil) }
scope :paypal, -> { where(charge_processor_id: PaypalChargeProcessor.charge_processor_id) }
scope :stripe, -> { where(charge_processor_id: StripeChargeProcessor.charge_processor_id) }
scope :stripe_connect, -> { stripe.where("json_data->>'$.meta.stripe_connect' = 'true'").where.not(user_id: nil) } # Logic should match method `#is_a_stripe_connect_account?`
# Public: Get Gumroad's merchant account on the charge processor.
#
# charge_processor_id β The charge processor to get a MerchantAccount for.
#
# Returns a MerchantAccount which is Gumroad's merchant account on the given charge processor.
def self.gumroad(charge_processor_id)
where(user_id: nil, charge_processor_id:).first
end
def is_managed_by_gumroad?
!user_id
end
def can_accept_charges?
!stripe_charge_processor? ||
is_a_stripe_connect_account? ||
Country.new(country).can_accept_stripe_charges?
end
# Logic should match `.stripe_connect` scope
def is_a_stripe_connect_account?
stripe_charge_processor? &&
user_id.present? &&
json_data.dig("meta", "stripe_connect") == "true"
end
def is_a_brazilian_stripe_connect_account?
is_a_stripe_connect_account? && country == Compliance::Countries::BRA.alpha2
end
def is_a_paypal_connect_account?
paypal_charge_processor?
end
def is_a_gumroad_managed_stripe_account?
stripe_charge_processor? && json_data.dig("meta", "stripe_connect") != "true"
end
# Public: Returns who holds the funds for charges created for this merchant account.
def holder_of_funds
if charge_processor_id.in?(ChargeProcessor.charge_processor_ids)
ChargeProcessor.holder_of_funds(self)
else
# Assume we hold the funds for removed charge processors
HolderOfFunds::GUMROAD
end
end
def delete_charge_processor_account!
mark_deleted!
self.meta = {} unless is_a_stripe_connect_account?
self.charge_processor_deleted_at = Time.current
self.charge_processor_alive_at = nil
self.charge_processor_verified_at = nil
save!
end
def charge_processor_delete!
case charge_processor_id
when StripeChargeProcessor.charge_processor_id
StripeMerchantAccountManager.delete_account(self)
else
raise NotImplementedError
end
end
def active?
alive? && charge_processor_alive?
end
def charge_processor_alive?
charge_processor_alive_at.present? && !charge_processor_deleted?
end
alias_method :charge_processor_alive, :charge_processor_alive?
def charge_processor_verified?
charge_processor_verified_at.present?
end
def charge_processor_unverified?
charge_processor_verified_at.nil?
end
def charge_processor_deleted?
charge_processor_deleted_at.present?
end
def mark_charge_processor_verified!
return if charge_processor_verified?
self.charge_processor_verified_at = Time.current
save!
end
def mark_charge_processor_unverified!
return if charge_processor_unverified?
self.charge_processor_verified_at = nil
save!
end
def paypal_account_details
payment_integration_api = PaypalIntegrationRestApi.new(user, authorization_header: PaypalPartnerRestCredentials.new.auth_token)
paypal_response = payment_integration_api.get_merchant_account_by_merchant_id(charge_processor_merchant_id)
if paypal_response.success?
parsed_response = paypal_response.parsed_response
# Special handling for China as PayPal returns country code as C2 instead of CN
parsed_response["country"] = "CN" if paypal_response["country"] == "C2"
parsed_response
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/panama_bank_account.rb | app/models/panama_bank_account.rb | # frozen_string_literal: true
class PanamaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "PA"
BANK_CODE_FORMAT_REGEX = /^[A-Z]{4}PAPA[A-Z0-9]{3}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,18}$/
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::PAN.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 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/australian_bank_account.rb | app/models/australian_bank_account.rb | # frozen_string_literal: true
class AustralianBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AUSTRALIAN"
# BSB Number Format:
# β’Β 2 digits to identify bank
# β’Β 1 digit to identify state
# β’ 3 digits to identify branch
BSB_NUMBER_FORMAT_REGEX = /^[0-9]{6}$/
private_constant :BSB_NUMBER_FORMAT_REGEX
alias_attribute :bsb_number, :bank_number
validate :validate_bsb_number
def routing_number
bsb_number
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::AUS.alpha2
end
def currency
Currency::AUD
end
def to_hash
super.merge(
bsb_number:
)
end
private
def validate_bsb_number
errors.add :base, "The BSB number is invalid." unless BSB_NUMBER_FORMAT_REGEX.match?(bsb_number)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/albania_bank_account.rb | app/models/albania_bank_account.rb | # frozen_string_literal: true
class AlbaniaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AL"
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::ALB.alpha2
end
def currency
Currency::ALL
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/bangladesh_bank_account.rb | app/models/bangladesh_bank_account.rb | # frozen_string_literal: true
class BangladeshBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BD"
BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){9}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^([0-9a-zA-Z]){13,17}$/
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::BGD.alpha2
end
def currency
Currency::BDT
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/follower.rb | app/models/follower.rb | # frozen_string_literal: true
class Follower < ApplicationRecord
include ExternalId
include TimestampScopes
include Follower::From
include Deletable
include ConfirmedFollowerEvent::FollowerCallbacks
include Follower::AudienceMember
has_paper_trail
belongs_to :user, foreign_key: "followed_id", optional: true
belongs_to :source_product, class_name: "Link", optional: true
validates_presence_of :user
validates_presence_of :email
validates :email, email_format: { message: "invalid." }, if: :email_changed?
validate :not_confirmed_and_deleted
validate :follower_user_id_exists
validate :double_follow_validation, on: :create
scope :confirmed, -> { where.not(confirmed_at: nil) }
scope :active, -> { alive.confirmed }
scope :created_after, ->(start_at) { where("followers.created_at > ?", start_at) if start_at.present? }
scope :created_before, ->(end_at) { where("followers.created_at < ?", end_at) if end_at.present? }
scope :by_external_variant_ids_or_products, ->(external_variant_ids, product_ids) do
return unless external_variant_ids.present? || product_ids.present?
purchases = Purchase.by_external_variant_ids_or_products(external_variant_ids, product_ids)
where(email: purchases.pluck(:email))
end
def mark_deleted!
self.confirmed_at = nil
super
end
def confirm!(schedule_workflow: true)
return if confirmed?
self.confirmed_at = Time.current
self.deleted_at = nil
save!
schedule_workflow_jobs if schedule_workflow && user.workflows.alive.follower_or_audience_type.present?
end
def confirmed?
confirmed_at.present?
end
def unconfirmed?
!confirmed?
end
def follower_user_id_exists
return if follower_user_id.nil?
return if User.find_by(id: follower_user_id).present?
errors.add(:follower_user_id, "Follower's User ID does not map to an existing user")
end
def double_follow_validation
return unless Follower.where(followed_id:, email:).exists?
errors.add(:base, "You are already following this creator.")
end
def follower_email
User.find_by(id: follower_user_id).try(:email).presence || email
end
def schedule_workflow_jobs
workflows = user.workflows.alive.follower_or_audience_type
workflows.each do |workflow|
next unless workflow.new_customer_trigger?
workflow.installments.alive.each do |installment|
installment_rule = installment.installment_rule
next if installment_rule.nil?
SendWorkflowInstallmentWorker.perform_in(installment_rule.delayed_delivery_time,
installment.id, installment_rule.version, nil, id, nil)
end
end
end
def self.unsubscribe(creator_id, email)
follower = where(email:, followed_id: creator_id).last
follower&.mark_deleted!
end
def send_confirmation_email
# Suppress repeated sending of confirmation emails. Allow only 1 email per hour.
Rails.cache.fetch("follower_confirmation_email_sent_#{id}", expires_in: 1.hour) do
FollowerMailer.confirm_follower(followed_id, id).deliver_later(queue: "critical", wait: 3.seconds)
end
end
def imported_from_csv?
source == Follower::From::CSV_IMPORT
end
def as_json(options = {})
pundit_user = options[:pundit_user]
{
id: external_id,
email:,
created_at:,
source:,
formatted_confirmed_on: confirmed_at.to_fs(:formatted_date_full_month),
can_update: pundit_user ? Pundit.policy!(pundit_user, [:audience, self]).update? : false,
}
end
private
def not_confirmed_and_deleted
if confirmed_at.present? && deleted_at.present?
errors.add(:base, "Can't be both confirmed and deleted")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/thumbnail.rb | app/models/thumbnail.rb | # frozen_string_literal: true
class Thumbnail < ApplicationRecord
include Deletable
include CdnUrlHelper
DISPLAY_THUMBNAIL_DIMENSION = 600
MAX_FILE_SIZE = 5.megabytes
ALLOW_CONTENT_TYPES = /jpeg|gif|png|jpg/i
belongs_to :product, class_name: "Link", optional: true
has_one_attached :file
before_create :generate_guid
validate :validate_file
def validate_file
return unless alive? && unsplash_url.blank?
if file.attached?
if !file.image? || !file.content_type.match?(ALLOW_CONTENT_TYPES)
errors.add(:base, "Could not process your thumbnail, please try again.")
elsif file.byte_size > MAX_FILE_SIZE
errors.add(:base, "Could not process your thumbnail, please upload an image with size smaller than 5 MB.")
elsif original_width != original_height
errors.add(:base, "Please upload a square thumbnail.")
elsif original_width.to_i < DISPLAY_THUMBNAIL_DIMENSION || original_height.to_i < DISPLAY_THUMBNAIL_DIMENSION
errors.add(:base, "Could not process your thumbnail, please try again.")
end
else
errors.add(:base, "Could not process your thumbnail, please try again.")
end
end
def alive
alive? ? self : nil
end
def url(variant: :default)
return unsplash_url if unsplash_url.present?
return unless file.attached?
# Don't post process for gifs
return cdn_url_for(file.url) if file.content_type.include?("gif")
case variant
when :default
cdn_url_for(thumbnail_variant.url)
when :original
cdn_url_for(file.url)
else
cdn_url_for(file.url)
end
end
def thumbnail_variant
return unless file.attached?
file.variant(resize_to_limit: [DISPLAY_THUMBNAIL_DIMENSION, DISPLAY_THUMBNAIL_DIMENSION]).processed
end
def as_json(*)
{ url:,
guid:
}
end
private
def original_width
return unless file.attached?
file.metadata["width"]
end
def original_height
return unless file.attached?
file.metadata["height"]
end
def generate_guid
self.guid ||= SecureRandom.hex
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/affiliate.rb | app/models/affiliate.rb | # frozen_string_literal: true
class Affiliate < ApplicationRecord
include ExternalId
include Deletable
include CurrencyHelper
include FlagShihTzu
include AudienceMember, Cookies
self.ignored_columns = %w(archived_at)
QUERY_PARAM = "affiliate_id"
SHORT_QUERY_PARAM = "a"
QUERY_PARAMS = [QUERY_PARAM, SHORT_QUERY_PARAM]
belongs_to :affiliate_user, class_name: "User"
has_many :affiliate_credits
has_many :purchases
has_many :product_affiliates, autosave: true
has_many :products, through: :product_affiliates
has_many :purchases_that_count_towards_volume, -> { counts_towards_volume }, class_name: "Purchase"
scope :created_after, ->(start_at) { where("affiliates.created_at > ?", start_at) if start_at.present? }
scope :created_before, ->(end_at) { where("affiliates.created_at < ?", end_at) if end_at.present? }
has_flags 1 => :apply_to_all_products,
2 => :send_posts,
3 => :dont_show_as_co_creator,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
scope :by_external_variant_ids_or_products, ->(external_variant_ids, product_ids) do
return unless external_variant_ids.present? || product_ids.present?
purchases = Purchase.by_external_variant_ids_or_products(external_variant_ids, product_ids)
joins(:affiliate_user).where(affiliate_user: { email: purchases.pluck(:email) })
end
scope :direct_affiliates, -> { where(type: DirectAffiliate.name) }
scope :global_affiliates, -> { where(type: GlobalAffiliate.name) }
scope :direct_or_global_affiliates, -> { where(type: [DirectAffiliate.name, GlobalAffiliate.name]) }
scope :pending_collaborators, -> { merge(Collaborator.invitation_pending) }
scope :confirmed_collaborators, -> { merge(Collaborator.invitation_accepted) }
scope :pending_or_confirmed_collaborators, -> { where(type: Collaborator.name) }
scope :for_product, ->(product) do
affiliates_relation = Affiliate.joins("LEFT OUTER JOIN affiliates_links ON affiliates_links.affiliate_id = affiliates.id").where("affiliates_links.link_id = ?", product.id).direct_affiliates
affiliates_relation = affiliates_relation.or(Affiliate.global_affiliates) if product.recommendable?
affiliates_relation
end
# Logic in `valid_for_product` scope should match logic in `eligible_for_purchase_credit?` methods
scope :valid_for_product, ->(product) { for_product(product).alive.joins(:affiliate_user).merge(User.not_suspended) }
validate :eligible_for_stripe_payments
def enabled_products
product_affiliates
.joins(:product)
.merge(Link.alive)
.select("affiliates_links.*, links.unique_permalink, links.name")
.map do
{
id: ObfuscateIds.encrypt_numeric(_1.link_id),
name: _1.name,
fee_percent: _1.affiliate_percentage || affiliate_percentage,
destination_url: _1.destination_url,
referral_url: construct_permalink(_1.unique_permalink)
}
end
end
def affiliate_info
{
id: external_id,
email: affiliate_user.email,
destination_url:,
affiliate_user_name: affiliate_user.display_name(prefer_email_over_default_username: true),
fee_percent: affiliate_percentage,
}
end
def referral_url
"#{PROTOCOL}://#{ROOT_DOMAIN}/a/#{external_id_numeric}"
end
def referral_url_for_product(product)
construct_permalink(product.unique_permalink)
end
def affiliate_percentage
return if affiliate_basis_points.nil?
affiliate_basis_points / 100
end
def basis_points(*)
affiliate_basis_points
end
def collaborator?
type == Collaborator.name
end
def global?
type == GlobalAffiliate.name
end
def total_cents_earned_formatted
formatted_dollar_amount(total_cents_earned, with_currency: affiliate_user.should_be_shown_currencies_always?)
end
def total_cents_earned
purchases.paid.not_chargedback_or_chargedback_reversed.sum(:affiliate_credit_cents)
end
def eligible_for_credit?
alive? && !affiliate_user.suspended? && !affiliate_user.has_brazilian_stripe_connect_account?
end
private
def construct_permalink(unique_permalink)
"#{referral_url}/#{unique_permalink}"
end
def eligible_for_stripe_payments
errors.add(:base, "This user cannot be added as #{collaborator? ? "a collaborator" : "an affiliate"} because they use a Brazilian Stripe account.") if affiliate_user&.has_brazilian_stripe_connect_account?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/singaporean_bank_account.rb | app/models/singaporean_bank_account.rb | # frozen_string_literal: true
class SingaporeanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "SG"
BANK_CODE_FORMAT_REGEX = /\A[0-9]{4}\z/
private_constant :BANK_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,19}\z/
private_constant :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_branch_code
validate :validate_account_number
def routing_number
"#{bank_code}-#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::SGP.alpha2
end
def currency
Currency::SGD
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_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/seller_profile_wishlists_section.rb | app/models/seller_profile_wishlists_section.rb | # frozen_string_literal: true
class SellerProfileWishlistsSection < SellerProfileSection
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/subtitle_file.rb | app/models/subtitle_file.rb | # frozen_string_literal: true
class SubtitleFile < ApplicationRecord
include S3Retrievable, ExternalId, JsonData, Deletable, CdnDeletable
VALID_FILE_TYPE_REGEX = /\A.+\.(srt|sub|sbv|vtt)\z/
has_paper_trail
belongs_to :product_file, optional: true
validates_presence_of :product_file, :url
validate :ensure_valid_file_type, unless: :deleted?
has_s3_fields :url
after_commit :schedule_calculate_size, on: :create
def user
product_file.try(:user)
end
def mark_deleted
self.deleted_at = Time.current
end
def size_displayable
ActionController::Base.helpers.number_to_human_size(size)
end
def calculate_size
self.size = s3_object.content_length
save!
end
def schedule_calculate_size
SubtitleFileSizeWorker.perform_in(5.seconds, id)
end
def has_alive_duplicate_files?
SubtitleFile.alive.where(url:).exists?
end
private
def ensure_valid_file_type
return if url.match?(VALID_FILE_TYPE_REGEX)
errors.add(:base, "Subtitle type not supported. Please upload only subtitles with extension .srt, .sub, .sbv, or .vtt.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_page_view.rb | app/models/product_page_view.rb | # frozen_string_literal: true
class ProductPageView
include Elasticsearch::Model
index_name "product_page_views"
def self.index_name_from_body(body)
USE_ES_ALIASES ? "#{index_name}-#{body["timestamp"].first(7)}" : index_name
end
settings number_of_shards: 1, number_of_replicas: 0
mapping dynamic: :strict do
indexes :product_id, type: :long
indexes :country, type: :keyword
indexes :state, type: :keyword
indexes :referrer_domain, type: :keyword
indexes :timestamp, type: :date
indexes :seller_id, type: :long
indexes :user_id, type: :long
indexes :ip_address, type: :keyword
indexes :url, type: :keyword
indexes :browser_guid, type: :keyword
indexes :browser_fingerprint, type: :keyword
indexes :referrer, type: :keyword
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/computed_sales_analytics_day.rb | app/models/computed_sales_analytics_day.rb | # frozen_string_literal: true
class ComputedSalesAnalyticsDay < ApplicationRecord
def self.read_data_from_keys(keys)
with_empty_values = keys.zip([nil]).to_h
with_existing_values = where(key: keys).order(:key).pluck(:key, :data).to_h do |(key, data)|
[key, JSON.parse(data)]
end
with_empty_values.merge(with_existing_values)
end
def self.fetch_data_from_key(key)
record = find_by(key:)
return JSON.parse(record.data) if record
record = new
record.key = key
record.data = yield.to_json
record.save!
JSON.parse(record.data)
end
def self.upsert_data_from_key(key, data)
record = find_by(key:) || new
record.key ||= key
record.data = data.to_json
record.save!
record
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/third_party_analytic.rb | app/models/third_party_analytic.rb | # frozen_string_literal: true
class ThirdPartyAnalytic < ApplicationRecord
include ExternalId
include Deletable
belongs_to :user, optional: true
belongs_to :link, optional: true
validates :user, presence: true
after_commit :clear_related_products_cache
scope :universal, -> { where("link_id is null") }
FOR_ALL_PRODUCTS = "#all_products"
LOCATIONS = ["all", "product", "receipt"]
class ThirdPartyAnalyticInvalid < StandardError
end
def self.save_third_party_analytics(analytics_params, seller)
existing_analytics = seller.third_party_analytics.alive
keep_analytics = []
if analytics_params.empty?
existing_analytics.each(&:mark_deleted)
return []
end
product_hash = Hash.new { |hash, key| hash[key] = {} }
analytics_params.each do |third_party_analytic|
product = product_from_permalink(third_party_analytic[:product])
raise ThirdPartyAnalyticInvalid, "Only one analytics block is allowed per product. Please consolidate your tracking segments by pasting them into in a single block." if product_hash[third_party_analytic[:location]][product.try(:id)]
product_hash[third_party_analytic[:location]][product.try(:id)] = true
end
analytics_params.each do |third_party_analytic|
product = product_from_permalink(third_party_analytic[:product])
if third_party_analytic[:id].present?
analytics = seller.third_party_analytics.alive.find_by_external_id(third_party_analytic[:id])
next if analytics.nil?
analytics.link = product if analytics.link != product
analytics.name = third_party_analytic[:name] if third_party_analytic[:name].present?
analytics.location = third_party_analytic[:location] if third_party_analytic[:location].present?
analytics.analytics_code = third_party_analytic[:code] if analytics.analytics_code != third_party_analytic[:code]
analytics.save!
else
analytics = seller.third_party_analytics.create!(analytics_code: third_party_analytic[:code], name: third_party_analytic[:name], location: third_party_analytic[:location], link: product)
end
keep_analytics << analytics
end
(existing_analytics - keep_analytics).each(&:mark_deleted)
keep_analytics.map(&:external_id)
end
def self.product_from_permalink(permalink)
permalink == FOR_ALL_PRODUCTS ? nil : Link.find_by(unique_permalink: permalink)
end
def clear_related_products_cache
user.clear_products_cache
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/event.rb | app/models/event.rb | # frozen_string_literal: true
class Event < ApplicationRecord
include TimestampScopes
include FlagShihTzu
# Events with names listed below are created and kept forever.
# We also create events that aren't in this list if they have a user_id (see Events#created_event),
# but they're automatically deleted after a while (see DeleteOldUnusedEventsWorker).
PERMITTED_NAMES = %w[
audience_callout_dismissal
chargeback
first_purchase_on_profile_visit
post_view
product_refund_policy_fine_print_view
purchase
service_charge
settlement_declined
refund
]
PERMITTED_NAMES.each do |name|
const_set("NAME_#{name.upcase}", name)
end
has_one :installment_event
belongs_to :purchase, optional: true
belongs_to :service_charge, optional: true
has_flags 1 => :from_profile,
2 => :was_product_recommended,
3 => :is_recurring_subscription_charge,
4 => :manufactured,
5 => :on_custom_domain,
6 => :from_multi_overlay,
7 => :from_seo,
:column => "visit_id",
:flag_query_mode => :bit_operator,
check_for_column: false
attr_accessor :extra_features
with_options if: -> { event_name == NAME_PURCHASE } do
validates_presence_of :purchase_id, :link_id
end
scope :by_browser_guid, ->(guid) { where(browser_guid: guid) }
scope :by_ip_address, ->(ip) { where(ip_address: ip) }
scope :purchase, -> { where(event_name: NAME_PURCHASE) }
scope :service_charge, -> { where(event_name: NAME_SERVICE_CHARGE) }
scope :link_view, -> { where(event_name: "link_view") }
scope :post_view, -> { where(event_name: NAME_POST_VIEW) }
scope :service_charge_successful, -> { service_charge.where(purchase_state: "successful") }
scope :purchase_successful, -> { purchase.where(purchase_state: "successful") }
scope :not_refunded, -> { purchase_successful.where("events.refunded is null or events.refunded = 0") }
scope :for_products, ->(products) { where(link_id: products) }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/direct_affiliate.rb | app/models/direct_affiliate.rb | # frozen_string_literal: true
class DirectAffiliate < Affiliate
include Affiliate::BasisPointsValidations
include Affiliate::DestinationUrlValidations
include Affiliate::Sorting
AFFILIATE_COOKIE_LIFETIME_DAYS = 30
attr_accessor :prevent_sending_invitation_email, :prevent_sending_invitation_email_to_seller
belongs_to :seller, class_name: "User"
has_and_belongs_to_many :products, class_name: "Link", join_table: "affiliates_links", foreign_key: "affiliate_id", after_add: :update_audience_member_with_added_product, after_remove: :update_audience_member_with_removed_product
validates :affiliate_basis_points, presence: true
validate :destination_url_or_username_required
validate :affiliate_basis_points_must_fall_in_an_acceptable_range
validate :eligible_for_stripe_payments
after_commit :send_invitation_email, on: :create
validates_uniqueness_of :affiliate_user_id, scope: :seller_id, conditions: -> { alive }, if: :alive?
def self.cookie_lifetime
AFFILIATE_COOKIE_LIFETIME_DAYS.days
end
def final_destination_url(product: nil)
product = products.last if !apply_to_all_products && product_affiliates.one?
product_affiliate = product_affiliates.find_by(link_id: product.id) if product.present?
product_destination_url = product_affiliate&.destination_url
if product_destination_url.present?
product_destination_url
elsif apply_to_all_products && destination_url.present?
destination_url
elsif product_affiliate.present?
product.long_url
else
seller.subdomain_with_protocol || products.last&.long_url
end
end
def as_json(options = {})
affiliated_products = enabled_products
affiliate_info.merge(
products: affiliated_products,
apply_to_all_products: affiliated_products.all? { _1[:fee_percent] == affiliate_percentage } && affiliated_products.length == seller.links.alive.count,
product_referral_url: product_affiliates.one? ? referral_url_for_product(products.first) : referral_url)
end
def product_sales_info
affiliate_credits
.where(link_id: products.map(&:id))
.joins(:purchase)
.merge(Purchase.counts_towards_volume)
.select("sum(purchases.price_cents) as volume_cents, count(purchases.id) as sales_count, affiliate_credits.link_id")
.group("affiliate_credits.link_id")
.each_with_object({}) { |credit, mapping| mapping[ObfuscateIds.encrypt_numeric(credit.link_id)] = { volume_cents: credit.volume_cents, sales_count: credit.sales_count } }
end
def products_data
product_affiliates = self.product_affiliates.to_a
credits = affiliate_credits.where(link_id: product_affiliates.map(&:link_id))
.joins(:purchase)
.merge(Purchase.counts_towards_volume)
.select("sum(purchases.price_cents) as volume_cents, count(purchases.id) as sales_count, affiliate_credits.link_id")
.group("affiliate_credits.link_id")
seller.links.alive.not_is_collab.map do |product|
credit = credits.find { _1.link_id == product.id }
product_affiliate = product_affiliates.find { _1.link_id == product.id }
next if product.archived? && product_affiliate.blank?
{
id: product.external_id_numeric,
enabled: product_affiliate.present?,
name: product.name,
volume_cents: credit&.volume_cents || 0,
sales_count: credit&.sales_count || 0,
fee_percent: product_affiliate&.affiliate_percentage || affiliate_percentage,
referral_url: referral_url_for_product(product),
destination_url: product_affiliate&.destination_url,
}
end.compact.sort_by { |product| [product[:enabled] ? 0 : 1, -product[:volume_cents]] }
end
def total_amount_cents
affiliate_credits.where(link_id: products.map(&:id))
.joins(:purchase)
.merge(Purchase.counts_towards_volume)
.sum(:price_cents)
end
def schedule_workflow_jobs
workflows = seller.workflows.alive.affiliate_or_audience_type
workflows.each do |workflow|
next unless workflow.new_customer_trigger?
workflow.installments.alive.each do |installment|
installment_rule = installment.installment_rule
next if installment_rule.nil?
SendWorkflowInstallmentWorker.perform_in(installment_rule.delayed_delivery_time,
installment.id, installment_rule.version, nil, nil, affiliate_user.id)
end
end
end
def update_posts_subscription(send_posts:)
seller.direct_affiliates.where(affiliate_user_id:).update(send_posts:)
end
def eligible_for_purchase_credit?(product:, **opts)
return false unless eligible_for_credit?
return false if opts[:was_recommended]
return false if seller.has_brazilian_stripe_connect_account?
products.include?(product)
end
def basis_points(product_id: nil)
return affiliate_basis_points if apply_to_all_products || product_id.blank?
product_affiliates.find_by(link_id: product_id)&.affiliate_basis_points || affiliate_basis_points
end
private
def destination_url_or_username_required
return if destination_url.present? || seller&.username.present?
errors.add(:base, "Please either provide a destination URL or add a username to your Gumroad account.") if products.length > 1 # .length so that we get the right number when self isn't saved.
end
def send_invitation_email
return if prevent_sending_invitation_email
AffiliateMailer.direct_affiliate_invitation(id, prevent_sending_invitation_email_to_seller).deliver_later(wait: 3.seconds)
end
def eligible_for_stripe_payments
super
return unless seller.present? && seller.has_brazilian_stripe_connect_account?
errors.add(:base, "You cannot add an affiliate because you are using a Brazilian Stripe account.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/saint_lucia_bank_account.rb | app/models/saint_lucia_bank_account.rb | # frozen_string_literal: true
class SaintLuciaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "LC"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{1,32}$/
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::LCA.alpha2
end
def currency
Currency::XCD
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/moldova_bank_account.rb | app/models/moldova_bank_account.rb | # frozen_string_literal: true
class MoldovaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MD"
BANK_CODE_FORMAT_REGEX = /^[A-Z0-9]{4}MD[A-Z0-9]{5}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^MD\d{2}[A-Z0-9]{20}$/
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::MDA.alpha2
end
def currency
Currency::MDL
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/variant_price.rb | app/models/variant_price.rb | # frozen_string_literal: true
class VariantPrice < BasePrice
belongs_to :variant, optional: true
validates :variant, presence: true
validate :recurrence_validation
validate :price_cents_validation
delegate :link, to: :variant
def price_formatted_without_symbol
return "" if price_cents.blank?
display_price_for_price_cents(price_cents, symbol: false)
end
def suggested_price_formatted_without_symbol
return nil if suggested_price_cents.blank?
display_price_for_price_cents(suggested_price_cents, symbol: false)
end
private
def display_price_for_price_cents(price_cents, additional_attrs = {})
attrs = { no_cents_if_whole: true, symbol: true }.merge(additional_attrs)
MoneyFormatter.format(price_cents, variant.link.price_currency_type.to_sym, attrs)
end
def recurrence_validation
return unless recurrence.present?
return if recurrence.in?(ALLOWED_RECURRENCES)
errors.add(:base, "Please provide a valid payment option.")
end
def price_cents_validation
return if price_cents.present?
errors.add(:base, "Please provide a price for all selected payment options.")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/czech_republic_bank_account.rb | app/models/czech_republic_bank_account.rb | # frozen_string_literal: true
class CzechRepublicBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "CZ"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::CZE.alpha2
end
def currency
Currency::CZK
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/malaysia_bank_account.rb | app/models/malaysia_bank_account.rb | # frozen_string_literal: true
class MalaysiaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MY"
BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^([0-9]){5,17}$/
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::MYS.alpha2
end
def currency
Currency::MYR
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/subscription_event.rb | app/models/subscription_event.rb | # frozen_string_literal: true
class SubscriptionEvent < ApplicationRecord
belongs_to :subscription
belongs_to :seller, class_name: "User"
before_validation :assign_seller, on: :create
validates :event_type, :occurred_at, presence: true
validate :consecutive_event_type_not_duplicated
enum event_type: %i[deactivated restarted]
private
def assign_seller
self.seller_id = subscription.seller_id
end
def consecutive_event_type_not_duplicated
return unless subscription.present? && occurred_at.present?
latest_event = subscription.subscription_events.order(:occurred_at, :id).last
return if latest_event.blank? || latest_event.event_type != event_type.to_s
errors.add(:event_type, "already exists as the latest event type")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/ecuador_bank_account.rb | app/models/ecuador_bank_account.rb | # frozen_string_literal: true
class EcuadorBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "EC"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{5,18}\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::ECU.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 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/tos_agreement.rb | app/models/tos_agreement.rb | # frozen_string_literal: true
class TosAgreement < ApplicationRecord
include ExternalId
belongs_to :user, optional: true
validates :user, presence: true
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/uzbekistan_bank_account.rb | app/models/uzbekistan_bank_account.rb | # frozen_string_literal: true
class UzbekistanBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "UZ"
BANK_CODE_FORMAT_REGEX = /^([a-zA-Z0-9]){8,11}$/
BRANCH_CODE_FORMAT_REGEX = /^([0-9]){5}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{5,20}$/
private_constant :BANK_CODE_FORMAT_REGEX, :BRANCH_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_branch_code
validate :validate_account_number
def routing_number
"#{bank_code}-#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::UZB.alpha2
end
def currency
Currency::UZS
end
def account_number_visual
"******#{account_number_last_four}"
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 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/order.rb | app/models/order.rb | # frozen_string_literal: true
class Order < ApplicationRecord
include ExternalId, Orderable, FlagShihTzu
belongs_to :purchaser, class_name: "User", optional: true
has_many :order_purchases, dependent: :destroy
has_many :purchases, through: :order_purchases, dependent: :destroy
has_many :charges, dependent: :destroy
has_one :cart, dependent: :destroy
attr_accessor :setup_future_charges
has_flags 1 => :DEPRECATED_seller_receipt_enabled,
column: "flags",
flag_query_mode: :bit_operator,
check_for_column: false
delegate :card_type, :card_visual, :full_name, to: :purchase_with_payment_as_orderable
after_save :schedule_review_reminder!, if: :should_schedule_review_reminder?
def receipt_for_gift_receiver?
# Ref https://gumroad.slack.com/archives/C01DBV0A257/p1702993001755659?thread_ts=1702968729.055289&cid=C01DBV0A257
# Raise to document the current state so that the caller is aware, rather than returning a Boolean that can
# generate undesired results.
raise NotImplementedError, "Not supported for multi-item orders" if successful_purchases.count > 1
purchase_as_orderable.is_gift_receiver_purchase?
end
def receipt_for_gift_sender?
# Ref https://gumroad.slack.com/archives/C01DBV0A257/p1702993001755659?thread_ts=1702968729.055289&cid=C01DBV0A257
# Raise to document the current state so that the caller is aware, rather than returning a Boolean that can
# generate undesired results.
raise NotImplementedError, "Not supported for multi-item orders" if successful_purchases.count > 1
purchase_as_orderable.is_gift_sender_purchase?
end
def email
purchase_as_orderable.email
end
def locale
purchase_as_orderable.locale
end
def test?
purchase_as_orderable.is_test_purchase?
end
def send_charge_receipts
return unless uses_charge_receipt?
successful_charges.each do
SendChargeReceiptJob.set(queue: _1.purchases_requiring_stamping.any? ? "default" : "critical").perform_async(_1.id)
end
end
def successful_charges
@_successful_charges ||= charges.select { _1.successful_purchases.any? }
end
def unsubscribe_buyer
purchase_as_orderable.unsubscribe_buyer
end
def schedule_review_reminder!
OrderReviewReminderJob.perform_in(reminder_email_delay, id)
update!(review_reminder_scheduled_at: Time.current)
end
private
# Currently, there is some order-level data that is duplicated on individual purchase records
# For example, payment information is duplicated on each purchase that requires payment.
# Since the data is identical, we can just use one of the purchases as the source of that data.
# Ideally, the data should be saved directly on the order.
# If at least one product requires payment, then the order requires payment.
def purchase_with_payment_as_orderable
@_purchase_with_payment_as_orderable = successful_purchases.non_free.first || purchase_as_orderable
end
# To be used only when the data retrieved is present on ALL purchases.
def purchase_as_orderable
@_purchase_as_orderable = successful_purchases.first
end
def successful_purchases
purchases.all_success_states_including_test
end
def should_schedule_review_reminder?
review_reminder_scheduled_at.nil? && cart.present? && purchases.any?(&:eligible_for_review_reminder?)
end
def reminder_email_delay
return ProductReview::REVIEW_REMINDER_PHYSICAL_DELAY if purchases.all? { _1.link.require_shipping }
ProductReview::REVIEW_REMINDER_DELAY
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/blocked_object.rb | app/models/blocked_object.rb | # frozen_string_literal: true
class BlockedObject
include Mongoid::Document
include Mongoid::Timestamps
# Block the IP for 6 months so that if the IP gets reallocated can be used again
# Also prevents the list of blocked IPs to grow indefinitely
IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS = 6
field :object_type, type: String
field :object_value, type: String
field :blocked_at, type: DateTime
field :expires_at, type: DateTime
field :blocked_by, type: Integer
BLOCKED_OBJECT_TYPES.each_value do |object_type|
scope object_type, -> { where(object_type:) }
define_method("#{object_type}?") { self.object_type == object_type }
end
validates_inclusion_of :object_type, in: BLOCKED_OBJECT_TYPES.values
validates :expires_at, presence: { if: %i[ip_address? blocked_at?] }
scope :active, -> { where(:blocked_at.ne => nil).any_of({ expires_at: nil }, { :expires_at.gt => Time.current }) }
class << self
def block!(object_type, object_value, blocking_user_id, expires_in: nil)
blocked_object = find_or_initialize_by(object_type:, object_value:)
blocked_at = Time.current
blocked_object.blocked_at = blocked_at
blocked_object.blocked_by = blocking_user_id
blocked_object.expires_at = blocked_at + expires_in if expires_in.present?
blocked_object.save!
blocked_object
end
def unblock!(object_value)
blocked_object = find_by(object_value:)
blocked_object.unblock! if blocked_object
end
def find_object(object_value)
find_by(object_value:)
rescue NoMethodError
nil
end
def find_active_object(object_value)
active.find_object(object_value)
end
def find_objects(object_values)
where(:object_value.in => object_values)
rescue NoMethodError
BlockedObject.none
end
def find_active_objects(object_values)
active.find_objects(object_values)
end
end
def block!(by_user_id: nil, expires_in: nil)
self.class.block!(object_type, object_value, by_user_id, expires_in:)
end
def unblock!
self.blocked_at = nil
self.expires_at = nil
self.save!
end
def blocked?
blocked_at.present? && (expires_at.nil? || expires_at > Time.current)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/indonesia_bank_account.rb | app/models/indonesia_bank_account.rb | # frozen_string_literal: true
class IndonesiaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "ID"
BANK_CODE_FORMAT_REGEX = /\A[0-9a-zA-Z]{3,4}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{1,35}\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::IDN.alpha2
end
def currency
Currency::IDR
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/north_macedonia_bank_account.rb | app/models/north_macedonia_bank_account.rb | # frozen_string_literal: true
class NorthMacedoniaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MK"
BANK_CODE_FORMAT_REGEX = /\A[a-zA-Z0-9]{8,11}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[a-zA-Z0-9]{19}\z/
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::MKD.alpha2
end
def currency
Currency::MKD
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 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/korea_bank_account.rb | app/models/korea_bank_account.rb | # frozen_string_literal: true
class KoreaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "KR"
BANK_CODE_FORMAT_REGEX = /\A[A-Za-z]{4}KR[A-Za-z0-9]{2,5}\z/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{11,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::KOR.alpha2
end
def currency
Currency::KRW
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/order_purchase.rb | app/models/order_purchase.rb | # frozen_string_literal: true
class OrderPurchase < ApplicationRecord
belongs_to :order
belongs_to :purchase
validates_presence_of :order
validates_presence_of :purchase
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/algeria_bank_account.rb | app/models/algeria_bank_account.rb | # frozen_string_literal: true
class AlgeriaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "DZ"
BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{20}$/
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::DZA.alpha2
end
def currency
Currency::DZD
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/uk_bank_account.rb | app/models/uk_bank_account.rb | # frozen_string_literal: true
class UkBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "UK"
SORT_CODE_FORMAT_REGEX = /^\d{2}-\d{2}-\d{2}$/
private_constant :SORT_CODE_FORMAT_REGEX
alias_attribute :sort_code, :bank_number
validate :validate_sort_code
def routing_number
sort_code
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::GBR.alpha2
end
def currency
Currency::GBP
end
def to_hash
super.merge(
sort_code:
)
end
private
def validate_sort_code
errors.add :base, "The sort code is invalid." unless SORT_CODE_FORMAT_REGEX.match?(sort_code)
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.rb | app/models/utm_link.rb | # frozen_string_literal: true
class UtmLink < ApplicationRecord
include Deletable, ExternalId
MAX_UTM_PARAM_LENGTH = 200
has_paper_trail
belongs_to :seller, class_name: "User"
belongs_to :target_resource, polymorphic: true, optional: true
has_many :utm_link_visits, dependent: :destroy
has_many :utm_link_driven_sales, dependent: :destroy
has_many :purchases, through: :utm_link_driven_sales
has_many :successful_purchases,
-> { successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback },
through: :utm_link_driven_sales,
class_name: "Purchase",
source: :purchase
enum :target_resource_type, {
profile_page: "profile_page",
subscribe_page: "subscribe_page",
product_page: "product_page",
post_page: "post_page"
}, prefix: :target, validate: true
before_validation :set_permalink
validates :title, presence: true
validates :target_resource_id, presence: true, if: :requires_resource_id?
validates :permalink, presence: true, format: { with: /\A[a-z0-9]{8}\z/ }, uniqueness: { case_sensitive: false }
validates :utm_campaign, presence: true, length: { maximum: MAX_UTM_PARAM_LENGTH }
validates :utm_medium, presence: true, length: { maximum: MAX_UTM_PARAM_LENGTH }
validates :utm_source, presence: true, length: { maximum: MAX_UTM_PARAM_LENGTH }
validates :utm_term, length: { maximum: MAX_UTM_PARAM_LENGTH }
validates :utm_content, length: { maximum: MAX_UTM_PARAM_LENGTH }
validate :last_click_at_is_same_or_after_first_click_at
validate :utm_fields_are_unique_per_target_resource
scope :enabled, -> { where(disabled_at: nil) }
scope :active, -> { alive.enabled }
def enabled? = disabled_at.blank?
def active? = alive? && enabled?
def mark_disabled!
update!(disabled_at: Time.current)
end
def mark_enabled!
update!(disabled_at: nil)
end
def short_url
"#{UrlService.short_domain_with_protocol}/u/#{permalink}"
end
def utm_url
uri = Addressable::URI.parse(target_resource_url)
params = uri.query_values || {}
params["utm_source"] = utm_source
params["utm_medium"] = utm_medium
params["utm_campaign"] = utm_campaign
params["utm_term"] = utm_term if utm_term.present?
params["utm_content"] = utm_content if utm_content.present?
uri.query_values = params
uri.to_s
end
def target_resource_name
if target_product_page?
"Product β #{target_resource.name}"
elsif target_post_page?
"Post β #{target_resource.name}"
elsif target_profile_page?
"Profile page"
elsif target_subscribe_page?
"Subscribe page"
end
end
def default_title
"#{target_resource_name} (auto-generated)".strip
end
def self.generate_permalink(max_retries: 10)
retries = 0
candidate = SecureRandom.alphanumeric(8).downcase
while self.exists?(permalink: candidate)
retries += 1
raise "Failed to generate unique permalink after #{max_retries} attempts" if retries >= max_retries
candidate = SecureRandom.alphanumeric(8).downcase
end
candidate
end
# Overrides the polymorphic class for :target_resource association since we
# don't store the actual class names in the :target_resource_type column
def self.polymorphic_class_for(name)
case name.to_s
when target_resource_types[:post_page] then Installment
when target_resource_types[:product_page] then Link
end
end
private
def requires_resource_id?
target_product_page? || target_post_page?
end
def last_click_at_is_same_or_after_first_click_at
return if last_click_at.blank?
if first_click_at.nil? || first_click_at > last_click_at
errors.add(:last_click_at, "must be same or after the first click at")
end
end
def target_resource_url
if target_profile_page?
seller.profile_url
elsif target_subscribe_page?
Rails.application.routes.url_helpers.custom_domain_subscribe_url(host: seller.subdomain_with_protocol)
elsif target_product_page?
target_resource.long_url
elsif target_post_page?
target_resource.full_url
end
end
def set_permalink
return if permalink.present?
self.permalink = self.class.generate_permalink
end
def utm_fields_are_unique_per_target_resource
return if self.class.alive.where(
seller_id:,
utm_source:,
utm_medium:,
utm_campaign:,
utm_term:,
utm_content:,
target_resource_type:,
target_resource_id:
).where.not(id:).none?
errors.add(:target_resource_id, "A link with similar UTM parameters already exists for this destination!")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_folder.rb | app/models/product_folder.rb | # frozen_string_literal: true
class ProductFolder < ApplicationRecord
include ExternalId
include Deletable
scope :in_order, -> { order(position: :asc) }
belongs_to :link, foreign_key: "product_id", optional: true
validates_presence_of :name
def as_json(options = {})
{
id: external_id,
name:
}
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_posts_section.rb | app/models/seller_profile_posts_section.rb | # frozen_string_literal: true
class SellerProfilePostsSection < SellerProfileSection
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bahamas_bank_account.rb | app/models/bahamas_bank_account.rb | # frozen_string_literal: true
class BahamasBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BS"
BANK_CODE_FORMAT_REGEX = /^[a-z0-9A-Z]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,10}$/
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::BHS.alpha2
end
def currency
Currency::BSD
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/community_chat_message.rb | app/models/community_chat_message.rb | # frozen_string_literal: true
class CommunityChatMessage < ApplicationRecord
include Deletable
include ExternalId
belongs_to :community
belongs_to :user
has_many :last_read_community_chat_messages, dependent: :destroy
validates :content, presence: true, length: { minimum: 1, maximum: 20_000 }
scope :recent_first, -> { 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/credit_card.rb | app/models/credit_card.rb | # frozen_string_literal: true
class CreditCard < ApplicationRecord
include PurchaseErrorCode
include ChargeProcessable
has_many :users
has_one :purchase
has_one :subscription
belongs_to :preorder, optional: true
has_one :bank_account
attr_accessor :error_code, :stripe_error_code
validates :stripe_fingerprint, presence: true
validates :visual, :card_type, presence: true
validates :stripe_customer_id, :expiry_month, :expiry_year, presence: true, if: -> { card_type != CardType::PAYPAL }
validates :braintree_customer_id, presence: { if: :braintree_charge_processor? }
validates :paypal_billing_agreement_id, presence: { if: :paypal_charge_processor? }
validates :charge_processor_id, presence: true
def as_json
{
credit: "saved",
visual: visual.gsub("*", "·").html_safe,
type: card_type,
processor: charge_processor_id,
date: expiry_visual
}
end
def self.new_card_info
{ credit: "new", visual: nil, type: nil, processor: nil, date: nil }
end
def self.test_card_info
{ credit: "test", visual: nil, type: nil, processor: nil, date: nil }
end
def expiry_visual
return nil if expiry_month.nil? || expiry_year.nil?
expiry_month.to_s.rjust(2, "0") + "/" + expiry_year.to_s[-2, 2]
end
def self.create(chargeable, card_data_handling_mode = nil, user = nil)
credit_card = CreditCard.new
credit_card.card_data_handling_mode = card_data_handling_mode
credit_card.charge_processor_id = chargeable.charge_processor_id
begin
chargeable.prepare!
credit_card.visual = chargeable.visual
credit_card.funding_type = chargeable.funding_type
credit_card.stripe_customer_id = chargeable.reusable_token_for!(StripeChargeProcessor.charge_processor_id, user)
credit_card.braintree_customer_id = chargeable.reusable_token_for!(BraintreeChargeProcessor.charge_processor_id, user)
credit_card.paypal_billing_agreement_id = chargeable.reusable_token_for!(PaypalChargeProcessor.charge_processor_id, user)
credit_card.processor_payment_method_id = chargeable.payment_method_id
credit_card.stripe_fingerprint = chargeable.fingerprint
credit_card.card_type = chargeable.card_type
credit_card.expiry_month = chargeable.expiry_month
credit_card.expiry_year = chargeable.expiry_year
credit_card.card_country = chargeable.country
# Only required for recurring purchases in India via Stripe, which use e-mandates:
# https://stripe.com/docs/india-recurring-payments?integration=paymentIntents-setupIntents
if chargeable.requires_mandate?
credit_card.json_data = { stripe_setup_intent_id: chargeable.try(:stripe_setup_intent_id), stripe_payment_intent_id: chargeable.try(:stripe_payment_intent_id) }
end
credit_card.save!
rescue ChargeProcessorInvalidRequestError, ChargeProcessorUnavailableError => e
logger.error("Error while persisting card with #{credit_card.charge_processor_id}: #{e.message} - card visual: #{credit_card.visual}")
credit_card.errors.add(:base, "There is a temporary problem, please try again (your card was not charged).")
credit_card.error_code = credit_card.charge_processor_unavailable_error
rescue ChargeProcessorCardError => e
logger.info("Error while persisting card with #{credit_card.charge_processor_id}: #{e.message} - card visual: #{credit_card.visual}")
credit_card.errors.add(:base, PurchaseErrorCode.customer_error_message(e.message))
credit_card.stripe_error_code = e.error_code
end
credit_card
end
def charge_processor_unavailable_error
charge_processor_id.blank? || stripe_charge_processor? ?
PurchaseErrorCode::STRIPE_UNAVAILABLE :
PurchaseErrorCode::PAYPAL_UNAVAILABLE
end
def to_chargeable(merchant_account: nil)
reusable_tokens = {
StripeChargeProcessor.charge_processor_id => stripe_customer_id,
BraintreeChargeProcessor.charge_processor_id => braintree_customer_id,
PaypalChargeProcessor.charge_processor_id => paypal_billing_agreement_id
}
ChargeProcessor.get_chargeable_for_data(
reusable_tokens,
processor_payment_method_id,
stripe_fingerprint,
stripe_setup_intent_id,
stripe_payment_intent_id,
ChargeableVisual.is_cc_visual(visual) ? ChargeableVisual.get_card_last4(visual) : nil,
visual.gsub(/\s/, "").length,
visual,
expiry_month,
expiry_year,
card_type,
card_country,
merchant_account:
)
end
def last_four_digits
visual.split.last
end
def requires_mandate?
card_country == "IN"
end
def stripe_setup_intent_id
json_data && json_data.deep_symbolize_keys[:stripe_setup_intent_id]
end
def stripe_payment_intent_id
json_data && json_data.deep_symbolize_keys[:stripe_payment_intent_id]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/audience_member.rb | app/models/audience_member.rb | # frozen_string_literal: true
class AudienceMember < ApplicationRecord
VALID_FILTER_TYPES = %w[customer follower affiliate].freeze
belongs_to :seller, class_name: "User"
after_initialize :assign_default_details_value
before_validation :compact_details
before_validation :normalize_email, if: :email?
validates :email, email_format: true, presence: true
validate :details_json_has_valid_format
before_save :assign_derived_columns
def self.filter(seller_id:, params: {}, with_ids: false)
params = params.slice(
:type,
:bought_product_ids, :bought_variant_ids,
:not_bought_product_ids, :not_bought_variant_ids,
:paid_more_than_cents, :paid_less_than_cents,
:created_after, :created_before,
:bought_from,
:affiliate_product_ids
).compact_blank
if params[:type]
raise ArgumentError, "Invalid type: #{params[:type]}. Must be one of: #{VALID_FILTER_TYPES.join(', ')}" unless params[:type].in?(VALID_FILTER_TYPES)
types_sql = where(:seller_id => seller_id, params[:type] => true).to_sql
end
if params[:bought_product_ids]
products_relation = where(seller_id:)
json_contains = "JSON_CONTAINS(details->'$.purchases[*].product_id', ?)"
products_where_sql = ([json_contains] * params[:bought_product_ids].size).join(" OR ")
products_relation = products_relation.where(products_where_sql, *params[:bought_product_ids])
products_sql = products_relation.to_sql
end
if params[:bought_variant_ids]
variants_relation = where(seller_id:)
json_contains = "JSON_CONTAINS(details->'$.purchases[*].variant_ids[*]', ?)"
variants_where_sql = ([json_contains] * params[:bought_variant_ids].size).join(" OR ")
variants_relation = variants_relation.where(variants_where_sql, *params[:bought_variant_ids])
variants_sql = variants_relation.to_sql
end
bought_products_union_variants_sql = [products_sql, variants_sql].compact.join(" UNION ").presence
if params[:not_bought_product_ids]
products_relation = where(seller_id:)
json_contains = "JSON_CONTAINS(details->'$.purchases[*].product_id', ?)"
products_where_sql = (["(#{json_contains} IS NULL OR #{json_contains} = 0)"] * params[:not_bought_product_ids].size).join(" AND ")
products_relation = products_relation.where(products_where_sql, *(params[:not_bought_product_ids].zip(params[:not_bought_product_ids]).flatten))
not_bought_products_sql = products_relation.to_sql
end
if params[:not_bought_variant_ids]
variants_relation = where(seller_id:)
json_contains = "JSON_CONTAINS(details->'$.purchases[*].variant_ids[*]', ?)"
variants_where_sql = (["(#{json_contains} IS NULL OR #{json_contains} = 0)"] * params[:not_bought_variant_ids].size).join(" AND ")
variants_relation = variants_relation.where(variants_where_sql, *(params[:not_bought_variant_ids].zip(params[:not_bought_variant_ids]).flatten))
not_bought_variants_sql = variants_relation.to_sql
end
if params[:paid_more_than_cents] || params[:paid_less_than_cents]
prices_relation = where(seller_id:)
prices_relation = prices_relation.where("max_paid_cents > ?", params[:paid_more_than_cents]) if params[:paid_more_than_cents]
prices_relation = prices_relation.where("min_paid_cents < ?", params[:paid_less_than_cents]) if params[:paid_less_than_cents]
prices_sql = prices_relation.to_sql
end
if params[:created_after] || params[:created_before]
created_at_relation = where(seller_id:)
min_created_at_column, max_created_at_column = \
case params[:type]
when "customer" then [:min_purchase_created_at, :max_purchase_created_at]
when "follower" then [:follower_created_at, :follower_created_at]
when "affiliate" then [:min_affiliate_created_at, :max_affiliate_created_at]
else [:min_created_at, :max_created_at]
end
created_at_relation = created_at_relation.where("#{max_created_at_column} > ?", params[:created_after]) if params[:created_after]
created_at_relation = created_at_relation.where("#{min_created_at_column} < ?", params[:created_before]) if params[:created_before]
created_at_sql = created_at_relation.to_sql
end
if params[:bought_from]
country_relation = where(seller_id:).where("JSON_CONTAINS(details->'$.purchases[*].country', ?)", %("#{params[:bought_from]}"))
country_sql = country_relation.to_sql
end
if params[:affiliate_product_ids]
affiliates_relation = where(seller_id:)
json_contains = "JSON_CONTAINS(details->'$.affiliates[*].product_id', ?)"
affiliates_where_sql = ([json_contains] * params[:affiliate_product_ids].size).join(" OR ")
affiliates_relation = affiliates_relation.where(affiliates_where_sql, *params[:affiliate_product_ids])
affiliates_sql = affiliates_relation.to_sql
end
filter_purchases_when = (
(params[:bought_product_ids] || params[:bought_variant_ids] || params[:affiliate_product_ids]) \
&& (params[:paid_more_than_cents] || params[:paid_less_than_cents] || params[:created_after] || params[:created_before] || params[:bought_from]))
filter_purchases_when ||= (params[:paid_more_than_cents] && params[:paid_less_than_cents])
filter_purchases_when ||= (params[:created_after] && params[:created_before])
if filter_purchases_when || with_ids
json_filter = where(seller_id:)
json_table = <<~SQL.squish
JSON_TABLE(details, '$' COLUMNS (
NESTED PATH '$.follower' COLUMNS (
follower_id INT PATH '$.id',
follower_created_at DATETIME PATH '$.created_at'
),
NESTED PATH '$.purchases[*]' COLUMNS (
purchase_id INT PATH '$.id',
purchase_product_id INT PATH '$.product_id',
NESTED PATH '$.variant_ids[*]' COLUMNS (purchase_variant_id INT PATH '$'),
purchase_price_cents INT PATH '$.price_cents',
purchase_created_at DATETIME PATH '$.created_at',
purchase_country CHAR(100) PATH '$.country'
),
NESTED PATH '$.affiliates[*]' COLUMNS (
affiliate_id INT PATH '$.id',
affiliate_product_id INT PATH '$.product_id',
affiliate_created_at DATETIME PATH '$.created_at'
)
))
SQL
json_filter = json_filter.joins("INNER JOIN #{json_table} AS jt")
json_filter = json_filter.where("jt.purchase_price_cents > ?", params[:paid_more_than_cents]) if params[:paid_more_than_cents]
json_filter = json_filter.where("jt.purchase_price_cents < ?", params[:paid_less_than_cents]) if params[:paid_less_than_cents]
timestamp_columns = if params[:type] == "customer"
%w[purchase_created_at]
elsif params[:type] == "follower"
if params[:bought_product_ids] || params[:bought_variant_ids]
%w[follower_created_at purchase_created_at]
else
%w[follower_created_at]
end
elsif params[:type] == "affiliate"
%w[affiliate_created_at]
else
%w[purchase_created_at follower_created_at affiliate_created_at]
end
if params[:created_after]
where_conditions = timestamp_columns.map { "jt.#{_1} > :date" }.join(" OR ")
json_filter = json_filter.where(where_conditions, date: params[:created_after])
end
if params[:created_before]
where_conditions = timestamp_columns.map { "jt.#{_1} < :date" }.join(" OR ")
json_filter = json_filter.where(where_conditions, date: params[:created_before])
end
if params[:bought_product_ids] && params[:bought_variant_ids]
json_filter = json_filter.where("jt.purchase_product_id IN (?) OR jt.purchase_variant_id IN (?)", params[:bought_product_ids], params[:bought_variant_ids])
else
json_filter = json_filter.where("jt.purchase_product_id IN (?)", params[:bought_product_ids]) if params[:bought_product_ids]
json_filter = json_filter.where("jt.purchase_variant_id IN (?)", params[:bought_variant_ids]) if params[:bought_variant_ids]
end
if params[:affiliate_product_ids]
json_filter = json_filter.where("jt.affiliate_product_id IN (?)", params[:affiliate_product_ids])
end
json_filter = json_filter.where("jt.purchase_country = ?", params[:bought_from]) if params[:bought_from]
# Joining a JSON_TABLE yields a row for each matching element in the JSON array.
# Our business logic says that if a user has multiple purchases or affiliates matching the filters,
# we should only return the most recent one. This is why we use max() and group() below, when we need the ids.
# We name those columns (e.g. purchase_id) so the root query can access values from this subquery if necessary.
# When we don't need the ids, we can just do a distinct (much faster) on all the rows found by the root query.
if with_ids
json_filter = json_filter.group(:id)
json_filter = json_filter.select("audience_members.*, max(jt.purchase_id) AS purchase_id, jt.follower_id AS follower_id, max(jt.affiliate_id) AS affiliate_id")
json_filter_sql = json_filter.to_sql
elsif json_filter.where_clause.present?
json_filter_sql = json_filter.to_sql
end
end
subqueries = [
types_sql,
bought_products_union_variants_sql,
not_bought_products_sql,
not_bought_variants_sql,
prices_sql,
created_at_sql,
country_sql,
affiliates_sql,
json_filter_sql,
].compact
return where(seller_id:) if subqueries.empty?
relation = from("(#{subqueries.first}) AS audience_members")
subqueries[1..].each.with_index do |subquery_sql, index|
relation = relation.joins("INNER JOIN (#{subquery_sql}) AS q#{index} ON audience_members.id = q#{index}.id")
end
if json_filter_sql
json_subquery_index = subqueries[1..].index(json_filter_sql)
# If the json filter is a subquery, we need to extract the id columns from it and add them to the root query.
if with_ids && json_subquery_index
relation = relation.select("audience_members.*, q#{json_subquery_index}.purchase_id AS purchase_id, q#{json_subquery_index}.follower_id AS follower_id, q#{json_subquery_index}.affiliate_id AS affiliate_id")
elsif !with_ids
# If we didn't get the rows with ids (that subquery includes a `group by`), they may not be unique.
relation = relation.distinct
end
end
relation
end
# Admin method: refreshes all audience members for a seller.
# Very slow, only use when absolutely necessary.
def self.refresh_all!(seller:)
emails = Set.new
batch_size = 10_000
# gather all possible emails (the records will be filtered later)
seller.sales.select(:id, :email).find_each(batch_size:) { emails << _1.email.downcase }
seller.followers.alive.select(:id, :email).find_each(batch_size:) { emails << _1.email.downcase }
seller.direct_affiliates.alive.includes(:affiliate_user).select(:id, :affiliate_user_id).find_each(batch_size:) { emails << _1.affiliate_user.email.downcase }
# remove members that are no longer members
seller.audience_members.find_each { emails.member?(_1.email) || _1.destroy! }
# create or update members
emails.each { seller.audience_members.find_or_initialize_by(email: _1).refresh! }
# return final count
seller.audience_members.count
end
# Admin method: refreshes the details of a specific audience member, or deletes record if no longer a member.
def refresh!
self.details = {}
seller.sales.where(email:).find_each do |purchase|
self.details["purchases"] ||= []
self.details["purchases"] << purchase.audience_member_details if purchase.should_be_audience_member?
end
follower = seller.followers.find_by(email:)
self.details["follower"] = follower.audience_member_details if follower&.should_be_audience_member?
seller.direct_affiliates.includes(:affiliate_user).where(users: { email: }).find_each do |affiliate|
next unless affiliate.should_be_audience_member?
self.details["affiliates"] ||= []
affiliate.product_affiliates.each do |product_affiliate|
self.details["affiliates"] << affiliate.audience_member_details(product_id: product_affiliate.link_id)
end
end
if valid?
save!
elsif persisted?
destroy!
end
end
private
def assign_default_details_value
return if persisted?
self.details ||= {}
end
def compact_details
self.details = self.details.compact_blank
self.details.slice("purchases", "affiliates").each { _2.each(&:compact_blank!) }
end
def details_json_has_valid_format
schema_file = Rails.root.join("lib", "json_schemas", "audience_member_details.json").to_s
JSON::Validator.fully_validate(schema_file, details).each { errors.add(:details, _1) }
end
def normalize_email
self.email = email.strip.downcase
end
def assign_derived_columns
self.customer = details["purchases"].present?
self.follower = details["follower"].present?
self.affiliate = details["affiliates"].present?
self.min_paid_cents, self.max_paid_cents = Array.wrap(details["purchases"]).map { _1["price_cents"] }.compact.minmax
self.min_purchase_created_at, self.max_purchase_created_at = Array.wrap(details["purchases"]).map { _1["created_at"] }.compact.minmax
self.follower_created_at = details.dig("follower", "created_at")
self.min_affiliate_created_at, self.max_affiliate_created_at = Array.wrap(details["affiliates"]).map { _1["created_at"] }.compact.minmax
self.min_created_at, self.max_created_at = [min_purchase_created_at, max_purchase_created_at, follower_created_at, min_affiliate_created_at, max_affiliate_created_at].compact.minmax
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/license.rb | app/models/license.rb | # frozen_string_literal: true
class License < ApplicationRecord
has_paper_trail only: %i[disabled_at serial]
include FlagShihTzu
include ExternalId
validates_numericality_of :uses, greater_than_or_equal_to: 0
validates_presence_of :serial
belongs_to :link, optional: true
belongs_to :purchase, optional: true
belongs_to :imported_customer, optional: true
before_validation :generate_serial, on: :create
has_flags 1 => :DEPRECATED_is_pregenerated,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
def generate_serial
return if serial.present?
self.serial = SecureRandom.uuid.upcase.delete("-").scan(/.{8}/).join("-")
end
def disabled?
disabled_at?
end
def disable!
self.disabled_at = Time.current
save!
end
def enable!
self.disabled_at = nil
save!
end
def rotate!
self.serial = nil
generate_serial
save!
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/south_africa_bank_account.rb | app/models/south_africa_bank_account.rb | # frozen_string_literal: true
class SouthAfricaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "ZA"
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,16}\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::ZAF.alpha2
end
def currency
Currency::ZAR
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/installment_plan_snapshot.rb | app/models/installment_plan_snapshot.rb | # frozen_string_literal: true
class InstallmentPlanSnapshot < ApplicationRecord
belongs_to :payment_option
validates :payment_option, uniqueness: true
validates :number_of_installments, presence: true, numericality: { greater_than: 0, only_integer: true }
validates :recurrence, presence: true
validates :total_price_cents, presence: true, numericality: { greater_than: 0, only_integer: true }
def calculate_installment_payment_price_cents
base_price = total_price_cents / number_of_installments
remainder = total_price_cents % number_of_installments
Array.new(number_of_installments) do |i|
i.zero? ? base_price + remainder : base_price
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/rwanda_bank_account.rb | app/models/rwanda_bank_account.rb | # frozen_string_literal: true
class RwandaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "RW"
BANK_CODE_FORMAT_REGEX = /^[A-Za-z0-9]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9]{1,15}$/
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::RWA.alpha2
end
def currency
Currency::RWF
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/seller_profile_products_section.rb | app/models/seller_profile_products_section.rb | # frozen_string_literal: true
class SellerProfileProductsSection < SellerProfileSection
def product_names
# Prevents a full table scan (see https://github.com/gumroad/web/pull/26855)
Link.where(user_id: seller_id, id: shown_products).pluck(:name)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/antigua_and_barbuda_bank_account.rb | app/models/antigua_and_barbuda_bank_account.rb | # frozen_string_literal: true
class AntiguaAndBarbudaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "AG"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{1,32}$/
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::ATG.alpha2
end
def currency
Currency::XCD
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/wishlist_product.rb | app/models/wishlist_product.rb | # frozen_string_literal: true
class WishlistProduct < ApplicationRecord
include ExternalId
include Deletable
WISHLIST_PRODUCT_LIMIT = 100
belongs_to :wishlist
belongs_to :product, class_name: "Link"
belongs_to :variant, class_name: "BaseVariant", optional: true
scope :available_to_buy, -> { joins(product: :user).merge(Link.alive).merge(User.not_suspended) }
validates :product_id, uniqueness: { scope: [:wishlist_id, :variant_id, :recurrence, :deleted_at] }
validates :recurrence, inclusion: { in: BasePrice::Recurrence::ALLOWED_RECURRENCES }, if: -> { product&.is_recurring_billing }
validates :recurrence, absence: true, unless: -> { product&.is_recurring_billing }
validates :quantity, numericality: { greater_than: 0 }
validates :quantity, numericality: { equal_to: 1 }, unless: -> { product&.quantity_enabled }
validates :rent, absence: true, unless: -> { product&.rentable? }
validates :rent, presence: true, unless: -> { product&.buyable? }
validate :versioned_product_has_variant
validate :variant_belongs_to_product
validate :wishlist_product_limit, on: :create
attribute :quantity, default: 1
attribute :rent, default: false
after_create :update_wishlist_recommendable
after_update :update_wishlist_recommendable, if: :saved_change_to_deleted_at?
private
def update_wishlist_recommendable
wishlist.update_recommendable
end
def versioned_product_has_variant
if (product.skus_enabled && product.skus.alive.not_is_default_sku.count > 1) || product.alive_variants.present?
if variant.blank?
errors.add(:base, "Wishlist product must have variant specified for versioned product")
end
end
end
def variant_belongs_to_product
if variant.present? && variant.link != product
errors.add(:base, "The wishlist product's variant must belong to its product")
end
end
def wishlist_product_limit
if wishlist.alive_wishlist_products.count >= WISHLIST_PRODUCT_LIMIT
errors.add(:base, "A wishlist can have at most #{WISHLIST_PRODUCT_LIMIT} products")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_review_response.rb | app/models/product_review_response.rb | # frozen_string_literal: true
class ProductReviewResponse < ApplicationRecord
belongs_to :user
belongs_to :product_review
validates :message, presence: true
after_create_commit :notify_reviewer_via_email
private
def notify_reviewer_via_email
CustomerMailer.review_response(self).deliver_later
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/commission.rb | app/models/commission.rb | # frozen_string_literal: true
class Commission < ApplicationRecord
include ExternalId
COMMISSION_DEPOSIT_PROPORTION = 0.5
STATUSES = ["in_progress", "completed", "cancelled"].freeze
STATUSES.each do |status|
const_set("STATUS_#{status.upcase}", status)
end
STATUSES.each do |status|
define_method("is_#{status}?") do
self.status == status
end
end
belongs_to :deposit_purchase, class_name: "Purchase"
belongs_to :completion_purchase, class_name: "Purchase", optional: true
has_many_attached :files
validates :status, inclusion: { in: STATUSES }
validate :purchases_must_be_different
validate :purchases_must_belong_to_same_commission_product
def create_completion_purchase!
return if is_completed?
completion_purchase_attributes = deposit_purchase.slice(
:link, :purchaser, :credit_card_id, :email, :full_name, :street_address,
:country, :state, :zip_code, :city, :ip_address, :ip_state, :ip_country,
:browser_guid, :referrer, :quantity, :was_product_recommended, :seller,
:credit_card_zipcode, :offer_code, :variant_attributes, :is_purchasing_power_parity_discounted
).merge(
perceived_price_cents: completion_display_price_cents,
affiliate: deposit_purchase.affiliate.try(:alive?) ? deposit_purchase.affiliate : nil,
is_commission_completion_purchase: true
)
completion_purchase = build_completion_purchase(completion_purchase_attributes)
deposit_tip = deposit_purchase.tip
if deposit_tip.present?
completion_tip_value_cents = (deposit_tip.value_cents / COMMISSION_DEPOSIT_PROPORTION) - deposit_tip.value_cents
completion_purchase.build_tip(value_cents: completion_tip_value_cents)
end
if deposit_purchase.is_purchasing_power_parity_discounted &&
deposit_purchase.purchasing_power_parity_info.present?
completion_purchase.build_purchasing_power_parity_info(
factor: deposit_purchase.purchasing_power_parity_info.factor
)
end
completion_purchase.ensure_completion do
completion_purchase.process!
if completion_purchase.errors.present?
raise ActiveRecord::RecordInvalid.new(completion_purchase)
end
completion_purchase.update_balance_and_mark_successful!
self.status = STATUS_COMPLETED
self.completion_purchase = completion_purchase
save!
end
end
def completion_price_cents
(deposit_purchase.price_cents / COMMISSION_DEPOSIT_PROPORTION) - deposit_purchase.price_cents
end
def completion_display_price_cents
(deposit_purchase.displayed_price_cents / COMMISSION_DEPOSIT_PROPORTION) - deposit_purchase.displayed_price_cents
end
private
def purchases_must_be_different
return if completion_purchase.nil?
if deposit_purchase == completion_purchase
errors.add(:base, "Deposit purchase and completion purchase must be different purchases")
end
end
def purchases_must_belong_to_same_commission_product
return if completion_purchase.nil?
if deposit_purchase.link != completion_purchase.link
errors.add(:base, "Deposit purchase and completion purchase must belong to the same commission product")
end
if deposit_purchase.link.native_type != Link::NATIVE_TYPE_COMMISSION
errors.add(:base, "Purchased product must be a commission")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/indian_bank_account.rb | app/models/indian_bank_account.rb | # frozen_string_literal: true
class IndianBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "IN"
# IFSC Format:
# β’Β 4 chars to identify bank
# β’Β 1 reserved digit, always 0
# β’ 6 chars to identify branch
IFSC_FORMAT_REGEX = /^[A-Za-z]{4}0[A-Z0-9a-z]{6}$/
private_constant :IFSC_FORMAT_REGEX
alias_attribute :ifsc, :bank_number
validate :validate_ifsc
def routing_number
ifsc
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::IND.alpha2
end
def currency
Currency::INR
end
def to_hash
{
routing_number:,
account_number: account_number_visual,
bank_account_type:
}
end
private
def validate_ifsc
errors.add :base, "The IFSC is invalid." unless IFSC_FORMAT_REGEX.match?(ifsc)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/payment_option.rb | app/models/payment_option.rb | # frozen_string_literal: true
class PaymentOption < ApplicationRecord
include Deletable
belongs_to :subscription
belongs_to :price
belongs_to :installment_plan,
foreign_key: :product_installment_plan_id, class_name: "ProductInstallmentPlan",
optional: true
has_one :installment_plan_snapshot, dependent: :destroy
validates :installment_plan, presence: true, if: -> { subscription&.is_installment_plan }
after_create :update_subscription_last_payment_option
after_update :update_subscription_last_payment_option, if: :saved_change_to_deleted_at?
after_destroy :update_subscription_last_payment_option
def offer_code
subscription.original_purchase.offer_code
end
def variant_attributes
subscription.original_purchase.variant_attributes
end
def update_subscription_last_payment_option
subscription.update_last_payment_option
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/zoom_integration.rb | app/models/zoom_integration.rb | # frozen_string_literal: true
class ZoomIntegration < Integration
INTEGRATION_DETAILS = %w[user_id email access_token refresh_token]
INTEGRATION_DETAILS.each { |detail| attr_json_data_accessor detail }
def self.is_enabled_for(purchase)
purchase.find_enabled_integration(Integration::ZOOM).present?
end
def same_connection?(integration)
integration.type == type && integration.user_id == user_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/sales_export.rb | app/models/sales_export.rb | # frozen_string_literal: true
class SalesExport < ApplicationRecord
belongs_to :recipient, class_name: "User"
# We use :delete_all instead of :destroy to prevent needlessly loading
# a lot of data in memory (column `purchases_data`).
has_many :chunks, class_name: "SalesExportChunk", foreign_key: :export_id, dependent: :delete_all
serialize :query, type: Hash, coder: YAML
validates_presence_of :query
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/workflow.rb | app/models/workflow.rb | # frozen_string_literal: true
class Workflow < ApplicationRecord
has_paper_trail
include ActionView::Helpers::NumberHelper, ExternalId, Deletable, JsonData, WithFiltering, FlagShihTzu,
Workflow::AbandonedCartProducts
has_flags 1 => :send_to_past_customers,
column: "flags",
flag_query_mode: :bit_operator,
check_for_column: false
belongs_to :link, optional: true
belongs_to :seller, class_name: "User", optional: true
belongs_to :base_variant, optional: true
has_many :installments
has_many :alive_installments, -> { alive }, class_name: "Installment"
attr_json_data_accessor :workflow_trigger
validates_presence_of :seller
MEMBER_CANCELLATION_WORKFLOW_TRIGGER = "member_cancellation"
SAVE_ACTION = "save"
SAVE_AND_PUBLISH_ACTION = "save_and_publish"
SAVE_AND_UNPUBLISH_ACTION = "save_and_unpublish"
scope :published, -> { where.not(published_at: nil) }
def recipient_type_audience?
audience_type?
end
def applies_to_purchase?(purchase)
return false if product_type? && link_id != purchase.link_id
return false if variant_type? && !purchase.variant_attributes.include?(base_variant)
purchase_passes_filters(purchase)
end
def new_customer_trigger?
workflow_trigger.nil?
end
def member_cancellation_trigger?
workflow_trigger == MEMBER_CANCELLATION_WORKFLOW_TRIGGER
end
def targets_variant?(variant)
(variant_type? && base_variant_id == variant.id) || (bought_variants.present? && bought_variants.include?(variant.external_id))
end
def mark_deleted!
self.deleted_at = Time.current
installments.each do |installment|
installment.mark_deleted!
installment.installment_rule.mark_deleted!
end
save!
end
def publish!
return true if published_at.present?
if !abandoned_cart_type? && !seller.eligible_to_send_emails?
errors.add(:base, "You cannot publish a workflow until you have made at least #{Money.from_cents(Installment::MINIMUM_SALES_CENTS_VALUE).format(no_cents: true)} in total earnings and received a payout")
raise ActiveRecord::RecordInvalid.new(self)
end
self.published_at = DateTime.current
self.first_published_at ||= published_at
installments.alive.find_each do |installment|
installment.publish!(published_at:)
schedule_installment(installment)
end
save!
end
def unpublish!
return true if published_at.nil?
self.published_at = nil
installments.alive.find_each(&:unpublish!)
save!
end
def has_never_been_published?
first_published_at.nil?
end
def schedule_installment(installment, old_delayed_delivery_time: nil)
return if installment.abandoned_cart_type?
return unless alive?
return unless new_customer_trigger?
return unless installment.published?
# don't schedule the installment if it is only for new customers/followers and it hasn't been scheduled before (old_delayed_delivery_time is nil)
return if old_delayed_delivery_time.nil? && installment.is_for_new_customers_of_workflow
# earliest_valid_time is:
# `installment.published_at` if the installment is for new customers only
# `nil` if the installment is being published for the first time and is not for new customers only,
# the time based off old_delayed_delivery_time if the installment has already been published before (at least once).
# We only want the purchases and/or followers created after earliest_valid_time because the specified
# installment has not been delivered to them and needs to be (re-)scheduled.
earliest_valid_time = if old_delayed_delivery_time.nil?
nil
elsif installment.is_for_new_customers_of_workflow && installment.published_at >= old_delayed_delivery_time.seconds.ago
installment.published_at
else
old_delayed_delivery_time.seconds.ago
end
SendWorkflowPostEmailsJob.perform_async(installment.id, earliest_valid_time&.iso8601)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/benin_bank_account.rb | app/models/benin_bank_account.rb | # frozen_string_literal: true
class BeninBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "BJ"
validate :validate_account_number, if: -> { Rails.env.production? }
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::BEN.alpha2
end
def currency
Currency::XOF
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/jamaica_bank_account.rb | app/models/jamaica_bank_account.rb | # frozen_string_literal: true
class JamaicaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "JM"
BANK_CODE_FORMAT_REGEX = /^\d{3}$/
BRANCH_CODE_FORMAT_REGEX = /^\d{5}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,18}$/
private_constant :BANK_CODE_FORMAT_REGEX, :BRANCH_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX
alias_attribute :bank_code, :bank_number
validate :validate_bank_code
validate :validate_branch_code
validate :validate_account_number
def routing_number
"#{bank_code}-#{branch_code}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::JAM.alpha2
end
def currency
Currency::JMD
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_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/tip.rb | app/models/tip.rb | # frozen_string_literal: true
class Tip < ApplicationRecord
belongs_to :purchase
validates :value_cents, numericality: { greater_than: 0 }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/base_price.rb | app/models/base_price.rb | # frozen_string_literal: true
class BasePrice < ApplicationRecord
has_paper_trail
self.table_name = "prices"
include BasePrice::Recurrence
include ExternalId
include ProductsHelper
include Deletable
include FlagShihTzu
validates :price_cents, :currency, presence: true
has_flags 1 => :is_rental,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
scope :is_buy, -> { self.not_is_rental }
def is_buy?
!is_rental?
end
def is_default_recurrence?
recurrence == link.subscription_duration.to_s
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/offer_code.rb | app/models/offer_code.rb | # frozen_string_literal: true
class OfferCode < ApplicationRecord
has_paper_trail
include FlagShihTzu
include ExternalId
include CurrencyHelper
include Mongoable
include Deletable
include MaxPurchaseCount
include OfferCode::Sorting
has_flags 1 => :is_cancellation_discount,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
stripped_fields :code
has_and_belongs_to_many :products, class_name: "Link", join_table: "offer_codes_products", association_foreign_key: "product_id"
belongs_to :user
has_many :purchases
has_many :purchases_that_count_towards_offer_code_uses, -> { counts_towards_offer_code_uses }, class_name: "Purchase"
has_one :upsell
alias_attribute :duration_in_billing_cycles, :duration_in_months
# Regex modified from https://stackoverflow.com/a/26900132
validates :code, presence: true, format: { with: /\A[A-Za-zΓ-ΓΓ-ΓΆΓΈ-ΓΏ0-9\-_]*\z/, message: "can only contain numbers, letters, dashes, and underscores." }, unless: -> { is_cancellation_discount? || upsell.present? }
validate :max_purchase_count_is_greater_than_or_equal_to_inventory_sold
validate :expires_at_is_after_valid_at
validate :price_validation
validate :validate_cancellation_discount_uniqueness
validate :validate_cancellation_discount_product_type
before_save :to_mongo
after_save :invalidate_product_cache
after_save :reindex_associated_products
before_destroy :capture_associated_product_ids
after_destroy :reindex_captured_products
validates_uniqueness_of :code, scope: %i[user_id deleted_at], if: :universal?, unless: :deleted?, message: "must be unique."
validate :code_validation, unless: lambda { |offer_code| offer_code.deleted? || offer_code.universal? || offer_code.upsell.present? }
# Public: Scope to get only universal offer codes which is when an offer applies to all user's products.
# Fixed-amount-off offer codes only show up on products that match their currency. That's why this scope takes a currency_type.
# nil currency_type is a percentage offer code
scope :universal_with_matching_currency, ->(currency_type) { where("universal = 1 and (currency_type = ? or currency_type is null)", currency_type) }
scope :universal, -> { where(universal: true) }
def is_valid_for_purchase?(purchase_quantity: 1)
return true if max_purchase_count.nil?
quantity_left >= purchase_quantity
end
def quantity_left
max_purchase_count - times_used
end
def is_percent?
amount_percentage.present?
end
def is_cents?
amount_cents.present?
end
def amount_off(price_cents)
return amount_cents if is_cents?
(price_cents * (amount_percentage / 100.0)).round
end
def original_price(discounted_price_cents)
return if amount_percentage == 100 # cannot determine original price from 100% discount code
return discounted_price_cents + amount_cents if is_cents?
(discounted_price_cents / (1 - amount_percentage / 100.0)).round
end
def amount
is_percent? ? amount_percentage : amount_cents
end
def is_currency_valid?(product)
is_percent? || currency_type.nil? || product.price_currency_type == currency_type
end
# Return amount buyer got off of the purchase with or without currency/'%'
#
# with_symbol - include currency/'%' in returned amount
def displayed_amount_off(currency_type, with_symbol: false)
if with_symbol
return Money.new(amount_cents, currency_type).format(no_cents_if_whole: true, symbol: true) if is_cents?
"#{amount_percentage}%"
else
return MoneyFormatter.format(amount_cents, currency_type.to_sym, no_cents_if_whole: true, symbol: false) if is_cents?
amount_percentage
end
end
def as_json(options = {})
if options[:api_scopes].present?
as_json_for_api
else
json = {
id: external_id,
code:,
max_purchase_count:,
universal: universal?,
times_used:
}
if is_percent?
json[:percent_off] = amount_percentage
else
json[:amount_cents] = amount_cents
end
json
end
end
def as_json_for_api
json = {
id: external_id,
# The `code` is returned as `name` for backwards compatibility of the API
name: code,
max_purchase_count:,
universal: universal?,
times_used:
}
if is_percent?
json[:percent_off] = amount_percentage
else
json[:amount_cents] = amount_cents
end
json
end
def times_used
purchases.counts_towards_offer_code_uses.sum(:quantity)
end
def time_fields
attributes.keys.keep_if { |key| key.include?("_at") && send(key) }
end
def applicable_products
if universal?
currency_type.present? ? user.links.alive.where(price_currency_type: currency_type) : user.links.alive
else
products
end
end
def applicable?(link)
if universal?
currency_type.present? ? link.price_currency_type == currency_type : true
else
products.include?(link)
end
end
def inactive?
!!(valid_at&.future? || expires_at&.past?)
end
def discount
(
is_cents? ?
{ type: "fixed", cents: amount_cents } :
{ type: "percent", percents: amount_percentage }
).merge(
{
product_ids: universal? ? nil : products.map(&:external_id),
expires_at:,
minimum_quantity:,
duration_in_billing_cycles:,
minimum_amount_cents:,
}
)
end
def is_amount_valid?(product)
product.available_price_cents.all? do |price_cents|
price_after_code = price_cents - amount_off(price_cents)
price_after_code <= 0 || price_after_code >= product.currency["min_price"]
end
end
def self.human_attribute_name(attr, _)
attr == "code" ? "Discount code" : super
end
private
def max_purchase_count_is_greater_than_or_equal_to_inventory_sold
return if deleted_at.present?
return unless max_purchase_count_changed?
return if max_purchase_count.nil? || max_purchase_count >= times_used
errors.add(:base, "You have chosen a discount code quantity that is less that the number already used. Please enter an amount no less than #{times_used}.")
end
def expires_at_is_after_valid_at
if (valid_at.present? && expires_at.present? && expires_at <= valid_at) || (valid_at.blank? && expires_at.present?)
errors.add(:base, "The discount code's start date must be earlier than its end date.")
end
end
def price_validation
return if deleted_at.present?
return errors.add(:base, "Please enter a positive discount amount.") if (is_percent? && amount_percentage.to_i < 0) || (is_cents? && amount_cents.to_i < 0)
return errors.add(:base, "Please enter a discount amount that is 100% or less.") if is_percent? && amount_percentage > 100
applicable_products.each do |product|
validate_price_after_discount(product)
validate_membership_price_after_discount(product)
validate_currency_type_after_discount(product)
return if errors.present?
end
end
def validate_price_after_discount(product)
return if is_amount_valid?(product)
errors.add(:base, "The price after discount for all of your products must be either #{product.currency["symbol"]}0 or at least #{product.min_price_formatted}.")
end
def validate_currency_type_after_discount(product)
return if is_currency_valid?(product)
errors.add(:base, "This discount code uses #{currency_type.upcase} but the product uses #{product.price_currency_type.upcase}. Please change the discount code to use the same currency as the product.")
end
def validate_membership_price_after_discount(product)
return unless product.is_tiered_membership? && duration_in_billing_cycles.present?
return if product.available_price_cents.none? { _1 - amount_off(_1) <= 0 }
errors.add(:base, "A fixed-duration discount code cannot be used to make a membership product temporarily free. Please add a free trial to your membership instead.")
end
def code_validation
applicable_products.each do |product|
if product.product_and_universal_offer_codes.any? { |other| code == other.code && id != other.id }
errors.add(:base, "Discount code must be unique.")
return
end
end
end
def invalidate_product_cache
products.each(&:invalidate_cache)
end
def validate_cancellation_discount_uniqueness
return unless is_cancellation_discount?
if universal?
errors.add(:base, "Cancellation discount offer codes cannot be universal")
return
end
if products.count > 1
errors.add(:base, "Cancellation discount offer codes must belong to exactly one product")
return
end
product = products.first
if product.offer_codes.alive.is_cancellation_discount.where.not(id: id).exists?
errors.add(:base, "This product already has a cancellation discount offer code")
end
end
def validate_cancellation_discount_product_type
return unless is_cancellation_discount?
product = products.first
unless product.is_tiered_membership?
errors.add(:base, "Cancellation discounts can only be added to memberships")
end
end
def reindex_associated_products(products_to_reindex: applicable_products)
products_to_reindex.each do |product|
product.enqueue_index_update_for(["offer_codes"])
end
end
def capture_associated_product_ids
@product_ids_to_reindex = applicable_products.ids
end
def reindex_captured_products
reindex_associated_products(products_to_reindex: Link.where(id: @product_ids_to_reindex)) if @product_ids_to_reindex.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/discover_search.rb | app/models/discover_search.rb | # frozen_string_literal: true
class DiscoverSearch < ApplicationRecord
belongs_to :user, optional: true
belongs_to :taxonomy, optional: true
belongs_to :clicked_resource, polymorphic: true, optional: true
has_one :discover_search_suggestion
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/refund.rb | app/models/refund.rb | # frozen_string_literal: true
class Refund < ApplicationRecord
FRAUD = "fraud"
include JsonData, FlagShihTzu
belongs_to :user, foreign_key: :refunding_user_id, optional: true
belongs_to :purchase
belongs_to :product, class_name: "Link", foreign_key: :link_id
belongs_to :seller, class_name: "User"
has_many :balance_transactions
has_one :credit
before_validation :assign_product, on: :create
before_validation :assign_seller, on: :create
validates_uniqueness_of :processor_refund_id, scope: :link_id, allow_blank: true
has_flags 1 => :is_for_fraud,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
attr_json_data_accessor :note
attr_json_data_accessor :business_vat_id
attr_json_data_accessor :debited_stripe_transfer
attr_json_data_accessor :retained_fee_cents
private
def assign_product
self.link_id = purchase.link_id
end
def assign_seller
self.seller_id = purchase.seller_id
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/call_limitation_info.rb | app/models/call_limitation_info.rb | # frozen_string_literal: true
class CallLimitationInfo < ApplicationRecord
DEFAULT_MINIMUM_NOTICE_IN_MINUTES = 180
CHECKOUT_GRACE_PERIOD = 3.minutes
belongs_to :call, class_name: "Link"
validate :belongs_to_call
attribute :minimum_notice_in_minutes, default: DEFAULT_MINIMUM_NOTICE_IN_MINUTES
def allows?(start_time)
has_enough_notice?(start_time) && can_take_more_calls_on?(start_time)
end
def has_enough_notice?(start_time)
return false if start_time.past?
return true if minimum_notice_in_minutes.nil?
start_time >= minimum_notice_in_minutes.minutes.from_now - CHECKOUT_GRACE_PERIOD
end
def can_take_more_calls_on?(start_time)
return true if maximum_calls_per_day.nil?
call.sold_calls.starts_on_date(start_time, call.user.timezone).count < maximum_calls_per_day
end
private
def belongs_to_call
if call.native_type != Link::NATIVE_TYPE_CALL
errors.add(:base, "Cannot create call limitations for a non-call product.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/upsell_variant.rb | app/models/upsell_variant.rb | # frozen_string_literal: true
class UpsellVariant < ApplicationRecord
include Deletable, ExternalId
belongs_to :upsell
belongs_to :selected_variant, class_name: "BaseVariant"
belongs_to :offered_variant, class_name: "BaseVariant"
validates_presence_of :upsell, :selected_variant, :offered_variant
validate :variants_belong_to_upsell_product, if: :alive?
private
def variants_belong_to_upsell_product
if selected_variant.link != upsell.product || offered_variant.link != upsell.product
errors.add(:base, "The selected variant and the offered variant must belong to the upsell's offered product.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/variant_category.rb | app/models/variant_category.rb | # frozen_string_literal: true
class VariantCategory < ApplicationRecord
include ExternalId
include Deletable
include FlagShihTzu
has_many :variants
has_many :alive_variants, -> { alive }, class_name: "Variant"
belongs_to :link, optional: true
# For tiered membership products, variants are "tiers"
has_many :tiers, -> { alive }, class_name: "Variant"
has_one :default_tier, -> { alive }, class_name: "Variant"
has_flags 1 => :DEPRECATED_variants_are_allowed_to_have_product_files,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
after_commit :invalidate_product_cache
scope :is_tier_category, -> { where(title: "Tier") }
def has_alive_grouping_variants_with_purchases?
alive_variants.each do |variant|
return true if variant.purchases.all_success_states.exists? && variant.product_files.alive.exists?
end
false
end
def available?
return true if variants.alive.empty?
variants.alive.any?(&:available?)
end
def as_json(*)
{ id: external_id, title: }.stringify_keys
end
private
def invalidate_product_cache
link.invalidate_cache if link.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/balance.rb | app/models/balance.rb | # frozen_string_literal: true
class Balance < ApplicationRecord
include ExternalId
include Balance::Searchable
include Balance::RefundEligibilityUnderwriter
belongs_to :user, optional: true
belongs_to :merchant_account, optional: true
has_many :balance_transactions
has_many :successful_sales, class_name: "Purchase", foreign_key: :purchase_success_balance_id
has_many :chargedback_sales, class_name: "Purchase", foreign_key: :purchase_chargeback_balance_id
has_many :refunded_sales, class_name: "Purchase", foreign_key: :purchase_refund_balance_id
has_many :successful_affiliate_credits, class_name: "AffiliateCredit", foreign_key: :affiliate_credit_success_balance_id
has_many :chargedback_affiliate_credits, class_name: "AffiliateCredit", foreign_key: :affiliate_credit_chargeback_balance_id
has_many :refunded_affiliate_credits, class_name: "AffiliateCredit", foreign_key: :affiliate_credit_refund_balance_id
has_many :credits
has_and_belongs_to_many :payments, join_table: "payments_balances"
# currency = The currency the balance was collected in.
# holding_currency = The currency the balance is being held in.
# Different if the funds were charged in USD, then settled and held in a merchant account in CAD, AUD, etc.
validates :merchant_account, :currency, :holding_currency, presence: true
validate :validate_amounts_are_only_changed_when_unpaid, on: :update
# Balance state machine
#
# unpaid β processing β paid
# β β β β
# β β β β β β β β β β β β β β
# β
# forfeited
#
# Note: Amounts are only changeable when in an unpaid state.
#
state_machine(:state, initial: :unpaid) do
event :mark_forfeited do
transition unpaid: :forfeited
end
event :mark_processing do
transition unpaid: :processing
end
event :mark_paid do
transition processing: :paid
end
event :mark_unpaid do
transition %i[processing paid] => :unpaid
end
state any do
validates_presence_of :amount_cents
end
after_transition any => any, :do => :log_transition
end
enum :state, %w[unpaid processing paid forfeited].index_by(&:itself), default: "unpaid"
private
def validate_amounts_are_only_changed_when_unpaid
return if unpaid?
%i[
amount_cents
holding_amount_cents
].each do |field|
errors.add(field, "may not be changed in #{state} state.") if field.to_s.in?(changed)
end
end
def log_transition
logger.info "Balance: balance ID #{id} transitioned to #{state}"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/macao_bank_account.rb | app/models/macao_bank_account.rb | # frozen_string_literal: true
class MacaoBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MO"
BANK_CODE_FORMAT_REGEX = /^[A-Za-z0-9]{8,11}$/
private_constant :BANK_CODE_FORMAT_REGEX
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,19}$/
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::MAC.alpha2
end
def currency
Currency::MOP
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/post_email_blast.rb | app/models/post_email_blast.rb | # frozen_string_literal: true
class PostEmailBlast < ApplicationRecord
# requested_at:
# Time when a user clicked on "Publish now".
# For a scheduled post, it is when the post was scheduled for.
# started_at:
# Time when we start the process of finding recipients to send the emails to.
# first_email_delivered_at:
# Time when the first email was delivered.
# last_email_delivered_at:
# Time the latest email was delivered. Not final until the blast is complete.
# delivery_count:
# Number of emails that were delivered. Not final until the blast is complete.
belongs_to :post, class_name: "Installment"
belongs_to :seller, class_name: "User"
before_validation -> { self.seller = post.seller }, on: :create
scope :aggregated, -> {
select(
"DATE(requested_at) AS date",
"COUNT(*) AS total",
"SUM(delivery_count) AS total_delivery_count",
"AVG(TIMESTAMPDIFF(SECOND, requested_at, started_at)) AS average_start_latency",
"AVG(TIMESTAMPDIFF(SECOND, requested_at, first_email_delivered_at)) AS average_first_email_delivery_latency",
"AVG(TIMESTAMPDIFF(SECOND, requested_at, last_email_delivered_at)) AS average_last_email_delivery_latency",
"AVG(delivery_count / TIMESTAMPDIFF(SECOND, first_email_delivered_at, last_email_delivered_at) * 60) AS average_deliveries_per_minute"
).group("DATE(requested_at)").order("date DESC")
}
# How many seconds it took to start the blast.
def start_latency
return if requested_at.nil? || started_at.nil?
started_at - requested_at
end
# How many seconds between the moment the blast was requested and the first email was delivered.
def first_email_delivery_latency
return if requested_at.nil? || first_email_delivered_at.nil?
first_email_delivered_at - requested_at
end
# How many seconds between the moment the blast was requested and the last email was delivered.
# When the blast is complete, this is the overall latency.
def last_email_delivery_latency
return if requested_at.nil? || last_email_delivered_at.nil?
last_email_delivered_at - requested_at
end
# How many emails were delivered per minute, on average, between the first and last email.
def deliveries_per_minute
return if first_email_delivered_at.nil? || last_email_delivered_at.nil?
delivery_count / (last_email_delivered_at - first_email_delivered_at) * 60.0
end
def self.acknowledge_email_delivery(blast_id, by: 1)
timestamp = Time.current.iso8601(6)
where(id: blast_id).update_all(
first_email_delivered_at: Arel.sql("COALESCE(first_email_delivered_at, ?)", timestamp),
last_email_delivered_at: timestamp,
delivery_count: Arel.sql("delivery_count + ?", by)
)
end
def self.format_datetime(time_with_zone)
return if time_with_zone.nil?
time_with_zone.to_fs(:db).delete_suffix(" UTC")
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/taxonomy.rb | app/models/taxonomy.rb | # frozen_string_literal: true
class Taxonomy < ApplicationRecord
has_closure_tree name_column: :slug
has_many :products, class_name: "Link"
has_one :taxonomy_stat, dependent: :destroy
validates :slug, presence: true, uniqueness: { scope: :parent_id }
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/community_chat_recap.rb | app/models/community_chat_recap.rb | # frozen_string_literal: true
class CommunityChatRecap < ApplicationRecord
belongs_to :community_chat_recap_run
belongs_to :community, optional: true
belongs_to :seller, class_name: "User", optional: true
validates :summarized_message_count, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :input_token_count, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :output_token_count, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :seller, presence: true, if: -> { status_finished? }
enum :status, { pending: "pending", finished: "finished", failed: "failed" }, prefix: true, validate: true
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/dispute.rb | app/models/dispute.rb | # frozen_string_literal: true
class Dispute < ApplicationRecord
has_paper_trail
include ExternalId
belongs_to :seller, class_name: "User", optional: true
belongs_to :purchase, optional: true
belongs_to :charge, optional: true
belongs_to :service_charge, optional: true
has_many :credits
has_many :balance_transactions
has_one :dispute_evidence
before_validation :assign_seller, on: :create, if: :disputable_has_seller?
validates :state, :event_created_at, presence: true
validates :seller, presence: true, if: :disputable_has_seller?
validate :disputable_must_be_present
validate :only_one_disputable_present
# Dispute state transitions:
#
# created β β β β initiated β β β β β closed
# β β
# β β β± won
# β β formalized β β β β ββ
# β³ lost
#
# created = A dispute has been created and is in the process of being recorded. All disputes will start in this state.
# initiated = A dispute has finished being created, has been initiated at the bank but is not formalized and does not yet have financial consequences.
# formalized = A dispute has finished being created, and is formalized, having financial consequences.
# won = A formalized dispute has been closed in our favor, the financial consequences were reversed in a Credit.
# lost = A formalized dispute has been closed in the payers favor.
#
# At the time of object creation a dispute may be initiated or formalized, because disputes will start in the initiated
# state if we are being told about the dispute before it's been formalized, or it may start in the formalized state immediately
# if the dispute is being created and already has financial consequences from day-one. For this reason the initial state is `nil`
# because there's no clear default initial state.
#
# Dispute objects are a new concept and there are many chargebacks recorded on purchases that do not have a dispute object.
# When an event occurs about an old dispute like won/lost, we're creating the dispute object then. So there may be disputes
# that have not gone through either the initiated or formalized state in 2015. This shouldn't be the case in 2016+.
#
state_machine :state, initial: :created do
after_transition any => any, :do => :log_transition
before_transition any => :initiated, do: ->(dispute) { dispute.initiated_at = Time.current }
before_transition any => :closed, do: ->(dispute) { dispute.closed_at = Time.current }
before_transition any => :formalized, do: ->(dispute) { dispute.formalized_at = Time.current }
before_transition any => :won, do: ->(dispute) { dispute.won_at = Time.current }
before_transition any => :lost, do: ->(dispute) { dispute.lost_at = Time.current }
event :mark_initiated do
transition [:created] => :initiated
end
event :mark_closed do
transition %i[created initiated] => :closed
end
event :mark_formalized do
transition %i[created initiated] => :formalized
end
event :mark_won do
transition %i[created formalized lost] => :won
end
event :mark_lost do
transition %i[created formalized won] => :lost
end
end
STRIPE_REASONS = %w[
credit_not_processed
duplicate
fraudulent
general
product_not_received
product_unacceptable
subscription_canceled
unrecognized
]
STRIPE_REASONS.each do |stripe_reason|
self.const_set("REASON_#{stripe_reason.upcase}", stripe_reason)
end
def disputable
charge || purchase || service_charge
end
def purchases
charge&.purchases || [purchase]
end
private
def log_transition
logger.info "Dispute: dispute ID #{id} transitioned to #{state}"
end
def disputable_must_be_present
return if disputable.present?
errors.add(:base, "A Disputable object must be provided.")
end
def only_one_disputable_present
errors.add(:base, "Only one Disputable object must be provided.") unless [charge, purchase, service_charge].one?(&:present?)
end
def disputable_has_seller? # this method exists because ServiceCharge does not have a seller
disputable.is_a?(Purchase) || disputable.is_a?(Charge)
end
def assign_seller
self.seller = disputable.seller
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_review_stat.rb | app/models/product_review_stat.rb | # frozen_string_literal: true
class ProductReviewStat < ApplicationRecord
belongs_to :link, optional: true
validates_presence_of :link
validates_uniqueness_of :link_id
RATING_COLUMN_MAP = {
1 => "ratings_of_one_count",
2 => "ratings_of_two_count",
3 => "ratings_of_three_count",
4 => "ratings_of_four_count",
5 => "ratings_of_five_count"
}.freeze
TEMPLATE = new.freeze
def rating_counts
RATING_COLUMN_MAP.transform_values { |column| attributes[column] }
end
def rating_percentages
return rating_counts if reviews_count.zero?
percentages = rating_counts.transform_values { (_1.to_f / reviews_count) * 100 }
# Increment ratings with the largest remainder so the total percentage is 100
remainders = percentages.map { |rating, percentage| [percentage % 1, rating] }.sort.reverse
threshold = remainders.sum(&:first).round
remainders[0...threshold].each { |_, rating| percentages[rating] += 1 }
percentages.transform_values(&:floor)
end
def update_with_added_rating(rating)
rating_column = RATING_COLUMN_MAP[rating]
update_ratings("#{rating_column} = #{rating_column} + 1")
end
def update_with_changed_rating(old_rating, new_rating)
old_rating_column = RATING_COLUMN_MAP[old_rating]
new_rating_column = RATING_COLUMN_MAP[new_rating]
update_ratings("#{old_rating_column} = #{old_rating_column} - 1, #{new_rating_column} = #{new_rating_column} + 1")
end
def update_with_removed_rating(rating)
rating_column = RATING_COLUMN_MAP[rating]
update_ratings("#{rating_column} = #{rating_column} - 1")
end
private
REVIEWS_COUNT_SQL = RATING_COLUMN_MAP.values.join(" + ").freeze
RATING_TOTAL_SQL = RATING_COLUMN_MAP.map { |value, column| "#{column} * #{value}" }.join(" + ").freeze
AVERAGE_RATING_SQL = "ROUND((#{RATING_TOTAL_SQL}) / reviews_count, 1)"
def update_ratings(assignment_list_sql)
self.class.where(id:).update_all <<~SQL.squish
#{assignment_list_sql},
reviews_count = #{REVIEWS_COUNT_SQL},
average_rating = #{AVERAGE_RATING_SQL},
updated_at = "#{Time.current.to_fs(:db)}"
SQL
reload
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/shipping_destination.rb | app/models/shipping_destination.rb | # frozen_string_literal: true
class ShippingDestination < ApplicationRecord
include CurrencyHelper
include ShippingDestination::Destinations
include FlagShihTzu
belongs_to :purchase, optional: true
belongs_to :user, optional: true
belongs_to :link, optional: true
has_flags 1 => :is_virtual_country,
:column => "flags",
:flag_query_mode => :bit_operator,
check_for_column: false
after_commit :invalidate_product_cache
validates :country_code, inclusion: { in: Destinations.shipping_countries.keys }
validates_presence_of :one_item_rate_cents
validates_presence_of :multiple_items_rate_cents
validates_absence_of :user_id, if: -> { link_id.present? }
validates_absence_of :link_id, if: -> { user_id.present? }
validates_uniqueness_of :country_code, scope: :user_id, conditions: -> { where("user_id is NOT NULL") }, case_sensitive: true
validates_uniqueness_of :country_code, scope: :link_id, conditions: -> { where("link_id is NOT NULL") }, case_sensitive: true
scope :alive, -> { where(deleted_at: nil) }
# Public - Calculates the shipping amount in USD based on the quantity and the applicable shipping rate
#
# Quantity - Quantity of items being purchased, determines the shipping rate (one/multiple) used
# Currency Type - The three-character string (code) representing the currency the product/shipping rate was configured in
#
# Returns nil if the quantity is less than 1. Returns a numeric value otherwise.
def calculate_shipping_rate(quantity: 0, currency_type: "usd")
return nil if quantity < 1
shipping_rate = get_usd_cents(currency_type, one_item_rate_cents)
shipping_rate += get_usd_cents(currency_type, multiple_items_rate_cents * (quantity - 1))
shipping_rate
end
def displayed_one_item_rate(currency_type, with_symbol: false)
MoneyFormatter.format(one_item_rate_cents, currency_type.to_sym, no_cents_if_whole: true, symbol: with_symbol)
end
def displayed_multiple_items_rate(currency_type, with_symbol: false)
MoneyFormatter.format(multiple_items_rate_cents, currency_type.to_sym, no_cents_if_whole: true, symbol: with_symbol)
end
def country_name
Destinations.shipping_countries[country_code]
end
def self.for_product_and_country_code(product: nil, country_code: nil)
return nil if country_code.nil? || product.nil?
return nil unless product.is_physical
virtual_countries = Destinations.virtual_countries_for_country_code(country_code)
shipping_destination = product.shipping_destinations.alive.where(country_code:).first
shipping_destination ||= product.shipping_destinations.alive.is_virtual_country.where("country_code IN (?)", virtual_countries).first
shipping_destination ||= product.shipping_destinations.alive.where(country_code: Product::Shipping::ELSEWHERE).first
shipping_destination
end
def country_or_countries
# TODO: (Anish) make ELSEWHERE a virtual country
if is_virtual_country || country_code == Destinations::ELSEWHERE
case country_code
when Destinations::EUROPE
Destinations.europe_shipping_countries
when Destinations::ASIA
Destinations.asia_shipping_countries
when Destinations::NORTH_AMERICA
Destinations.north_america_shipping_countries
else
Compliance::Countries.for_select.to_h
end
else
Destinations.shipping_countries.slice(country_code)
end.reject { |code, country| Compliance::Countries.blocked?(code) }
end
private
def invalidate_product_cache
link.invalidate_cache if link.present?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/variant.rb | app/models/variant.rb | # frozen_string_literal: true
class Variant < BaseVariant
include Variant::Prices
belongs_to :variant_category, optional: true
has_many :prices, class_name: "VariantPrice"
has_many :alive_prices, -> { alive }, class_name: "VariantPrice"
has_and_belongs_to_many :skus, join_table: :skus_variants
has_many :product_files_archives
has_many :subscription_plan_changes, foreign_key: "base_variant_id"
validates_presence_of :variant_category
validate :price_must_be_within_range
validates :duration_in_minutes, numericality: { greater_than: 0 }, if: -> { link.native_type == Link::NATIVE_TYPE_CALL }
before_create :set_position
after_save :set_customizable_price
delegate :link, to: :variant_category
delegate :user, to: :link
scope :in_order, -> { order(position_in_category: :asc, created_at: :asc) }
def alive_skus
skus.alive
end
def name_displayable
"#{link.name} (#{name})"
end
def has_prices?
prices.alive.exists? || link.is_tiered_membership
end
def as_json(options = {})
json = super(options)
if has_prices?
json["is_customizable_price"] = customizable_price.to_s == "true"
json["recurrence_price_values"] = recurrence_price_values(for_edit: true)
end
json
end
def recurrence_price_values(for_edit: false, subscription_attrs: nil)
recurrence_price_values = {}
BasePrice::Recurrence.all.each do |recurrence|
use_subscription_price = subscription_attrs.present? && subscription_attrs[:variants].include?(self) && recurrence == subscription_attrs[:recurrence]
price = (alive? && link.recurrence_price_enabled?(recurrence)) ? alive_prices.is_buy.find_by(recurrence:) : nil
# if rendering price info for a subscription, include the subscription's
# recurrence price even if it is deleted
if !price.present? && use_subscription_price
price = prices.is_buy.find { |p| p.recurrence == recurrence }
end
if for_edit
if price.present?
recurrence_price_values[recurrence] = {
enabled: true,
price_cents: price.price_cents,
suggested_price_cents: price.suggested_price_cents,
# TODO: :product_edit_react cleanup
price: price.price_formatted_without_symbol,
}
# TODO: :product_edit_react cleanup
recurrence_price_values[recurrence][:suggested_price] = price.suggested_price_formatted_without_symbol if price.suggested_price_cents.present?
else
recurrence_price_values[recurrence] = {
enabled: false
}
end
else
if price.present?
price_cents = use_subscription_price ? subscription_attrs[:price_cents] : price.price_cents
recurrence_price_values[recurrence] = {
price_cents:,
suggested_price_cents: price.suggested_price_cents,
}
end
end
end
recurrence_price_values
end
private
def set_position
return if self.position_in_category.present?
return unless variant_category
previous = variant_category.variants.alive.in_order.last
if previous
self.position_in_category = previous.position_in_category.present? ? previous.position_in_category + 1 : variant_category.variants.alive.in_order.count
else
self.position_in_category = 0
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_review_video.rb | app/models/product_review_video.rb | # frozen_string_literal: true
class ProductReviewVideo < ApplicationRecord
include ExternalId
include Deletable
belongs_to :product_review
has_one :video_file, as: :record, dependent: :destroy
validates :video_file, presence: true
accepts_nested_attributes_for :video_file
APPROVAL_STATUES = %w[pending_review approved rejected].freeze
enum :approval_status, APPROVAL_STATUES.index_by(&:itself), default: :pending_review
scope :editable, -> { where(approval_status: [:pending_review, :approved]) }
scope :latest, -> { order(created_at: :desc) }
APPROVAL_STATUES.each do |status|
define_method("#{status}!".to_sym) do
ProductReviewVideo.transaction do
product_review.with_lock do
product_review.videos
.where.not(id: id)
.where(approval_status: status)
.each(&:mark_deleted!)
super()
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/laos_bank_account.rb | app/models/laos_bank_account.rb | # frozen_string_literal: true
class LaosBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "LA"
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,18}$/
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::LAO.alpha2
end
def currency
Currency::LAK
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/wishlist.rb | app/models/wishlist.rb | # frozen_string_literal: true
class Wishlist < ApplicationRecord
include ExternalId, Deletable, FlagShihTzu
DEFAULT_NAME_MATCHER = /\AWishlist \d+\z/
belongs_to :user
has_many :wishlist_products
has_many :alive_wishlist_products, -> { alive }, class_name: "WishlistProduct"
has_many :products, through: :wishlist_products
has_many :wishlist_followers
has_flags 1 => :discover_opted_out
validates :name, presence: true
validates :description, length: { maximum: 3_000 }
before_save -> { update_recommendable(save: false) }
def self.find_by_url_slug(url_slug)
find_by_external_id_numeric(url_slug.split("-").last.to_i)
end
def url_slug
"#{name.parameterize}-#{external_id_numeric}"
end
def followed_by?(user)
wishlist_followers.alive.exists?(follower_user: user)
end
def wishlist_products_for_email
followers_last_contacted_at? ? wishlist_products.alive.where("created_at > ?", followers_last_contacted_at) : wishlist_products.alive
end
def update_recommendable(save: true)
self.recommendable = !discover_opted_out? && name !~ DEFAULT_NAME_MATCHER && !AdultKeywordDetector.adult?(name) && !AdultKeywordDetector.adult?(description) && alive_wishlist_products.any?
self.save if save
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/canadian_bank_account.rb | app/models/canadian_bank_account.rb | # frozen_string_literal: true
class CanadianBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "CANADIAN"
INSTITUTION_NUMBER_FORMAT_REGEX = /^\d{3}$/
TRANSIT_NUMBER_FORMAT_REGEX = /^\d{5}$/
private_constant :INSTITUTION_NUMBER_FORMAT_REGEX, :TRANSIT_NUMBER_FORMAT_REGEX
alias_attribute :institution_number, :bank_number
alias_attribute :transit_number, :branch_code
validate :validate_institution_number
validate :validate_transit_number
def routing_number
"#{transit_number}-#{institution_number}"
end
def bank_account_type
BANK_ACCOUNT_TYPE
end
def country
Compliance::Countries::CAN.alpha2
end
def currency
Currency::CAD
end
def to_hash
super.merge(
transit_number:,
institution_number:
)
end
private
def validate_institution_number
errors.add :base, "The institution number is invalid." unless INSTITUTION_NUMBER_FORMAT_REGEX.match?(institution_number)
end
def validate_transit_number
errors.add :base, "The transit number is invalid." unless TRANSIT_NUMBER_FORMAT_REGEX.match?(transit_number)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mongolia_bank_account.rb | app/models/mongolia_bank_account.rb | # frozen_string_literal: true
class MongoliaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "MN"
BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,12}$/
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::MNG.alpha2
end
def currency
Currency::MNT
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/namibia_bank_account.rb | app/models/namibia_bank_account.rb | # frozen_string_literal: true
class NamibiaBankAccount < BankAccount
BANK_ACCOUNT_TYPE = "NA"
BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/
ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{8,13}$/
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::NAM.alpha2
end
def currency
Currency::NAD
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.