repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/search_index_model_common.rb
app/models/concerns/search_index_model_common.rb
# frozen_string_literal: true module SearchIndexModelCommon extend ActiveSupport::Concern class_methods do def search_fields @_search_fields ||= mappings.to_hash[:properties].keys.map(&:to_s) end end def as_indexed_json(options = {}) fields = options[:only] || self.class.search_fields fields.index_with { |field_name| search_field_value(field_name) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/attribute_blockable.rb
app/models/concerns/attribute_blockable.rb
# frozen_string_literal: true # AttributeBlockable provides a flexible system for checking if model attributes # are blocked via the BlockedObject system, with support for efficient N+1 query # prevention through eager loading. # # == Basic Usage # # To make an attribute blockable, use the +attr_blockable+ class method: # # class User < ApplicationRecord # include AttributeBlockable # # attr_blockable :email # attr_blockable :form_email_domain, object_type: :email # end # # This generates several instance methods: # - +blocked_by_email?+ - Returns true if the email is blocked # - +blocked_by_email_object+ - Returns the BlockedObject record # - +block_by_email!+ - Blocks the email value # - +unblock_by_email!+ - Unblocks the email value # # == Preventing N+1 Queries # # When loading multiple records that need blocked attribute checks, use # +with_blocked_attributes_for+ to preload blocked status for all records # in a single MongoDB query: # # # Without preloading (N+1 queries) # users = User.where(verified: true) # users.each { |user| puts user.blocked_by_email? } # # # With preloading (single query) # users = User.where(verified: true) # .with_blocked_attributes_for(:email, :email_domain) # users.each { |user| puts user.blocked_by_email? } # # == Caching # # The concern uses an instance variable to cache blocked status. This cache is # automatically populated when using +with_blocked_attributes_for+ or lazily # loaded on first access. The cache is cleared on +reload+. # # == Introspection # # The concern tracks all blockable attributes defined on a model: # # User.blockable_attributes # # => [{ object_type: :email, blockable_method: :email }, # # { object_type: :email, blockable_method: :form_email }] # # User.blockable_method_names # # => [:email, :form_email] # # # Preload all blockable attributes automatically # User.with_all_blocked_attributes # # @example Admin controller with preloading # def index # @users = User.refund_queue # .includes(:payments) # .with_blocked_attributes_for(:form_email, :form_email_domain) # end # # @example Purchase model with multiple blockable attributes # class Purchase < ApplicationRecord # attr_blockable :email # attr_blockable :browser_guid # attr_blockable :ip_address # attr_blockable :charge_processor_fingerprint # end # module AttributeBlockable extend ActiveSupport::Concern # Returns the cache hash for blocked attribute lookups. # Structure: { "method_name" => blocked_object_or_nil } # # @return [Hash] Cache of blocked attribute statuses def blocked_by_attributes @blocked_by_attributes ||= {}.with_indifferent_access end def reload(*) @blocked_by_attributes = nil super end included do class_attribute :blockable_attributes, instance_writer: false, default: [] end # Provides the +with_blocked_attributes_for+ scope method for ActiveRecord relations. module RelationMethods # Eagerly loads blocked attribute status for the specified methods. # This prevents N+1 queries by fetching all BlockedObjects in a single query. # # @param method_names [Array<Symbol, String>] Names of blockable attributes to preload # @return [ActiveRecord::Relation] Chainable relation with preloading configured # # @example Preload multiple attributes # User.with_blocked_attributes_for(:email, :email_domain) # # @example Chain with other scopes # User.where(verified: true) # .with_blocked_attributes_for(:email) # .order(created_at: :desc) def with_blocked_attributes_for(*method_names) spawn.tap { |relation| relation.extending!(BlockedAttributesPreloader.new(*method_names)) } end end # Internal module that handles the actual preloading logic by extending # ActiveRecord relations and hooking into query execution. # # @private class BlockedAttributesPreloader < Module # @param method_names [Array<Symbol, String>] Attribute names to preload def initialize(*method_names) @method_names = Array.wrap(method_names).map(&:to_s) super() end # Called when this module extends a relation. Sets up preloading hooks. # # @param relation [ActiveRecord::Relation] The relation being extended # @return [ActiveRecord::Relation] The extended relation def extended(relation) add_method_to_preload_list(relation) override_exec_queries(relation) define_preloading_methods(relation) relation end private # Adds method names to the relation's preload list, merging with any # existing methods from previous +with_blocked_attributes_for+ calls. def add_method_to_preload_list(relation) existing_methods = relation.instance_variable_get(:@_blocked_attributes_methods) || Set.new relation.instance_variable_set(:@_blocked_attributes_methods, Set.new(existing_methods + @method_names)) end # Overrides the relation's +exec_queries+ method to trigger preloading # after records are fetched from the database. def override_exec_queries(relation) relation.define_singleton_method(:exec_queries) do |&block| @records = super(&block) preload_blocked_attributes! unless relation.instance_variable_get(:@_blocked_attributes_preloaded) @records end end # Defines the preloading methods on the relation instance. def define_preloading_methods(relation) # Iterates through all registered method names and preloads their blocked status relation.define_singleton_method(:preload_blocked_attributes!) do return if @records.blank? (@_blocked_attributes_methods || Set.new).each do |method_name| preload_blocked_attribute_for_method(method_name) end relation.instance_variable_set(:@_blocked_attributes_preloaded, true) end # Preloads blocked status for a single attribute across all records # in the relation using a single MongoDB query. # # @param method_name [String] The attribute method name relation.define_singleton_method(:preload_blocked_attribute_for_method) do |method_name| values = @records.filter_map { |record| record.try(method_name).presence }.uniq return if values.empty? # Look up the actual object type from the blockable_attributes registry # For example: form_email maps to :email, form_email_domain maps to :email_domain model_class = @records.first.class blockable_config = model_class.blockable_attributes.find { |attr| attr[:blockable_method] == method_name.to_sym } attribute_type = blockable_config ? blockable_config[:object_type] : method_name.to_sym scope = BLOCKED_OBJECT_TYPES.fetch(attribute_type, :all) blocked_objects_by_value = BlockedObject.send(scope).find_active_objects(values).index_by(&:object_value) @records.each do |record| value = record.send(method_name) blocked_object = blocked_objects_by_value[value] record.blocked_by_attributes[method_name] = blocked_object end end end end module ClassMethods # Defines blockable attribute methods for the given attribute. # # Generates the following instance methods: # - +blocked_by_{method}?+ - Returns true if the value is currently blocked # - +blocked_by_{method}_object+ - Returns the BlockedObject record # - +block_by_{method}!+ - Blocks the attribute value # - +unblock_by_{method}!+ - Unblocks the attribute value # # @param blockable_method [Symbol, String] The method name to make blockable # @param object_type [Symbol, String, nil] The BlockedObject type to use (defaults to blockable_method) # # @example Basic usage # attr_blockable :email # # user.blocked_by_email? # # user.blocked_by_email_object&.blocked_at # # user.block_by_email!(by_user_id: current_user.id) # # @example With custom attribute mapping # attr_blockable :form_email, object_type: :email # # Uses 'email' BlockedObject type but creates form_email methods # # @example Blocking with expiration # user.block_by_email!( # by_user_id: admin.id, # expires_in: 30.days # ) def attr_blockable(blockable_method, object_type: nil) object_type ||= blockable_method define_method("blocked_by_#{blockable_method}?") { blocked_object_by_method(object_type, blockable_method:)&.blocked? || false } define_method("blocked_by_#{blockable_method}_object") do blocked_object_by_method(object_type, blockable_method:) end define_method("block_by_#{blockable_method}!") do |by_user_id: nil, expires_in: nil| return if (value = send(blockable_method)).blank? blocked_object = BlockedObject.block!(object_type, value, by_user_id, expires_in:) blocked_by_attributes[blockable_method.to_s] = blocked_object end define_method("unblock_by_#{blockable_method}!") do return if (value = send(blockable_method)).blank? scope = BLOCKED_OBJECT_TYPES.fetch(object_type.to_sym, :all) BlockedObject.send(scope).find_objects([value]).each do |blocked_object| blocked_object.unblock! blocked_by_attributes.delete(blockable_method.to_s) end end # Register this blockable attribute for introspection self.blockable_attributes = blockable_attributes + [{ object_type: object_type.to_sym, blockable_method: blockable_method.to_sym }] end # Returns an array of all blockable method names defined on this model. # Useful for automatically preloading all blockable attributes. # # @return [Array<Symbol>] Array of blockable method names # # @example # User.blockable_method_names # # => [:email, :form_email, :form_email_domain] def blockable_method_names blockable_attributes.map { |attr| attr[:blockable_method] } end # Preloads all registered blockable attributes for this model. # Convenience method that automatically calls +with_blocked_attributes_for+ # with all blockable methods defined via +attr_blockable+. # # @return [ActiveRecord::Relation] Relation with all blockable attributes preloaded # # @example # User.with_all_blocked_attributes # # Equivalent to: User.with_blocked_attributes_for(:email, :form_email, :form_email_domain) def with_all_blocked_attributes with_blocked_attributes_for(*blockable_method_names) end # Class-level version of +with_blocked_attributes_for+ for use on model classes. # # @param method_names [Array<Symbol, String>] Names of blockable attributes to preload # @return [ActiveRecord::Relation] Relation with preloading configured # # @example # User.with_blocked_attributes_for(:email, :email_domain) def with_blocked_attributes_for(*method_names) all.extending(RelationMethods).with_blocked_attributes_for(*method_names) end end def blocked_object_by_method(object_type, blockable_method: nil) blockable_method ||= object_type method_key = blockable_method.to_s return blocked_by_attributes[method_key] if blocked_by_attributes.key?(method_key) value = send(blockable_method) return if value.blank? blocked_object = blocked_object_for_value(object_type, value) blocked_by_attributes[method_key] = blocked_object blocked_object end # Retrieves BlockedObject records for the given values and attribute type. # # @param method_name [Symbol, String] The BlockedObject type # @param values [Array<String>] Values to look up # @return [Array<BlockedObject>] Array of BlockedObject records # # @example # user.blocked_objects_for_values(:email, ['email1@example.com', 'email2@example.com']) def blocked_objects_for_values(method_name, values) scope = BLOCKED_OBJECT_TYPES.fetch(method_name.to_sym, :all) BlockedObject.send(scope).find_active_objects(values) end private # Retrieves a single BlockedObject for the given value. # # @param method_name [Symbol, String] The BlockedObject type # @param value [String] Value to look up # @return [BlockedObject, nil] The BlockedObject or nil if not found def blocked_object_for_value(method_name, value) scope = BLOCKED_OBJECT_TYPES.fetch(method_name.to_sym, :all) BlockedObject.send(scope).find_active_object(value) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/secure_external_id.rb
app/models/concerns/secure_external_id.rb
# frozen_string_literal: true # A concern to generate and resolve secure, expiring, encrypted, URL-safe tokens # that represent a model instance. It supports key rotation. # # Configuration: # This module requires configuration in your config/credentials.yml.enc or environment variables via GlobalConfig. # The configuration should contain a primary key version and a list of encryption keys for generating secure tokens. # You must provide a primary key version and a list of keys. # The primary key is used for encrypting new tokens. All keys are available for decryption. # # @example in `config/credentials.yml.enc` # # secure_external_id: # primary_key_version: '1' # This MUST be a string # keys: # '1': 'a_very_secure_secret_key_for_v1' # 32 bytes for aes-256-gcm # '2': 'a_different_secure_key_for_v2' # 32 bytes for aes-256-gcm # module SecureExternalId extend ActiveSupport::Concern class Error < StandardError; end class InvalidToken < Error; end class KeyNotFound < Error; end # Generates a secure, URL-safe token for the model instance. # # @param scope [String] The scope of the token. # @param expires_at [Time, nil] The optional expiration timestamp for the token. # @return [String] The versioned, encrypted, URL-safe token. def secure_external_id(scope:, expires_at: nil) self.class.encrypt_id(id, scope: scope, expires_at: expires_at) end class_methods do # Finds a record by its secure external ID. # # @param token [String] The token to decrypt and use for finding the record. # @param scope [String] The expected scope of the token. # @return [ActiveRecord::Base, nil] The model instance if the token is valid, not expired, # for the correct model, and has the correct scope; otherwise nil. def find_by_secure_external_id(token, scope:) record_id = decrypt_id(token, scope: scope) find_by(id: record_id) if record_id end # Encrypts a record's ID into a secure, URL-safe token. # This is a low-level method; prefer using the instance method `secure_external_id`. # # @param id [String, Integer] The ID of the record. # @param scope [String] The scope of the token. # @param expires_at [Time, nil] The optional expiration timestamp for the token. # @return [String] The versioned, encrypted, URL-safe token. def encrypt_id(id, scope:, expires_at: nil) version = primary_key_version encryptor = encryptors[version] raise KeyNotFound, "Primary key version '#{version}' not found" unless encryptor inner_payload = { model: name, id: id, exp: expires_at&.to_i, scp: scope } encrypted_data = encryptor.encrypt_and_sign(inner_payload.to_json) outer_payload = { v: version, d: encrypted_data } Base64.urlsafe_encode64(outer_payload.to_json, padding: false) end # Decrypts a token to retrieve a record's ID if the token is valid. # This is a low-level method; prefer using `find_by_secure_external_id`. # # @param token [String] The token to decrypt. # @param scope [String] The expected scope of the token. # @return [String, Integer, nil] The ID if the token is valid; otherwise nil. def decrypt_id(token, scope:) return nil unless token.is_a?(String) decoded_json = Base64.urlsafe_decode64(token) outer_payload = JSON.parse(decoded_json, symbolize_names: true) version = outer_payload[:v] encrypted_data = outer_payload[:d] return nil if version.blank? || encrypted_data.blank? encryptor = encryptors[version] return nil unless encryptor # Invalid version decrypted_json = encryptor.decrypt_and_verify(encrypted_data) inner_payload = JSON.parse(decrypted_json, symbolize_names: true) return nil if inner_payload[:model] != name return nil if inner_payload[:scp] != scope return nil if inner_payload[:exp] && Time.current.to_i > inner_payload[:exp] inner_payload[:id] rescue JSON::ParserError, ArgumentError, ActiveSupport::MessageEncryptor::InvalidMessage => e Rails.logger.error "SecureExternalId decryption failed: #{e.class}" nil end private def config @config ||= begin raw_config = GlobalConfig.dig(:secure_external_id, default: nil) || build_config_from_env validate_config!(raw_config) raw_config end end def build_config_from_env primary_key_version = GlobalConfig.dig(:secure_external_id, :primary_key_version, default: nil) return {} if primary_key_version.blank? # Build the keys hash from environment variables # Looks for SECURE_EXTERNAL_ID__KEYS__1, SECURE_EXTERNAL_ID__KEYS__2, etc. keys = {} (1..10).each do |version| key = GlobalConfig.dig(:secure_external_id, :keys, version.to_s, default: nil) keys[version.to_s] = key if key.present? end { primary_key_version: primary_key_version, keys: keys } end def validate_config!(config) raise Error, "SecureExternalId configuration is missing" if config.blank? raise Error, "primary_key_version is required in SecureExternalId config" if config[:primary_key_version].blank? raise Error, "keys are required in SecureExternalId config" if config[:keys].blank? keys_hash = config[:keys].with_indifferent_access raise Error, "Primary key version '#{config[:primary_key_version]}' not found in keys" unless keys_hash.key?(config[:primary_key_version]) keys_hash.each do |version, key| raise Error, "Key for version '#{version}' must be exactly 32 bytes for aes-256-gcm" unless key.bytesize == 32 end end def primary_key_version config[:primary_key_version] end def encryptors @encryptors ||= (config[:keys] || {}).transform_values do |key| ActiveSupport::MessageEncryptor.new(key, cipher: "aes-256-gcm") end.with_indifferent_access end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/json_data.rb
app/models/concerns/json_data.rb
# frozen_string_literal: true # Mixin for modules that contain a `json_data` field. Adds functions that # standardize how data is stored within the `json_data` field, and what happens # if the data within is not present or blank. # # All functions are safe to call when `json_data` is nil and it does not need # to be initialized before use. module JsonData extend ActiveSupport::Concern included do serialize :json_data, coder: JSON end class_methods do # Public: Defines both reader and writer methods for an attributes # stored within json_data. # Can be used with a single attribute at a time. # * attribute – the name of the attribute, as a symbol # * default – the value that will be returned by the reader if the value is blank # the default may be a lambda, Proc, or a static value. def attr_json_data_accessor(attribute, default: nil) attr_json_data_reader(attribute, default:) attr_json_data_writer(attribute) end # Public: Defines reader methods for attributes in json_data. # Can be used with a single attribute at a time. # * attribute – the name of the attribute, as a symbol # * default – the value that will be returned if the value is blank # the default may be a lambda, Proc, or a static value. def attr_json_data_reader(attribute, default: nil) define_method(attribute) do default_value = default.try(:respond_to?, :call) ? instance_exec(&default) : default json_data_for_attr(attribute.to_s, default: default_value) end end # Public: Defines writer methods for attributes in json_data. # Can be used with a single attribute at a time. # * attribute – the name of the attribute, as a symbol def attr_json_data_writer(attribute) define_method("#{attribute}=") do |value| set_json_data_for_attr(attribute.to_s, value) end end end # Public: Returns the json_data field, instantiating it to an empty hash if # it is not already set. def json_data self[:json_data] ||= {} raise ArgumentError, "json_data must be a hash" unless self[:json_data].is_a?(Hash) self[:json_data].deep_stringify_keys! end # Public: Sets the attribute on the json_data of this object, such that # calling with attribute 'attr' and value 'value' will result in a json_data # field containing: # { 'attr' => 'value' } def set_json_data_for_attr(attribute, value) json_data[attribute] = value end # Public: Gets the value for an attribute on the json_data of this object, such that # calling with attribute 'attr' of the following json_data would return 'value': # { 'attr' => 'value' } # # If the attr is not present in the json_data, the value passed as the default will be returned. def json_data_for_attr(attribute, default: nil) return json_data[attribute] if json_data && json_data[attribute].present? default end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/with_filtering.rb
app/models/concerns/with_filtering.rb
# frozen_string_literal: true module WithFiltering extend ActiveSupport::Concern include CurrencyHelper, JsonData AUDIENCE_TYPE = "audience" SELLER_TYPE = "seller" PRODUCT_TYPE = "product" VARIANT_TYPE = "variant" FOLLOWER_TYPE = "follower" AFFILIATE_TYPE = "affiliate" ABANDONED_CART_TYPE = "abandoned_cart" included do attr_json_data_accessor :variant attr_json_data_accessor :bought_products attr_json_data_accessor :not_bought_products attr_json_data_accessor :paid_more_than_cents attr_json_data_accessor :paid_less_than_cents attr_json_data_accessor :created_after attr_json_data_accessor :created_before attr_json_data_accessor :bought_from attr_json_data_accessor :bought_variants attr_json_data_accessor :not_bought_variants attr_json_data_accessor :affiliate_products # Name of the column containing the recipient type. # i.e. "installment_type" (Installment) and "workflow_type" (Workflow) mattr_reader :recipient_type_column, default: "#{model_name.singular}_type" scope :audience_type, -> { where(recipient_type_column => AUDIENCE_TYPE) } scope :seller_type, -> { where(recipient_type_column => SELLER_TYPE) } scope :product_type, -> { where(recipient_type_column => PRODUCT_TYPE) } scope :variant_type, -> { where(recipient_type_column => VARIANT_TYPE) } scope :follower_type, -> { where(recipient_type_column => FOLLOWER_TYPE) } scope :affiliate_type, -> { where(recipient_type_column => AFFILIATE_TYPE) } scope :abandoned_cart_type, -> { where(recipient_type_column => ABANDONED_CART_TYPE) } scope :product_or_variant_type, -> { where(recipient_type_column => [PRODUCT_TYPE, VARIANT_TYPE]) } scope :seller_or_audience_type, -> { where(recipient_type_column => [SELLER_TYPE, AUDIENCE_TYPE]) } scope :follower_or_audience_type, -> { where(recipient_type_column => [FOLLOWER_TYPE, AUDIENCE_TYPE]) } scope :affiliate_or_audience_type, -> { where(recipient_type_column => [AFFILIATE_TYPE, AUDIENCE_TYPE]) } scope :seller_or_product_or_variant_type, -> { where(recipient_type_column => [SELLER_TYPE, PRODUCT_TYPE, VARIANT_TYPE]) } end def audience_type? = attributes[self.recipient_type_column] == AUDIENCE_TYPE def seller_type? = attributes[self.recipient_type_column] == SELLER_TYPE def product_type? = attributes[self.recipient_type_column] == PRODUCT_TYPE def variant_type? = attributes[self.recipient_type_column] == VARIANT_TYPE def follower_type? = attributes[self.recipient_type_column] == FOLLOWER_TYPE def affiliate_type? = attributes[self.recipient_type_column] == AFFILIATE_TYPE def abandoned_cart_type? = attributes[self.recipient_type_column] == ABANDONED_CART_TYPE def product_or_variant_type? = product_type? || variant_type? def seller_or_product_or_variant_type? = seller_type? || product_or_variant_type? def add_and_validate_filters(params, user) currency = user.currency_type self.paid_more_than_cents = if seller_or_product_or_variant_type? if params[:paid_more_than_cents].present? params[:paid_more_than_cents] elsif params[:paid_more_than].present? get_usd_cents(currency, (params[:paid_more_than].to_f * unit_scaling_factor(currency)).to_i) end end self.paid_less_than_cents = if seller_or_product_or_variant_type? if params[:paid_less_than_cents].present? params[:paid_less_than_cents] elsif params[:paid_less_than].present? get_usd_cents(currency, (params[:paid_less_than].to_f * unit_scaling_factor(currency)).to_i) end end self.bought_products = (!audience_type? && params[:bought_products].present?) ? Array.wrap(params[:bought_products]) : [] self.not_bought_products = params[:not_bought_products].present? ? Array.wrap(params[:not_bought_products]) : [] # created "on and after" this timestamp: self.created_after = params[:created_after].present? ? Date.parse(params[:created_after]).in_time_zone(user.timezone) : nil # created "on and before" this timestamp: self.created_before = params[:created_before].present? ? Date.parse(params[:created_before]).in_time_zone(user.timezone).end_of_day : nil self.bought_from = seller_or_product_or_variant_type? ? params[:bought_from].presence : nil self.bought_variants = (!audience_type? && params[:bought_variants].present?) ? Array.wrap(params[:bought_variants]) : [] self.not_bought_variants = params[:not_bought_variants].present? ? Array.wrap(params[:not_bought_variants]) : [] self.affiliate_products = (!audience_type? && params[:affiliate_products].present?) ? Array.wrap(params[:affiliate_products]) : [] self.workflow_trigger = seller_or_product_or_variant_type? ? params[:workflow_trigger].presence : nil if paid_more_than_cents.present? && paid_less_than_cents.present? && paid_more_than_cents > paid_less_than_cents errors.add(:base, "Please enter valid paid more than and paid less than values.") return false end if created_after.present? && created_before.present? && created_after > created_before errors.add(:base, "Please enter valid before and after dates.") return false end true end def affiliate_passes_filters(affiliate) return false if created_after.present? && affiliate.created_at < created_after return false if created_before.present? && affiliate.created_at > created_before return false if affiliate_products.present? && (affiliate_products & affiliate.products.pluck(:unique_permalink)).empty? true end def follower_passes_filters(follower) return false if created_after.present? && follower.created_at < created_after return false if created_before.present? && follower.created_at > created_before true end def purchase_passes_filters(purchase) params = purchase.slice(:email, :country, :ip_country) params[:min_created_at] = purchase.created_at params[:max_created_at] = purchase.created_at params[:min_price_cents] = purchase.price_cents params[:max_price_cents] = purchase.price_cents params[:product_permalinks] = [purchase.link.unique_permalink] params[:variant_external_ids] = purchase.variant_attributes.map(&:external_id) seller_post_passes_filters(**params.symbolize_keys) end def seller_post_passes_filters(email: nil, min_created_at: nil, max_created_at: nil, min_price_cents: nil, max_price_cents: nil, country: nil, ip_country: nil, product_permalinks: [], variant_external_ids: []) return false if created_after.present? && (min_created_at.nil? || (min_created_at.present? && min_created_at < created_after)) return false if created_before.present? && (max_created_at.nil? || (max_created_at.present? && max_created_at > created_before)) excludes_product = bought_products.present? && (product_permalinks.empty? || (bought_products & product_permalinks).empty?) excludes_variants = bought_variants.present? && (variant_external_ids.empty? || (bought_variants & variant_external_ids).empty?) if bought_products.present? && bought_variants.present? return false if excludes_product && excludes_variants elsif bought_products.present? return false if excludes_product elsif bought_variants.present? return false if excludes_variants end return false if paid_more_than_cents.present? && (min_price_cents.nil? || (min_price_cents.present? && min_price_cents < paid_more_than_cents)) return false if paid_less_than_cents.present? && (max_price_cents.nil? || (max_price_cents.present? && max_price_cents > paid_less_than_cents)) return false if bought_from.present? && !(country == bought_from || (country.nil? && ip_country == bought_from)) exclude_product_ids = not_bought_products.present? ? Link.find_by(unique_permalink: not_bought_products)&.id : [] return false if (exclude_product_ids.present? || not_bought_variants.present?) && seller.sales .not_is_archived_original_subscription_purchase .not_subscription_or_original_purchase .by_external_variant_ids_or_products(not_bought_variants, exclude_product_ids) .exists?(email:) true end def json_filters json = {} json[:bought_products] = bought_products if bought_products.present? json[:not_bought_products] = not_bought_products if not_bought_products.present? json[:not_bought_variants] = not_bought_variants if not_bought_variants.present? json[:bought_variants] = bought_variants if bought_variants.present? if paid_more_than_cents.present? json[:paid_more_than] = Money.new(paid_more_than_cents, seller.currency_type) .format(no_cents_if_whole: true, symbol: false) end if paid_less_than_cents.present? json[:paid_less_than] = Money.new(paid_less_than_cents, seller.currency_type) .format(no_cents_if_whole: true, symbol: false) end json[:created_after] = convert_to_date(created_after) if created_after.present? json[:created_before] = convert_to_date(created_before) if created_before.present? json[:bought_from] = bought_from if bought_from.present? json[:affiliate_products] = affiliate_products if affiliate_products.present? json[:workflow_trigger] = workflow_trigger if workflow_trigger.present? json end def convert_to_date(date) date.is_a?(String) ? Date.parse(date) : date end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/max_purchase_count.rb
app/models/concerns/max_purchase_count.rb
# frozen_string_literal: true module MaxPurchaseCount extend ActiveSupport::Concern MAX_PURCHASE_COUNT_RANGE = (0 .. 10_000_000) included do before_validation :constrain_max_purchase_count_within_range validates_numericality_of :max_purchase_count, in: MAX_PURCHASE_COUNT_RANGE, allow_nil: true end def constrain_max_purchase_count_within_range return if max_purchase_count.nil? self.max_purchase_count = max_purchase_count.clamp(MAX_PURCHASE_COUNT_RANGE) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/transactional_attribute_change_tracker.rb
app/models/concerns/transactional_attribute_change_tracker.rb
# frozen_string_literal: true # Tracks all the attributes that were changed in a transaction, # and makes them available in `#attributes_committed` when the transaction is committed. # This module exists because `previous_changes` only contains the attributes that were changed in the last `save`, # if the record was not `reload`ed during the transaction. # Caveats: # - if an attribute is saved twice in the same transaction, and goes back to its original value, it will still be tracked in `#attributes_committed` module TransactionalAttributeChangeTracker extend ActiveSupport::Concern included do attr_reader :attributes_committed after_save do @attributes_committed = nil (@attributes_changed_in_transaction ||= Set.new).merge(previous_changes.keys) end before_commit do next unless @attributes_changed_in_transaction @attributes_committed = @attributes_changed_in_transaction.to_a @attributes_changed_in_transaction.clear end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/rich_contents.rb
app/models/concerns/rich_contents.rb
# frozen_string_literal: true module RichContents extend ActiveSupport::Concern included do has_many :rich_contents, as: :entity has_many :alive_rich_contents, -> { alive }, class_name: "RichContent", as: :entity end def rich_content_folder_name(folder_id) return if folder_id.blank? folder = alive_rich_contents .lazy .flat_map(&:description) .find do |node| node["type"] == RichContent::FILE_EMBED_GROUP_NODE_TYPE && node.dig("attrs", "uid") == folder_id end folder ? folder.dig("attrs", "name").to_s : nil end def rich_content_json if is_a?(BaseVariant) return [] if link.has_same_rich_content_for_all_variants? variant_id = self.external_id end alive_rich_contents.sort_by(&:position).map do |content| { id: content.external_id, # TODO (product_edit_react) remove duplicate ID page_id: content.external_id, title: content.title, variant_id:, description: { type: "doc", content: content.description }, updated_at: content.updated_at } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/unused_columns.rb
app/models/concerns/unused_columns.rb
# frozen_string_literal: true # This module allows marking certain columns as unused on a model. # For large tables, removing columns can be an expensive operation. It is often preferable to collect # multiple columns and remove them in a batch. # This serves as a temporary alternative to `self.ignored_columns`, which can make queries unreadable. # # When attempting to access or assign a value to these columns, a NoMethodError will be raised, # indicating that the column is not being used. # # Example usage: # # class Purchase < ApplicationRecord # unused_columns :custom_fields, :deleted_at # end # # Purchase.unused_attributes # # => ["custom_fields", "deleted_at"] # # purchase = Purchase.new # purchase.custom_fields # # => raises NoMethodError: Column custom_fields is not being used. # # purchase.custom_fields = "some value" # # => raises NoMethodError: Column custom_fields is not being used. module UnusedColumns extend ActiveSupport::Concern class_methods do def unused_columns(*columns) @_unused_attributes = columns.map(&:to_s) columns.each do |column| # Allow creating a custom getter that matches the column name unless method_defined?(column) define_method(column) do raise NoMethodError, "Column #{column} is deprecated and no longer used." end end define_method(:"#{column}=") do |_value| raise NoMethodError, "Column #{column} is deprecated and no longer used." end end end def unused_attributes @_unused_attributes || [] end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/versionable.rb
app/models/concerns/versionable.rb
# frozen_string_literal: true # Requires has_paper_trail on the model # module Versionable extend ActiveSupport::Concern # Reasonable limit of version records to query LIMIT = 100 VersionInfoStruct = Struct.new(:created_at, :changes) # It returns a collection of VersionInfoStruct objects that contain changes from # at least one of the fields provided # def versions_for(*fields) attributes = fields.map(&:to_s) versions .reorder("id DESC") .limit(LIMIT) .map { |v| build_version_info(v, attributes) } .compact .select { |info| (info.changes.keys & attributes.map(&:to_s)).any? } end private def build_version_info(version, attributes) return if version.object_changes.blank? VersionInfoStruct.new( version.created_at, PaperTrail.serializer.load(version.object_changes).slice(*attributes) ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/charge_processable.rb
app/models/concerns/charge_processable.rb
# frozen_string_literal: true module ChargeProcessable def stripe_charge_processor? charge_processor_id == StripeChargeProcessor.charge_processor_id end def paypal_charge_processor? charge_processor_id == PaypalChargeProcessor.charge_processor_id end def braintree_charge_processor? charge_processor_id == BraintreeChargeProcessor.charge_processor_id end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/streamable.rb
app/models/concerns/streamable.rb
# frozen_string_literal: true module Streamable extend ActiveSupport::Concern included do has_many :transcoded_videos, as: :streamable end def attempt_to_transcode?(allowed_when_processing: false) # Don't transcode if another transcoding job is already pending for this particular video. return false if !allowed_when_processing && transcoded_videos.alive.processing.exists?(original_video_key: s3_key) # Don't transcode if the video is already transcoded. return false if transcoded_videos.alive.completed.exists?(original_video_key: s3_key) true end def transcodable? streamable? && height.present? && width.present? end def transcoding_in_progress? streamable? && transcoded_videos.alive.processing.exists?(original_video_key: s3_key) end def transcoding_failed end def streamable? true end # This method returns a string representing the secured m3u8 HLS playlist # content for this product file. # # This method can return nil if there are no transcoded videos for the # product file. def hls_playlist last_hls_transcoded_video = transcoded_videos.alive.is_hls.completed.last return nil if last_hls_transcoded_video.nil? playlist_key = last_hls_transcoded_video.transcoded_video_key hls_key_prefix = "#{File.dirname(playlist_key)}/" # Extract path without the filename playlist_s3_object = Aws::S3::Resource.new.bucket(S3_BUCKET).object(playlist_key) playlist = playlist_s3_object.get.body.read playlist_content_with_signed_urls = "" playlist.split("\n").each do |playlist_line| if playlist_line.start_with?("#") playlist_content_with_signed_urls += "#{playlist_line}\n" next end resolution_specific_playlist_key = playlist_line resolution_specific_playlist_key.prepend(hls_key_prefix) # Escape the user-provided portion of the URL, which is the original file # name. Note that the ProductFile could have been renamed by now. That's # why we get the original file name from the hls_key_prefix, which comes # from the TranscodedVideo object that was created when the video was # originally transcoded. original_file_name = if hls_key_prefix.include?("/original/") hls_key_prefix[%r{/original/(.*?)/hls}m, 1] else hls_key_prefix[%r{attachments/.*/(.*?)/hls}m, 1] end resolution_specific_playlist_key.gsub!( original_file_name, CGI.escape(original_file_name) ) signed_resolution_specific_playlist_url = signed_cloudfront_url( "#{HLS_DISTRIBUTION_URL}#{resolution_specific_playlist_key}", is_video: true ) playlist_content_with_signed_urls += "#{signed_resolution_specific_playlist_url}\n" end playlist_content_with_signed_urls end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/timestamp_state_fields.rb
app/models/concerns/timestamp_state_fields.rb
# frozen_string_literal: true # Implements ActiveRecord state fields based on timestamp columns. # # Requires a column to be named `property_at`, e.g., `verified_at`. # # `state` method uses reverse order of states to determine priority. E.g., it # checks the last state in the fields first to determine if the object is in # that state. # # Example: # # class User < ActiveRecord::Base # include TimestampStateFields # timestamp_state_fields :subscribed, :verified, default_state: :created # end # # u = User.new # u.subscribed_at # => "2015-11-15 22:51:13 -0800" # u.subscribed? # => true # u.not_subscribed? # => false # u.state # => :subscribed # u.state_subscribed? # => true # u.state_verified? # => false # u.update_as_verified! # u.state # => :verified # u.update_as_not_subscribed! # # User.subscribed.count # Number of subscribed users # User.subscribed.not_verified.count # Number of unsubscribed users that are not verified # module TimestampStateFields extend ActiveSupport::Concern class_methods do def timestamp_state_fields(*names, default_state: :created, states_excluded_from_default: []) names.map(&:to_s).each do |name| column_name = "#{name}_at" define_singleton_method(:"#{name}") { where.not(column_name => nil) } define_singleton_method(:"not_#{name}") { where(column_name => nil) } define_method(:"#{name}?") { send(column_name).present? } define_method(:"not_#{name}?") { send(column_name).blank? } define_method(:"update_as_#{name}!") do |options = {}| update!(options.merge(column_name => Time.current)) end define_method(:"update_as_not_#{name}!") do |options = {}| update!(options.merge(column_name => nil)) end define_method(:"state_#{name}?") do state == name.to_sym end end define_method(:"state_#{default_state}?") do state == default_state end define_method(:state) do names.reverse_each do |name| next if states_excluded_from_default.include?(name) return name.to_sym if send(:"#{name}?") end default_state 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/concerns/installment/searchable.rb
app/models/concerns/installment/searchable.rb
# frozen_string_literal: true module Installment::Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model include SearchIndexModelCommon include ElasticsearchModelAsyncCallbacks index_name "installments" settings number_of_shards: 1, number_of_replicas: 0, index: { analysis: { filter: { autocomplete_filter: { type: "edge_ngram", min_gram: 1, max_gram: 20, token_chars: %w[letter digit] } }, analyzer: { name: { tokenizer: "whitespace", filter: %w[lowercase autocomplete_filter] }, search_name: { tokenizer: "whitespace", filter: "lowercase" }, message: { tokenizer: "whitespace", filter: "lowercase", char_filter: ["html_strip"] }, search_message: { tokenizer: "whitespace", filter: "lowercase", char_filter: ["html_strip"] } } } } mapping dynamic: :strict do indexes :id, type: :long indexes :message, type: :text, analyzer: :message, search_analyzer: :search_message indexes :name, type: :text, analyzer: :name, search_analyzer: :search_name indexes :seller_id, type: :long indexes :workflow_id, type: :long indexes :created_at, type: :date indexes :deleted_at, type: :date indexes :published_at, type: :date indexes :selected_flags, type: :keyword end ATTRIBUTE_TO_SEARCH_FIELDS = { "id" => "id", "name" => "name", "message" => "message", "seller_id" => "seller_id", "workflow_id" => "workflow_id", "created_at" => "created_at", "deleted_at" => "deleted_at", "published_at" => "published_at", "flags" => "selected_flags", } def search_field_value(field_name) case field_name when "selected_flags" selected_flags.map(&:to_s) else attributes[field_name] end.as_json end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/native_type_templates.rb
app/models/concerns/product/native_type_templates.rb
# frozen_string_literal: true module Product::NativeTypeTemplates extend ActiveSupport::Concern DEFAULT_ATTRIBUTES_FOR_TYPE = { podcast: [ { name: "Episodes", value: "" }, { name: "Total length", value: "" } ], ebook: [ { name: "Pages", value: "" } ], audiobook: [ { name: "Length", value: "" } ], }.freeze PRODUCT_TYPES_THAT_INCLUDE_LAST_POST = ["membership", "newsletter"].freeze def set_template_properties_if_needed return if self.native_type.blank? save_custom_attributes(DEFAULT_ATTRIBUTES_FOR_TYPE[self.native_type.to_sym]) if DEFAULT_ATTRIBUTES_FOR_TYPE.key? self.native_type.to_sym self.should_include_last_post = true if PRODUCT_TYPES_THAT_INCLUDE_LAST_POST.include?(native_type) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/taxonomies.rb
app/models/concerns/product/taxonomies.rb
# frozen_string_literal: true module Product::Taxonomies extend ActiveSupport::Concern include Purchase::Searchable::ProductCallbacks included do belongs_to :taxonomy, optional: true end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/bundles_marketing.rb
app/models/concerns/product/bundles_marketing.rb
# frozen_string_literal: true module Product::BundlesMarketing YEAR_BUNDLE = "year" BEST_SELLING_BUNDLE = "best_selling" EVERYTHING_BUNDLE = "everything" BUNDLE_NAMES = { YEAR_BUNDLE => "#{1.year.ago.year} Bundle", BEST_SELLING_BUNDLE => "Best Selling Bundle", EVERYTHING_BUNDLE => "Everything Bundle" }.freeze end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/as_json.rb
app/models/concerns/product/as_json.rb
# frozen_string_literal: true module Product::AsJson extend ActiveSupport::Concern included do alias super_as_json as_json end def as_json(options = {}) return super(options) if options.delete(:original) return as_json_for_admin_info if options.delete(:admin_info) return as_json_for_api(options) if options[:api_scopes].present? return as_json_for_mobile_api if options.delete(:mobile) return as_json_variant_details_only if options.delete(:variant_details_only) json = super(only: %i[name description require_shipping preview_url]).merge!( "id" => unique_permalink, "external_id" => external_id, "price" => default_price_cents, "currency" => price_currency_type, "short_url" => long_url, "formatted_price" => price_formatted_verbose, "recommendable" => recommendable?, "rated_as_adult" => rated_as_adult?, "hide_sold_out_variants" => hide_sold_out_variants?, ) json["custom_delivery_url"] = nil # Deprecated if preorder_link.present? json.merge!( "is_preorder" => true, "is_in_preorder_state" => is_in_preorder_state, "release_at" => preorder_link.release_at.to_s ) end json end private def as_json_for_admin_info as_json( original: true, only: %i[ purchase_type ], methods: %i[ external_id long_url alive recommendable staff_picked is_in_preorder_state has_stampable_pdfs streamable is_physical is_licensed is_adult has_adult_keywords ], include: { user: { methods: :all_adult_products }, tags: { methods: :humanized_name }, active_integrations: { only: :type } } ).merge( taxonomy: taxonomy.as_json(methods: :ancestry_path), type: product_type_label, formatted_rental_price_cents: MoneyFormatter.format(rental_price_cents, price_currency_type.to_sym, no_cents_if_whole: true, symbol: true), ) end def as_json_for_api(options) keep = %w[ name description require_shipping preview_url custom_receipt customizable_price custom_permalink subscription_duration ] cached_default_price_cents = default_price_cents ppp_factors = purchasing_power_parity_enabled? ? options[:preloaded_ppp_factors] || PurchasingPowerParityService.new.get_all_countries_factors(user) : nil json = as_json(original: true, only: keep).merge!( "id" => external_id, "url" => nil, # Deprecated "price" => cached_default_price_cents, "currency" => price_currency_type, "short_url" => long_url, "thumbnail_url" => thumbnail&.alive&.url.presence, "tags" => tags.pluck(:name), "formatted_price" => price_formatted_verbose, "published" => alive?, "file_info" => multifile_aware_product_file_info, "max_purchase_count" => max_purchase_count, "deleted" => deleted_at.present?, "custom_fields" => custom_field_descriptors.as_json, "custom_summary" => custom_summary, "is_tiered_membership" => is_tiered_membership?, "recurrences" => is_tiered_membership? ? prices.alive.is_buy.map(&:recurrence).uniq : nil, "variants" => variant_categories_alive.map do |cat| { title: cat.title, options: cat.alive_variants.map do |variant| { name: variant.name, price_difference: variant.price_difference_cents, is_pay_what_you_want: variant.customizable_price?, recurrence_prices: is_tiered_membership? ? variant.recurrence_price_values : nil, url: nil, # Deprecated } end.map do ppp_factors.blank? ? _1 : _1.merge({ purchasing_power_parity_prices: _1[:price_difference].present? ? compute_ppp_prices(_1[:price_difference] + cached_default_price_cents, ppp_factors, currency) : nil, recurrence_prices: _1[:recurrence_prices]&.transform_values do |v| v.merge({ purchasing_power_parity_prices: compute_ppp_prices(v[:price_cents], ppp_factors, currency) }) end, }) end } end ) if preorder_link.present? json.merge!( "is_preorder" => true, "is_in_preorder_state" => is_in_preorder_state, "release_at" => preorder_link.release_at.to_s ) end if ppp_factors.present? json["purchasing_power_parity_prices"] = compute_ppp_prices(cached_default_price_cents, ppp_factors, currency) end if options[:api_scopes].include?("view_sales") json["custom_delivery_url"] = nil # Deprecated json["sales_count"] = successful_sales_count json["sales_usd_cents"] = total_usd_cents end json end def compute_ppp_prices(price_cents, factors, currency) factors.keys.index_with do |country_code| price_cents == 0 ? 0 : [factors[country_code] * price_cents, currency["min_price"]].max.round end end def as_json_for_mobile_api as_json(original: true, only: %w[name description unique_permalink]).merge!( created_at:, updated_at:, content_updated_at: content_updated_at || created_at, creator_name: user.name_or_username || "", creator_username: user.username || "", creator_profile_picture_url: user.avatar_url, creator_profile_url: user.profile_url, preview_url: preview_oembed_thumbnail_url || preview_url || "", thumbnail_url: thumbnail&.alive&.url.presence, preview_oembed_url: mobile_oembed_url, preview_height: preview_height_for_mobile, preview_width: preview_width_for_mobile, has_rich_content: true ) end def as_json_variant_details_only variants = { categories: {}, skus: {}, skus_enabled: false } return variants if variant_categories_alive.empty? && !skus_enabled? variant_categories_alive.each do |category| category_hash = { title: category.title.present? ? category.title : "Version", options: {} } category.variants.alive.each do |variant| category_hash[:options][variant.external_id] = variant.as_json(for_views: true) end variants[:categories][category.external_id] = category_hash end if skus_enabled? skus.not_is_default_sku.alive.each do |sku| variants[:skus][sku.external_id] = sku.as_json(for_views: true) end variants[:skus_title] = sku_title variants[:skus_enabled] = true end variants end private def product_type_label return "Product" unless is_recurring_billing? return "Membership" if is_tiered_membership? "Subscription" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/structured_data.rb
app/models/concerns/product/structured_data.rb
# frozen_string_literal: true module Product::StructuredData extend ActiveSupport::Concern include ActionView::Helpers::SanitizeHelper def structured_data return {} unless native_type == Link::NATIVE_TYPE_EBOOK data = { "@context" => "https://schema.org", "@type" => "Book", "name" => name, "author" => { "@type" => "Person", "name" => user.name }, "description" => product_description, "url" => long_url } work_examples = build_book_work_examples data["workExample"] = work_examples if work_examples.any? data end private def build_book_work_examples book_files = alive_product_files.select(&:supports_isbn?) book_files.map do |file| work_example = { "@type" => "Book", "bookFormat" => "EBook", "name" => "#{name} (#{file.filetype.upcase})" } work_example["isbn"] = file.isbn if file.isbn.present? work_example end end def product_description (custom_summary.presence || strip_tags(html_safe_description).presence) .to_s .truncate(160) .presence end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/sorting.rb
app/models/concerns/product/sorting.rb
# frozen_string_literal: true module Product::Sorting extend ActiveSupport::Concern ES_SORT_KEYS = ["display_price_cents", "is_recommendable"] SQL_SORT_KEYS = ["name", "successful_sales_count", "status", "taxonomy", "display_product_reviews", "revenue", "cut"] SORT_KEYS = ES_SORT_KEYS + SQL_SORT_KEYS SORT_KEYS.each do |key| const_set(key.upcase, key) end class_methods do def sorted_by(key: nil, direction: nil, user_id:) direction = direction == "desc" ? "desc" : "asc" case key when NAME order(name: direction) when CUT joins(:affiliates) .joins(:product_affiliates) .order(Arel.sql("CASE WHEN links.user_id = #{user_id} THEN 10000 - affiliates_links.affiliate_basis_points ELSE affiliates_links.affiliate_basis_points END #{direction}")) when SUCCESSFUL_SALES_COUNT with_latest_product_cached_values(user_id:).order("latest_product_cached_values.successful_sales_count" => direction) when STATUS order(Arel.sql("links.purchase_disabled_at IS NULL #{direction}")) when TAXONOMY order(Arel.sql("links.taxonomy_id IS NULL #{direction}")) when DISPLAY_PRODUCT_REVIEWS order(Arel.sql("links.flags & #{Link.flag_mapping["flags"][:display_product_reviews]} #{direction}")) when REVENUE with_latest_product_cached_values(user_id:).order("latest_product_cached_values.total_usd_cents" => direction) else all end end def elasticsearch_sorted_and_paginated_by(key: nil, direction: nil, page:, per_page:, user_id:) direction = direction == "desc" ? "desc" : "asc" sort = nil case key when DISPLAY_PRICE_CENTS sort = direction == "desc" ? ProductSortKey::AVAILABLE_PRICE_DESCENDING : ProductSortKey::AVAILABLE_PRICE_ASCENDING when IS_RECOMMENDABLE sort = direction == "desc" ? ProductSortKey::IS_RECOMMENDABLE_DESCENDING : ProductSortKey::IS_RECOMMENDABLE_ASCENDING else return { page: 1, pages: 1 }, self end response = Link.search(Link.search_options( { user_id:, ids: self.pluck(:id), sort:, size: per_page, from: per_page * (page.to_i - 1) + 1 } )) pages = (response.results.total / per_page.to_f).ceil return { page:, pages: }, response.records end def elasticsearch_key?(key) ES_SORT_KEYS.include?(key) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/staff_picked.rb
app/models/concerns/product/staff_picked.rb
# frozen_string_literal: true module Product::StaffPicked extend ActiveSupport::Concern def staff_picked? return false if staff_picked_product.blank? staff_picked_product.not_deleted? end alias_method :staff_picked, :staff_picked? def staff_picked_at return if staff_picked_product.blank? || staff_picked_product.deleted? staff_picked_product.updated_at end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/layout.rb
app/models/concerns/product/layout.rb
# frozen_string_literal: true module Product::Layout PROFILE = "profile" DISCOVER = "discover" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/product/tags.rb
app/models/concerns/product/tags.rb
# frozen_string_literal: true module Product::Tags extend ActiveSupport::Concern included do has_many :product_taggings, foreign_key: :product_id, dependent: :destroy has_many :tags, through: :product_taggings scope :with_tags, lambda { |tag_names| if tag_names.present? && tag_names.any? joins(:tags) .where("tags.name IN (?)", tag_names) .group("links.id") .having("COUNT(tags.id) >= ?", tag_names.count) else all end } end def tag!(name) name = name.downcase product_tagging = product_taggings.new tag = Tag.find_by(name:) || Tag.new if tag.new_record? tag.name = name tag.save! end product_tagging.tag = tag product_tagging.save! end def has_tag?(name) tags.pluck(:name).include?(name.downcase) end def untag!(name) product_taggings.where(tag: Tag.find_by(name:)).destroy_all if has_tag?(name) end def save_tags!(tag_list) tag_list = {} if tag_list.blank? # TODO: Remove support for non-array argument when product edit page is migrated to React tags_to_save = tag_list.is_a?(Array) ? tag_list : tag_list.values.map(&:downcase) (tags.pluck(:name) - tags_to_save).each { |tag_to_remove| untag!(tag_to_remove) } (tags_to_save - tags.pluck(:name)).each { |tag_to_add| tag!(tag_to_add) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/recommendation_type.rb
app/models/concerns/user/recommendation_type.rb
# frozen_string_literal: true module User::RecommendationType TYPES = [ "no_recommendations", "own_products", "gumroad_affiliates_products", "directly_affiliated_products" ].freeze TYPES.each do |type| self.const_set(type.upcase, type) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/social_apple.rb
app/models/concerns/user/social_apple.rb
# frozen_string_literal: true module User::SocialApple extend ActiveSupport::Concern class_methods do def find_for_apple_auth(authorization_code:, app_type:) email = verified_apple_id_email(authorization_code:, app_type:) return if email.blank? User.find_by(email:) end private def verified_apple_id_email(authorization_code:, app_type:) client = AppleID::Client.new(apple_id_client_options[app_type]) client.authorization_code = authorization_code token_response = client.access_token! id_token = token_response.id_token id_token.verify!( client:, access_token: token_response.access_token, verify_signature: false ) id_token.email if id_token.email_verified? rescue AppleID::Client::Error => e Rails.logger.error "[Apple login error] #{e.full_message}" nil end def apple_id_client_options { Device::APP_TYPES[:consumer] => { identifier: GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_IDENTIFIER"), team_id: GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_TEAM_ID"), key_id: GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_KEY_ID"), private_key: OpenSSL::PKey::EC.new(GlobalConfig.get("IOS_CONSUMER_APP_APPLE_LOGIN_PRIVATE_KEY")), }, Device::APP_TYPES[:creator] => { identifier: GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_IDENTIFIER"), team_id: GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_TEAM_ID"), key_id: GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_KEY_ID"), private_key: OpenSSL::PKey::EC.new(GlobalConfig.get("IOS_CREATOR_APP_APPLE_LOGIN_PRIVATE_KEY")), } } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/comments.rb
app/models/concerns/user/comments.rb
# frozen_string_literal: true module User::Comments extend ActiveSupport::Concern def add_payout_note(content:) comments.create!( content:, author_id: GUMROAD_ADMIN_ID, comment_type: Comment::COMMENT_TYPE_PAYOUT_NOTE ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/vip_creator.rb
app/models/concerns/user/vip_creator.rb
# frozen_string_literal: true module User::VipCreator extend ActiveSupport::Concern def vip_creator? recent_gross_sales_cents > 5_000_00 end private def recent_gross_sales_cents search_params = { seller: self, state: Purchase::CHARGED_SUCCESS_STATES, exclude_giftees: true, exclude_refunded: true, exclude_unreversed_chargedback: true, exclude_bundle_product_purchases: true, exclude_commission_completion_purchases: true, created_after: 30.days.ago, aggs: { price_cents_total: { sum: { field: "price_cents" } } }, size: 0 } result = PurchaseSearchService.search(search_params) result.aggregations.price_cents_total.value end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/direct_affiliates.rb
app/models/concerns/user/direct_affiliates.rb
# frozen_string_literal: true module User::DirectAffiliates extend ActiveSupport::Concern included do has_many :direct_affiliates, foreign_key: :seller_id, class_name: "DirectAffiliate" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/taxation.rb
app/models/concerns/user/taxation.rb
# frozen_string_literal: true module User::Taxation extend ActiveSupport::Concern include Compliance MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING = 5_000 * 100 # Ref https://docs.stripe.com/connect/1099-K for state filing thresholds MIN_SALE_AMOUNTS_FOR_1099_K_STATE_FILINGS = { "AL" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Alabama "AR" => 2_500 * 100, # Arkansas "CA" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # California "DC" => 600 * 100, # District of Columbia "FL" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Florida "GA" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Georgia "HI" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Hawaii "IL" => 1_000 * 100, # Illinois "ME" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Maine "MA" => 600 * 100, # Massachusetts "MT" => 600 * 100, # Montana "NJ" => 1_000 * 100, # New Jersey "NY" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # New York "OR" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Oregon "TN" => MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING, # Tennessee "VA" => 600 * 100, # Virginia } MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING = 600 * 100 # Ref https://docs.stripe.com/connect/1099-MISC for state filing thresholds MIN_AFFILIATE_AMOUNTS_FOR_1099_MISC_STATE_FILINGS = { "AR" => 2_500 * 100, # Arkansas "CA" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # California "DC" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # District of Columbia "HI" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # Hawaii "ME" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # Maine "MA" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # Massachusetts "MT" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # Montana "NJ" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # New Jersey "OR" => MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING, # Oregon } def eligible_for_1099_k?(year) return false unless is_a_non_suspended_creator_from_usa? return false unless eligible_for_1099_k_federal_filing?(year) || eligible_for_1099_k_state_filing?(year) true end def eligible_for_1099_k_federal_filing?(year) sales_scope_for(year).sum(:total_transaction_cents) >= MIN_SALE_AMOUNT_FOR_1099_K_FEDERAL_FILING end def eligible_for_1099_k_state_filing?(year) state = alive_user_compliance_info.legal_entity_state return false unless MIN_SALE_AMOUNTS_FOR_1099_K_STATE_FILINGS.key?(state) return false unless sales_scope_for(year).sum(:total_transaction_cents) >= MIN_SALE_AMOUNTS_FOR_1099_K_STATE_FILINGS[state] true end def eligible_for_1099_misc?(year) return false unless is_a_non_suspended_creator_from_usa? return false unless eligible_for_1099_misc_federal_filing?(year) || eligible_for_1099_misc_state_filing?(year) true end def eligible_for_1099_misc_federal_filing?(year) affiliate_sales_scope_for(year).sum(:affiliate_credit_cents) >= MIN_AFFILIATE_AMOUNT_FOR_1099_MISC_FEDERAL_FILING end def eligible_for_1099_misc_state_filing?(year) state = alive_user_compliance_info.legal_entity_state return false unless MIN_AFFILIATE_AMOUNTS_FOR_1099_MISC_STATE_FILINGS.key?(state) return false unless affiliate_sales_scope_for(year).sum(:affiliate_credit_cents) >= MIN_AFFILIATE_AMOUNTS_FOR_1099_MISC_STATE_FILINGS[state] true end def eligible_for_1099?(year) return false unless is_a_non_suspended_creator_from_usa? eligible_for_1099_k?(year) || eligible_for_1099_misc?(year) end def is_a_non_suspended_creator_from_usa? return false if suspended? return false unless from_us? true end def from_us? alive_user_compliance_info&.country_code == Compliance::Countries::USA.alpha2 end private def sales_scope_for(year) range = Date.new(year).in_time_zone(timezone).all_year sales.successful.not_fully_refunded.not_chargedback_or_chargedback_reversed .where("purchases.price_cents > 0") .where(paypal_order_id: nil) .where.not(merchant_account_id: merchant_accounts.select { _1.is_a_stripe_connect_account? }.map(&:id)) .where(created_at: range) end def affiliate_sales_scope_for(year) range = Date.new(year).in_time_zone(timezone).all_year affiliate_sales.successful.not_fully_refunded.not_chargedback_or_chargedback_reversed.where(created_at: range) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/low_balance_fraud_check.rb
app/models/concerns/user/low_balance_fraud_check.rb
# frozen_string_literal: true module User::LowBalanceFraudCheck extend ActiveSupport::Concern LOW_BALANCE_THRESHOLD = -100_00 # USD -100 private_constant :LOW_BALANCE_THRESHOLD LOW_BALANCE_PROBATION_WAIT_TIME = 2.months private_constant :LOW_BALANCE_PROBATION_WAIT_TIME LOW_BALANCE_FRAUD_CHECK_AUTHOR_NAME = "LowBalanceFraudCheck" private_constant :LOW_BALANCE_FRAUD_CHECK_AUTHOR_NAME def enable_refunds! self.refunds_disabled = false save! end def disable_refunds! self.refunds_disabled = true save! end def check_for_low_balance_and_probate(refunded_or_disputed_purchase_id) return if unpaid_balance_cents > LOW_BALANCE_THRESHOLD AdminMailer.low_balance_notify(id, refunded_or_disputed_purchase_id).deliver_later disable_refunds_and_put_on_probation! unless recently_probated_for_low_balance? || suspended? end private def disable_refunds_and_put_on_probation! disable_refunds! content = "Probated (payouts suspended) automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of suspicious refund activity" self.put_on_probation(author_name: LOW_BALANCE_FRAUD_CHECK_AUTHOR_NAME, content:) end def recently_probated_for_low_balance? comments.with_type_on_probation .where(author_name: LOW_BALANCE_FRAUD_CHECK_AUTHOR_NAME) .where("created_at > ?", LOW_BALANCE_PROBATION_WAIT_TIME.ago) .exists? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/stripe_connect.rb
app/models/concerns/user/stripe_connect.rb
# frozen_string_literal: true module User::StripeConnect extend ActiveSupport::Concern class_methods do def find_or_create_for_stripe_connect_account(data) return nil if data.blank? user = MerchantAccount.where(charge_processor_merchant_id: data["uid"]).alive .find { |ma| ma.is_a_stripe_connect_account? }&.user if user.nil? ActiveRecord::Base.transaction do user = User.new user.provider = :stripe_connect email = data["info"]["email"] user.email = email if EmailFormatValidator.valid?(email) user.name = data["info"]["name"] user.password = Devise.friendly_token[0, 20] user.skip_confirmation! user.save! user.user_compliance_infos.build.tap do |new_user_compliance_info| new_user_compliance_info.country = Compliance::Countries.mapping[data["extra"]["extra_info"]["country"]] new_user_compliance_info.json_data = {} new_user_compliance_info.save! end if user.email.present? Purchase.where(email: user.email, purchaser_id: nil).each do |past_purchase| past_purchase.attach_to_user_and_card(user, nil, nil) end end end end user rescue ActiveRecord::RecordInvalid => e logger.error("Error creating user via Stripe Connect: #{e.message}") unless e.message.include?("An account already exists with this email.") nil end end def has_brazilian_stripe_connect_account? !!merchant_account(StripeChargeProcessor.charge_processor_id)&.is_a_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/concerns/user/as_json.rb
app/models/concerns/user/as_json.rb
# frozen_string_literal: true module User::AsJson extend ActiveSupport::Concern def as_json(options = {}) result = if options[:internal_use] || valid_api_scope?(options) super(only: %i[name bio twitter_handle currency_type], methods: options[:methods], include: options[:include]) .merge(common_fields_for_as_json) .merge(profile_url: avatar_url, email: form_email) else super(only: %i[name bio twitter_handle]) .compact .merge(common_fields_for_as_json) end if view_profile_scope?(options) result[:display_name] = display_name end if options[:internal_use] result.merge!(internal_use_fields_for_as_json) end result.with_indifferent_access end private def view_profile_scope?(options) api_scopes_options(options).include?("view_profile") end def valid_api_scope?(options) (%w[edit_products view_sales revenue_share ifttt view_profile] & api_scopes_options(options)).present? end def api_scopes_options(options) Array(options[:api_scopes]) end def common_fields_for_as_json { id: external_id, user_id: ObfuscateIds.encrypt(id), url: profile_url, links: (links.presence && links.alive.map(&:general_permalink)), } end def internal_use_fields_for_as_json { created_at:, sign_in_count:, current_sign_in_at:, last_sign_in_at:, current_sign_in_ip:, last_sign_in_ip:, purchases_count: purchases.count, successful_purchases_count: purchases.successful_or_preorder_authorization_successful.count, } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/purchases.rb
app/models/concerns/user/purchases.rb
# frozen_string_literal: true module User::Purchases extend ActiveSupport::Concern def transfer_purchases!(new_email:) new_user = User.find_by!(email: new_email) purchases = Purchase.where(email:) transaction do purchases.find_each do |purchase| purchase.email = new_email purchase.purchaser_id = new_user.id purchase.save! 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/concerns/user/mailer_level.rb
app/models/concerns/user/mailer_level.rb
# frozen_string_literal: true module User::MailerLevel extend ActiveSupport::Concern MAILER_LEVEL_REDIS_EXPIRY = 1.week def mailer_level # Use Memcached cache to reduce the number of queries to Redis Rails.cache.fetch("creator_mailer_level_#{id}", expires_in: 2.days) do level_from_redis = mailer_level_redis_namespace.get(mailer_level_cache_key) return level_from_redis.to_sym if level_from_redis.present? level = mailer_level_from_sales_cents(sales_cents_total) # Store in Redis for persistent caching mailer_level_redis_namespace.set(mailer_level_cache_key, level, ex: MAILER_LEVEL_REDIS_EXPIRY.to_i) level end end private def mailer_level_from_sales_cents(sales_cents) case when sales_cents <= 10_000_00 # USD 10K :level_1 else :level_2 end end def mailer_level_cache_key "creator_mailer_level_#{id}" end def mailer_level_redis_namespace @_user_mailer_redis_namespace ||= Redis::Namespace.new(:user_mailer_redis_namespace, redis: $redis) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/social_google.rb
app/models/concerns/user/social_google.rb
# frozen_string_literal: true module User::SocialGoogle extend ActiveSupport::Concern def google_picture_url(data) return nil if data["info"]["image"].nil? || data["info"]["image"].empty? pic_url = data["info"]["image"] # Replacing all instances of "s96-c" in the string with "s400-c" to get a larger image pic_url = pic_url.gsub("s96-c", "s400-c") pic_url = URI(URI::DEFAULT_PARSER.escape(pic_url)) URI.open(pic_url) do |remote_file| tempfile = Tempfile.new(binmode: true) tempfile.write(remote_file.read) tempfile.rewind self.avatar.attach(io: tempfile, filename: File.basename(pic_url.to_s), content_type: remote_file.content_type) self.avatar.blob.save! end self.avatar.analyze unless self.avatar.attached? self.avatar_url rescue StandardError nil end class_methods do def find_or_create_for_google_oauth2(data) if data["uid"].blank? Bugsnag.notify("Google OAuth2 data is missing a uid") return nil end user = User.where(google_uid: data["uid"]).first if user.nil? email = data["info"]["email"] || data["extra"]["raw_info"]["email"] user = User.where(email:).first if EmailFormatValidator.valid?(email) if user.nil? user = User.new user.provider = :google_oauth2 user.password = Devise.friendly_token[0, 20] query_google(user, data, new_user: true) if user.email.present? Purchase.where(email: user.email, purchaser_id: nil).each do |past_purchase| past_purchase.attach_to_user_and_card(user, nil, nil) end end else query_google(user, data) end else query_google(user, data) end user rescue ActiveRecord::RecordInvalid => e logger.error("Error finding or creating user via Google OAuth2: #{e.message}") Bugsnag.notify(e) nil end def query_google(user, data, new_user: false) return if data.blank? || data.is_a?(String) email = data["info"]["email"] || data["extra"]["raw_info"]["email"] # Don't set user properties if they already have values user.google_uid ||= data["uid"] user.name ||= data["info"]["name"] # Always update user's email upon log in as it may have changed # on google's side # https://support.google.com/accounts/answer/19870?hl=en if EmailFormatValidator.valid?(email) && user.email&.downcase != email.downcase user.email = email end # Set user's avatar if they don't have one user.google_picture_url(data) unless user.avatar.attached? user.skip_confirmation_notification! user.save! user.confirm if user.has_unconfirmed_email? user end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/team.rb
app/models/concerns/user/team.rb
# frozen_string_literal: true module User::Team extend ActiveSupport::Concern included do has_many :user_memberships, class_name: "TeamMembership", foreign_key: :user_id has_many :seller_memberships, class_name: "TeamMembership", foreign_key: :seller_id has_many :team_invitations, foreign_key: :seller_id has_many :admin_manageable_user_memberships, -> { not_deleted.role_not_owner.order(last_accessed_at: :desc, created_at: :desc) }, class_name: "TeamMembership", foreign_key: :user_id end def member_of?(seller) role_owner_for?(seller) || team_member_of?(seller) end # Needed for seller accounts where there are no team memberships def role_owner_for?(seller) seller == self end def role_accountant_for?(seller) role_owner_for?(seller) || find_user_membership_for_seller!(seller).role_accountant? end def role_admin_for?(seller) role_owner_for?(seller) || find_user_membership_for_seller!(seller).role_admin? end def role_marketing_for?(seller) role_owner_for?(seller) || find_user_membership_for_seller!(seller).role_marketing? end def role_support_for?(seller) role_owner_for?(seller) || find_user_membership_for_seller!(seller).role_support? end def user_memberships_not_deleted_and_ordered # Returns an array to ensure this is only queried once per request @_user_memberships_not_deleted_and_ordered ||= user_memberships .not_deleted .order(last_accessed_at: :desc, created_at: :desc) .to_a end def find_user_membership_for_seller!(seller) team_membership = user_memberships_not_deleted_and_ordered.find { _1.seller_id == seller.id } # Raise to document the fact that the record is expected to exist raise ActiveRecord::RecordNotFound if team_membership.nil? team_membership end # In order to avoid creating one owner TeamMembership record for all users, the record is created only when # the seller is part of a team of a **different** seller (so they can switch back to their account) # For that reason, seller that are not part of a team don't have this record # def create_owner_membership_if_needed! return if user_memberships.one?(&:role_owner?) user_memberships.create!(seller: self, role: TeamMembership::ROLE_OWNER) end def gumroad_account? email == ApplicationMailer::ADMIN_EMAIL end private def team_member_of?(seller) find_user_membership_for_seller!(seller).present? rescue ActiveRecord::RecordNotFound false end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/followers.rb
app/models/concerns/user/followers.rb
# frozen_string_literal: true module User::Followers extend ActiveSupport::Concern included do has_many :followers, foreign_key: "followed_id" end def follower_by_email(email) Follower.active.find_by(followed_id: id, email:) end def followed_by?(email) follower_by_email(email).present? end def following Follower.includes(:user) .active .where(email: form_email) .where.not(followed_id: id) .map { |follower| { external_id: follower.external_id, creator: follower.user } } end def add_follower(email, options = {}) follower_attributes = options.dup logged_in_user = follower_attributes.delete(:logged_in_user) Follower::CreateService.perform( followed_user: self, follower_email: email, follower_attributes:, logged_in_user: ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/affiliated_products.rb
app/models/concerns/user/affiliated_products.rb
# frozen_string_literal: true module User::AffiliatedProducts extend ActiveSupport::Concern def directly_affiliated_products(alive: true) scope = Link.with_direct_affiliates scope = scope.merge(DirectAffiliate.alive).alive if alive scope.for_affiliate_user(id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/user/social_google_mobile.rb
app/models/concerns/user/social_google_mobile.rb
# frozen_string_literal: true module User::SocialGoogleMobile extend ActiveSupport::Concern class_methods do def find_for_google_mobile_auth(google_id_token:) email = email_from_google_id_token(google_id_token:) return if email.blank? User.find_by(email:) end private def email_from_google_id_token(google_id_token:) key_source = Google::Auth::IDTokens::JwkHttpKeySource.new(Google::Auth::IDTokens::OAUTH2_V3_CERTS_URL) verifier = Google::Auth::IDTokens::Verifier.new(key_source:) client_id = GlobalConfig.get("GOOGLE_CLIENT_ID") begin payload = verifier.verify(google_id_token) audience = payload["aud"] email_verified = payload["email_verified"] payload["email"] if audience == client_id && email_verified rescue nil 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/concerns/follower/audience_member.rb
app/models/concerns/follower/audience_member.rb
# frozen_string_literal: true module Follower::AudienceMember extend ActiveSupport::Concern included do after_save :update_audience_member_details after_destroy :remove_from_audience_member_details end def should_be_audience_member? confirmed_at.present? && EmailFormatValidator.valid?(email) end def audience_member_details { id:, created_at: } end private def update_audience_member_details return unless confirmed_at_previously_changed? || email_previously_changed? remove_from_audience_member_details(email_previously_was) if email_previously_changed? && !previously_new_record? return remove_from_audience_member_details unless should_be_audience_member? member = AudienceMember.find_or_initialize_by(email:, seller: user) member.details["follower"] = audience_member_details member.save! end def remove_from_audience_member_details(email = attributes["email"]) member = AudienceMember.find_by(email:, seller: user) return if member.nil? member.details.delete("follower") member.valid? ? member.save! : member.destroy! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/affiliate/cookies.rb
app/models/concerns/affiliate/cookies.rb
# frozen_string_literal: true module Affiliate::Cookies extend ActiveSupport::Concern AFFILIATE_COOKIE_NAME_PREFIX = "_gumroad_affiliate_id_" class_methods do def by_cookies(cookies) in_order_of(:id, ids_from_cookies(cookies)) end def ids_from_cookies(cookies) cookies .sort_by { |cookie| -cookie[1].to_i }.map(&:first) .filter_map do |cookie_name| next unless cookie_name&.starts_with?(AFFILIATE_COOKIE_NAME_PREFIX) next unless (cookie_id = extract_cookie_id_from_cookie_name(cookie_name)) decrypt_cookie_id(cookie_id) end end def extract_cookie_id_from_cookie_name(cookie_name) CGI.unescape(cookie_name).delete_prefix(AFFILIATE_COOKIE_NAME_PREFIX) end # Decrypts cookie ID back to raw affiliate ID # Handles both padded (ABC123==) and unpadded (ABC123) base64 formats for backward compatibility def decrypt_cookie_id(cookie_id) ObfuscateIds.decrypt(cookie_id) end end def cookie_key "#{AFFILIATE_COOKIE_NAME_PREFIX}#{cookie_id}" end def cookie_id ObfuscateIds.encrypt(id, padding: false) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/affiliate/audience_member.rb
app/models/concerns/affiliate/audience_member.rb
# frozen_string_literal: true module Affiliate::AudienceMember extend ActiveSupport::Concern included do after_save :update_audience_member_details after_destroy :remove_from_audience_member_details end def update_audience_member_with_added_product(product_or_id) return unless persisted? && type == "DirectAffiliate" && should_be_audience_member? product_id = product_or_id.is_a?(Link) ? product_or_id.id : product_or_id member = AudienceMember.find_or_initialize_by(email: affiliate_user.email, seller:) return if member.details["affiliates"]&.any? { _1["id"] == id && _1["product_id"] == product_id } member.details["affiliates"] ||= [] member.details["affiliates"] << audience_member_details(product_id:) member.save! end def update_audience_member_with_removed_product(product_or_id) return unless persisted? && type == "DirectAffiliate" && should_be_audience_member? product_id = product_or_id.is_a?(Link) ? product_or_id.id : product_or_id member = AudienceMember.find_by(email: affiliate_user.email, seller:) return if member.nil? member.details["affiliates"]&.delete_if { _1["id"] == id && _1["product_id"] == product_id } member.valid? ? member.save! : member.destroy! end def should_be_audience_member? type == "DirectAffiliate" && alive? && send_posts && seller.present? && EmailFormatValidator.valid?(affiliate_user&.email) end def audience_member_details(product_id:) { id:, product_id:, created_at: created_at.iso8601 } end private def update_audience_member_details return unless type == "DirectAffiliate" return if !previous_changes.keys.intersect?(%w[deleted_at flags]) return remove_from_audience_member_details unless should_be_audience_member? return unless deleted_at_previously_changed? return if product_affiliates.empty? member = AudienceMember.find_or_initialize_by(email: affiliate_user.email, seller:) member.details["affiliates"] ||= [] product_affiliates.each do member.details["affiliates"] << audience_member_details(product_id: _1.link_id) end member.save! end def remove_from_audience_member_details return unless type == "DirectAffiliate" member = AudienceMember.find_by(email: affiliate_user.email, seller:) return if member.nil? member.details["affiliates"]&.delete_if { _1["id"] == id } member.valid? ? member.save! : member.destroy! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/affiliate/destination_url_validations.rb
app/models/concerns/affiliate/destination_url_validations.rb
# frozen_string_literal: true module Affiliate::DestinationUrlValidations extend ActiveSupport::Concern included do validate :destination_url_validation private def destination_url_validation return if destination_url.blank? errors.add(:base, "The destination url you entered is invalid.") unless /\A#{URI.regexp([%w[http https]])}\z/.match?(destination_url) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/affiliate/basis_points_validations.rb
app/models/concerns/affiliate/basis_points_validations.rb
# frozen_string_literal: true module Affiliate::BasisPointsValidations extend ActiveSupport::Concern MIN_AFFILIATE_BASIS_POINTS = 100 # 1% MAX_AFFILIATE_BASIS_POINTS = 7500 # 75% included do private def affiliate_basis_points_must_fall_in_an_acceptable_range return if affiliate_basis_points.nil? return if affiliate_basis_points >= MIN_AFFILIATE_BASIS_POINTS && affiliate_basis_points <= MAX_AFFILIATE_BASIS_POINTS errors.add(:base, "Affiliate commission must be between #{MIN_AFFILIATE_BASIS_POINTS / 100}% and #{MAX_AFFILIATE_BASIS_POINTS / 100}%.") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/affiliate/sorting.rb
app/models/concerns/affiliate/sorting.rb
# frozen_string_literal: true module Affiliate::Sorting extend ActiveSupport::Concern SORT_KEYS = ["affiliate_user_name", "products", "fee_percent", "volume_cents"] SORT_KEYS.each do |key| const_set(key.upcase, key) end class_methods do def sorted_by(key: nil, direction: nil) direction = direction == "desc" ? "desc" : "asc" case key when AFFILIATE_USER_NAME joins(:affiliate_user) .order(Arel.sql("CASE WHEN users.name IS NOT NULL THEN users.name WHEN users.username != users.external_id THEN users.username WHEN users.unconfirmed_email IS NOT NULL THEN users.unconfirmed_email ELSE users.email END #{direction}")) when PRODUCTS left_outer_joins(:product_affiliates) .group(:id) .order("COUNT(affiliates_links.id) #{direction}") when FEE_PERCENT left_outer_joins(:product_affiliates) .group(:id) .order("MIN(affiliates_links.affiliate_basis_points) #{direction}") when VOLUME_CENTS left_outer_joins(:purchases_that_count_towards_volume) .group(:id) .order("SUM(purchases.price_cents) #{direction}") else all 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/concerns/upsell/sorting.rb
app/models/concerns/upsell/sorting.rb
# frozen_string_literal: true module Upsell::Sorting extend ActiveSupport::Concern SORT_KEYS = ["name", "revenue", "uses", "status"] SORT_KEYS.each do |key| const_set(key.upcase, key) end class_methods do def sorted_by(key: nil, direction: nil) direction = direction == "desc" ? "desc" : "asc" case key when NAME order(name: direction) when REVENUE left_outer_joins(:purchases_that_count_towards_volume) .group(:id) .order("SUM(purchases.price_cents) #{direction}") when USES left_outer_joins(:purchases_that_count_towards_volume) .group(:id) .order("SUM(purchases.quantity) #{direction}") when STATUS order(paused: direction) else all 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/concerns/offer_code/sorting.rb
app/models/concerns/offer_code/sorting.rb
# frozen_string_literal: true module OfferCode::Sorting extend ActiveSupport::Concern SORT_KEYS = ["name", "revenue", "uses", "term"] SORT_KEYS.each do |key| const_set(key.upcase, key) end class_methods do def sorted_by(key: nil, direction: nil) direction = direction == "desc" ? "desc" : "asc" case key when NAME order(name: direction) when REVENUE left_outer_joins(:purchases_that_count_towards_offer_code_uses) .group(:id) .order("SUM(purchases.price_cents) #{direction}") when USES left_outer_joins(:purchases_that_count_towards_offer_code_uses) .group(:id) .order("SUM(purchases.quantity) #{direction}") when TERM order(valid_at: direction, expires_at: direction) else all 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/concerns/charge/disputable.rb
app/models/concerns/charge/disputable.rb
# frozen_string_literal: true module Charge::Disputable extend ActiveSupport::Concern include CurrencyHelper included do has_one :dispute def charge_processor is_a?(Charge) ? processor : charge_processor_id end def charge_processor_transaction_id is_a?(Charge) ? processor_transaction_id : stripe_transaction_id end def purchase_for_dispute_evidence @_purchase_for_dispute_evidence ||= if multiple_purchases? purchases_with_a_refund_policy = disputed_purchases.select { _1.purchase_refund_policy.present? } subscription_purchases = disputed_purchases.select { _1.subscription.present? } subscription_purchases_with_a_refund_policy = purchases_with_a_refund_policy & subscription_purchases selected_purchases = subscription_purchases_with_a_refund_policy.presence selected_purchases ||= if dispute&.reason == Dispute::REASON_SUBSCRIPTION_CANCELED subscription_purchases.presence || purchases_with_a_refund_policy.presence else purchases_with_a_refund_policy.presence || subscription_purchases.presence end selected_purchases ||= disputed_purchases selected_purchases.sort_by(&:total_transaction_cents).last else disputed_purchases.first end end def first_product_without_refund_policy disputed_purchases.find { !_1.link.product_refund_policy_enabled? }&.link end def disputed_amount_cents is_a?(Charge) ? amount_cents : total_transaction_cents end def formatted_disputed_amount formatted_dollar_amount(disputed_amount_cents) end def customer_email purchase_for_dispute_evidence.email end def disputed_purchases is_a?(Charge) ? purchases.to_a : [self] end def multiple_purchases? disputed_purchases.count > 1 end def dispute_balance_date purchase_for_dispute_evidence.succeeded_at.to_date end def mark_as_disputed!(disputed_at:) is_a?(Charge) ? update!(disputed_at:) : update!(chargeback_date: disputed_at) end def mark_as_dispute_reversed!(dispute_reversed_at:) is_a?(Charge) ? update!(dispute_reversed_at:) : update!(chargeback_reversed: true) end def disputed? is_a?(Charge) ? disputed_at.present? : chargeback_date.present? end def build_flow_of_funds(event_flow_of_funds, purchase) multiple_purchases? ? purchase.build_flow_of_funds_from_combined_charge(event_flow_of_funds) : event_flow_of_funds end end def handle_event_dispute_formalized!(event) unless disputed_purchases.any?(&:successful?) Bugsnag.notify("Invalid charge event received for failed #{self.class.name} #{external_id} - " \ "received reversal notification with ID #{event.charge_event_id}") return end if event.flow_of_funds.nil? && event.charge_processor_id != StripeChargeProcessor.charge_processor_id event.flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, -disputed_amount_cents) end dispute = find_or_build_dispute(event) return unless dispute.initiated? || dispute.created? mark_as_disputed!(disputed_at: event.created_at) disputed_purchases.each do |purchase| purchase_event = Event.where(purchase_id: purchase.id, event_name: "purchase").last if purchase_event.present? Event.create( event_name: "chargeback", purchase_id: purchase_event.purchase_id, browser_fingerprint: purchase_event.browser_fingerprint, ip_address: purchase_event.ip_address ) end end dispute.mark_formalized! disputed_purchases.each do |purchase| flow_of_funds = build_flow_of_funds(event.flow_of_funds, purchase) purchase.decrement_balance_for_refund_or_chargeback!(flow_of_funds, dispute:) if purchase.link.is_recurring_billing subscription = Subscription.find_by(id: purchase.subscription_id) subscription.cancel_effective_immediately!(by_buyer: true) subscription.original_purchase.update!(should_exclude_product_review: true) if subscription.should_exclude_product_review_on_charge_reversal? end purchase.enqueue_update_sales_related_products_infos_job(false) purchase.mark_giftee_purchase_as_chargeback if purchase.is_gift_sender_purchase purchase.chargeback_date = event.created_at purchase.chargeback_reason = event.extras.try(:[], :reason) purchase.save! purchase.mark_product_purchases_as_chargedback! purchase.pause_payouts_for_seller_based_on_chargeback_rate! end dispute_evidence = create_dispute_evidence_if_needed! dispute_evidence&.update_as_seller_contacted! ContactingCreatorMailer.chargeback_notice(dispute.id).deliver_later AdminMailer.chargeback_notify(dispute.id).deliver_later CustomerLowPriorityMailer.chargeback_notice_to_customer(dispute.id).deliver_later(wait: 5.seconds) disputed_purchases.each do |purchase| # Check for low balance and put the creator on probation LowBalanceFraudCheckWorker.perform_in(5.seconds, purchase.id) PostToPingEndpointsWorker.perform_in(5.seconds, purchase.id, purchase.url_parameters, ResourceSubscription::DISPUTE_RESOURCE_NAME) end FightDisputeJob.perform_async(dispute_evidence.dispute.id) if dispute_evidence.present? end def handle_event_dispute_won!(event) unless disputed_purchases.any?(&:successful?) Bugsnag.notify("Invalid charge event received for failed #{self.class.name} #{external_id} - " \ "received reversal won notification with ID #{event.charge_event_id}") return end unless disputed? Bugsnag.notify("Invalid charge event received for successful #{self.class.name} #{external_id} - " \ "received reversal won notification with ID #{event.charge_event_id} but was not disputed.") return end if event.flow_of_funds.nil? && event.charge_processor_id != StripeChargeProcessor.charge_processor_id event.flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, disputed_amount_cents) end dispute = find_or_build_dispute(event) dispute.mark_won! mark_as_dispute_reversed!(dispute_reversed_at: event.created_at) disputed_purchases.each do |purchase| purchase.chargeback_reversed = true purchase.mark_giftee_purchase_as_chargeback_reversed if purchase.is_gift_sender_purchase purchase.mark_product_purchases_as_chargeback_reversed! if purchase.link.is_recurring_billing? logger.info("Chargeback event won; re-activating subscription: #{purchase.subscription_id}") subscription = Subscription.find_by(id: purchase.subscription_id) terminated_or_scheduled_for_termination = subscription.termination_date.present? subscription.resubscribe! subscription.send_restart_notifications!(Subscription::ResubscriptionReason::PAYMENT_ISSUE_RESOLVED) if terminated_or_scheduled_for_termination end unless purchase.refunded? purchase.enqueue_update_sales_related_products_infos_job flow_of_funds = build_flow_of_funds(event.flow_of_funds, purchase) purchase.create_credit_for_dispute_won!(flow_of_funds) PostToPingEndpointsWorker.perform_in(5.seconds, purchase.id, purchase.url_parameters, ResourceSubscription::DISPUTE_WON_RESOURCE_NAME) end end ContactingCreatorMailer.chargeback_won(dispute.id).deliver_later unless disputed_purchases.all?(&:refunded?) end def handle_event_dispute_lost!(event) dispute = find_or_build_dispute(event) dispute.mark_lost! return unless first_product_without_refund_policy.present? ContactingCreatorMailer.chargeback_lost_no_refund_policy(dispute.id).deliver_later end def find_or_build_dispute(event) self.dispute ||= build_dispute( charge_processor_id: charge_processor, charge_processor_dispute_id: event.extras.try(:[], :charge_processor_dispute_id), reason: event.extras.try(:[], :reason), event_created_at: event.created_at, ) end def create_dispute_evidence_if_needed! return dispute.dispute_evidence if dispute.dispute_evidence.present? return unless disputed? return unless eligible_for_dispute_evidence? DisputeEvidence.create_from_dispute!(dispute) end def eligible_for_dispute_evidence? return false unless charge_processor == StripeChargeProcessor.charge_processor_id return false if merchant_account&.is_a_stripe_connect_account? true end def fight_chargeback dispute_evidence = dispute.dispute_evidence ChargeProcessor.fight_chargeback(charge_processor, charge_processor_transaction_id, dispute_evidence) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/charge/chargeable.rb
app/models/concerns/charge/chargeable.rb
# frozen_string_literal: true module Charge::Chargeable class << self def find_by_stripe_event(event) chargeable = nil if event.charge_reference.to_s.starts_with?(Charge::COMBINED_CHARGE_PREFIX) chargeable ||= Charge.where(id: event.charge_reference.sub(Charge::COMBINED_CHARGE_PREFIX, "")).last chargeable ||= Charge.where(processor_transaction_id: event.charge_id).last if event.charge_id chargeable ||= Charge.where(stripe_payment_intent_id: event.processor_payment_intent_id).last if event.processor_payment_intent_id.present? else chargeable = Purchase.find_by_external_id(event.charge_reference) if event.charge_reference chargeable ||= Purchase.where(stripe_transaction_id: event.charge_id).last if event.charge_id chargeable ||= ProcessorPaymentIntent.where(intent_id: event.processor_payment_intent_id).last&.purchase if event.processor_payment_intent_id.present? end chargeable end def find_by_processor_transaction_id!(processor_transaction_id) Charge.find_by!(processor_transaction_id:) rescue ActiveRecord::RecordNotFound Purchase.find_by!(stripe_transaction_id: processor_transaction_id) end def find_by_purchase_or_charge!(purchase: nil, charge: nil) raise ArgumentError, "Either purchase or charge must be present" if purchase.blank? && charge.blank? raise ArgumentError, "Only one of purchase or charge must be present" if purchase.present? && charge.present? return charge if charge.present? if purchase.uses_charge_receipt? # We always want to (re)send the charge receipt, if that's how it was originally sent. purchase.charge else purchase end end end def charged_purchases is_a?(Charge) ? purchases.non_free.to_a.reject { _1.is_free_trial_purchase? || _1.is_preorder_authorization? } : [self] end def successful_purchases is_a?(Charge) ? super : Purchase.where(id:) end def update_processor_fee_cents!(processor_fee_cents:) is_a?(Charge) ? super : update!(processor_fee_cents:) end def charged_amount_cents # Cannot use Charge#amount_cents because it is calculated before the purchases are being charged, so it may # include purchases that are not successful is_a?(Charge) ? successful_purchases.sum(&:total_transaction_cents) : total_transaction_cents end def charged_gumroad_amount_cents is_a?(Charge) ? gumroad_amount_cents : total_transaction_amount_for_gumroad_cents end def refundable_amount_cents is_a?(Charge) ? purchases.successful.sum(&:total_transaction_cents) : total_transaction_cents end def purchaser is_a?(Charge) ? order.purchaser : super end def orderable is_a?(Charge) ? order : self end def support_email unique_support_emails = successful_purchases.joins(:link).pluck("links.support_email").uniq if unique_support_emails.size == 1 && unique_support_emails.first.present? unique_support_emails.first else seller.support_or_form_email end end def unbundled_purchases @_unbundled_purchases ||= successful_purchases.map do |purchase| purchase.is_bundle_purchase? ? purchase.product_purchases : [purchase] end.flatten end # Used by ReceiptPresenter to render a different title for recurring subscription def is_recurring_subscription_charge is_a?(Charge) ? false : super end def taxable? is_a?(Charge) ? super : was_purchase_taxable? end def multi_item_charge? is_a?(Charge) ? super : false end def taxed_by_gumroad? is_a?(Charge) ? super : gumroad_tax_cents > 0 end def external_id_for_invoice is_a?(Charge) ? super : external_id end def external_id_numeric_for_invoice is_a?(Charge) ? super : external_id_numeric.to_s end def subscription is_a?(Charge) ? nil : super end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/charge/refundable.rb
app/models/concerns/charge/refundable.rb
# frozen_string_literal: true module Charge::Refundable extend ActiveSupport::Concern def handle_event_refund_updated!(event) stripe_refund_id = event.refund_id db_refunds = Refund.where(processor_refund_id: stripe_refund_id) if db_refunds.present? db_refunds.each do |db_refund| db_refund.status = event.extras[:refund_status] db_refund.save! end else return unless event.extras[:refund_status] == "succeeded" stripe_charge_id = event.charge_id refundable = Charge.find_by(processor_transaction_id: stripe_charge_id) || Purchase.find_by(stripe_transaction_id: stripe_charge_id) return unless refundable.present? return unless event.extras[:refunded_amount_cents] == refundable.refundable_amount_cents charge_refund = StripeChargeProcessor.new.get_refund(stripe_refund_id, merchant_account: refundable.merchant_account) refundable.charged_purchases.each do |purchase| next if !purchase.successful? || purchase.stripe_refunded? flow_of_funds = if purchase.is_part_of_combined_charge? purchase.send(:build_flow_of_funds_from_combined_charge, charge_refund.flow_of_funds) else charge_refund.flow_of_funds end refunded = purchase.refund_purchase!(flow_of_funds, GUMROAD_ADMIN_ID, charge_refund.refund, event.extras[:refund_reason] == "fraudulent") next unless refunded if event.extras[:refund_reason] == "fraudulent" ContactingCreatorMailer.purchase_refunded_for_fraud(purchase.id).deliver_later else ContactingCreatorMailer.purchase_refunded(purchase.id).deliver_later 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/concerns/video_file/has_thumbnail.rb
app/models/concerns/video_file/has_thumbnail.rb
# frozen_string_literal: true module VideoFile::HasThumbnail extend ActiveSupport::Concern THUMBNAIL_SUPPORTED_CONTENT_TYPES = /jpeg|gif|png|jpg/i THUMBNAIL_MAXIMUM_SIZE = 5.megabytes included do has_one_attached :thumbnail do |attachable| attachable.variant :preview, resize_to_limit: [1280, 720], preprocessed: true end validate :validate_thumbnail end def validate_thumbnail return unless thumbnail.attached? if !thumbnail.image? || !thumbnail.content_type.match?(THUMBNAIL_SUPPORTED_CONTENT_TYPES) errors.add(:thumbnail, "must be a JPG, PNG, or GIF image.") return end if thumbnail.byte_size > THUMBNAIL_MAXIMUM_SIZE errors.add(:thumbnail, "must be smaller than 5 MB.") end end def thumbnail_url return nil unless thumbnail.attached? url = thumbnail.variant(:preview).url || thumbnail.url url.present? ? cdn_url_for(url) : nil end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/payment/failure_reason.rb
app/models/concerns/payment/failure_reason.rb
# frozen_string_literal: true module Payment::FailureReason extend ActiveSupport::Concern CANNOT_PAY = "cannot_pay" DEBIT_CARD_LIMIT = "debit_card_limit" INSUFFICIENT_FUNDS = "insufficient_funds" PAYPAL_MASS_PAY = { "PAYPAL 1000" => "Unknown error", "PAYPAL 1001" => "Receiver's account is invalid", "PAYPAL 1002" => "Sender has insufficient funds", "PAYPAL 1003" => "User's country is not allowed", "PAYPAL 1004" => "User funding source is ineligible", "PAYPAL 3004" => "Cannot pay self", "PAYPAL 3014" => "Sender's account is locked or inactive", "PAYPAL 3015" => "Receiver's account is locked or inactive", "PAYPAL 3016" => "Either the sender or receiver exceeded the transaction limit", "PAYPAL 3017" => "Spending limit exceeded", "PAYPAL 3047" => "User is restricted", "PAYPAL 3078" => "Negative balance", "PAYPAL 3148" => "Receiver's address is in a non-receivable country or a PayPal zero country", "PAYPAL 3501" => "Email address invalid; try again with a valid email ID", "PAYPAL 3535" => "Invalid currency", "PAYPAL 3547" => "Sender's address is located in a restricted State (e.g., California)", "PAYPAL 3558" => "Receiver's address is located in a restricted State (e.g., California)", "PAYPAL 3769" => "Market closed and transaction is between 2 different countries", "PAYPAL 4001" => "Internal error", "PAYPAL 4002" => "Internal error", "PAYPAL 8319" => "Zero amount", "PAYPAL 8330" => "Receiving limit exceeded", "PAYPAL 8331" => "Duplicate mass payment", "PAYPAL 9302" => "Transaction was declined", "PAYPAL 11711" => "Per-transaction sending limit exceeded", "PAYPAL 14159" => "Transaction currency cannot be received by the recipient", "PAYPAL 14550" => "Currency compliance", "PAYPAL 14761" => "The mass payment was declined because the secondary user sending the mass payment has not been verified", "PAYPAL 14763" => "Regulatory review - Pending", "PAYPAL 14764" => "Regulatory review - Blocked", "PAYPAL 14765" => "Receiver is unregistered", "PAYPAL 14766" => "Receiver is unconfirmed", "PAYPAL 14767" => "Receiver is a youth account", "PAYPAL 14800" => "POS cumulative sending limit exceeded" } private_constant :PAYPAL_MASS_PAY PAYPAL_FAILURE_SOLUTIONS = { "PAYPAL 11711" => { reason: "per-transaction sending limit exceeded", solution: "Contact PayPal to get receiving limit on the account increased. If that's not possible, Gumroad can split their payout, please contact Gumroad Support" }, "PAYPAL 14159" => { reason: "transaction currency cannot be received by the recipient", solution: "Use a different PayPal account which supports receiving USD" }, "PAYPAL 3015" => { reason: "receiver's account is locked or inactive", solution: "Log in to your PayPal account and ensure there are no restrictions on it, or contact PayPal Support for more information" }, "PAYPAL 3148" => { reason: "receiver's address is in a non-receivable country or a PayPal zero country", solution: "Use a different PayPal account which supports receiving USD" }, "PAYPAL 8330" => { reason: "receiving limit exceeded", solution: "Reach out to PayPal support" }, "PAYPAL 9302" => { reason: "transaction was declined", solution: "Reach out to PayPal support" } } private_constant :PAYPAL_FAILURE_SOLUTIONS STRIPE_FAILURE_SOLUTIONS = { "account_closed" => { reason: "the bank account has been closed", solution: "Use another bank account", }, "account_frozen" => { reason: "the bank account has been frozen", solution: "Use another bank account", }, "bank_account_restricted" => { reason: "the bank account has restrictions on either the type, or the number, of payouts allowed. This normally indicates that the bank account is a savings or other non-checking account", solution: "Confirm the bank account entered in payout settings", }, "could_not_process" => { reason: "the bank could not process this payout", solution: "Confirm the bank account entered in payout settings. If it's correct, update to a new bank account", }, "debit_card_limit" => { reason: "payouts to debit cards have a $3,000 per payout limit", solution: "Use a bank account to receive payouts instead of a debit card", }, "expired_card" => { reason: "the card has expired", solution: "Replace the card with a new card and/or bank account", }, "incorrect_account_holder_address" => { reason: "the bank notified us that the bank account holder address on file is incorrect", solution: "Confirm the bank account holder details entered in payout settings", }, "incorrect_account_holder_name" => { reason: "the bank notified us that the bank account holder name on file is incorrect", solution: "Confirm the bank account holder details entered in payout settings", }, "invalid_account_number" => { reason: "the routing number seems correct, but the account number is invalid", solution: "Confirm the bank account entered in payout settings", }, "invalid_card" => { reason: "the card is invalid", solution: "Replace the card with a new card and/or bank account", }, "invalid_currency" => { reason: "the bank was unable to process this payout because of its currency. This is probably because the bank account cannot accept payments in that currency", solution: "Add a bank account that can accept local currency", }, "lost_or_stolen_card" => { reason: "the card is marked as lost or stolen", solution: "Replace the card with a new card and/or bank account", }, "no_account" => { reason: "the bank account details on file are probably incorrect. No bank account could be located with those details", solution: "Confirm the bank account entered in payout settings", }, "refer_to_card_issuer" => { reason: "the card is invalid", solution: "Reach out to their bank", }, "unsupported_card" => { reason: "the bank no longer supports payouts to this card", solution: "Change the card used for payouts", }, } private_constant :STRIPE_FAILURE_SOLUTIONS private def add_payment_failure_reason_comment return unless failure_reason.present? solution = if processor == PayoutProcessorType::PAYPAL PAYPAL_FAILURE_SOLUTIONS[failure_reason] elsif processor == PayoutProcessorType::STRIPE STRIPE_FAILURE_SOLUTIONS[failure_reason] end return unless solution.present? content = "Payout via #{processor.capitalize} on #{created_at} failed because #{solution[:reason]}. Solution: #{solution[:solution]}." user.add_payout_note(content:) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/order/orderable.rb
app/models/concerns/order/orderable.rb
# frozen_string_literal: true module Order::Orderable def require_shipping? is_a?(Order) ? super : link.require_shipping? end def receipt_for_gift_receiver? is_a?(Order) ? super : is_gift_receiver_purchase? end def receipt_for_gift_sender? is_a?(Order) ? super : is_gift_sender_purchase? end def seller_receipt_enabled? is_a?(Order) end def test? is_a?(Order) ? super : is_test_purchase? end def uses_charge_receipt? # For a Purchase record, this needs to work for: # * a stand-alone purchase without a charge or a order # * a purchase that belongs directly to an order (before charges were introduced) # * a purchase that belongs to a charge, and the charge belongs to an order is_a?(Order) ? seller_receipt_enabled? : (charge&.order&.seller_receipt_enabled? || false) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/balance/searchable.rb
app/models/concerns/balance/searchable.rb
# frozen_string_literal: true module Balance::Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model include SearchIndexModelCommon include ElasticsearchModelAsyncCallbacks index_name "balances" settings number_of_shards: 1, number_of_replicas: 0 mapping dynamic: :strict do indexes :amount_cents, type: :long indexes :user_id, type: :long indexes :state, type: :keyword end ATTRIBUTE_TO_SEARCH_FIELDS = { "amount_cents" => "amount_cents", "user_id" => "user_id", "state" => "state" } def search_field_value(field_name) case field_name when "amount_cents", "user_id", "state" attributes[field_name] end.as_json end end class_methods do def amount_cents_sum_for(user) query = Elasticsearch::DSL::Search.search do size 0 query do bool do filter do term user_id: user.id end filter do term state: "unpaid" end end end aggregation :sum_amount_cents do sum field: "amount_cents" end end __elasticsearch__.search(query).aggregations.sum_amount_cents.value.to_i end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/balance/refund_eligibility_underwriter.rb
app/models/concerns/balance/refund_eligibility_underwriter.rb
# frozen_string_literal: true module Balance::RefundEligibilityUnderwriter extend ActiveSupport::Concern included do after_commit :update_seller_refund_eligibility end private def update_seller_refund_eligibility return if user_id.blank? return unless anticipate_refund_eligibility_changes? UpdateSellerRefundEligibilityJob.perform_async(user_id) end def anticipate_refund_eligibility_changes? return unless amount_cents_previously_changed? before = amount_cents_previously_was || 0 after = amount_cents balance_increased = before < after balance_decreased = before > after return true if balance_increased && user.refunds_disabled? return true if balance_decreased && !user.refunds_disabled? false end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/dispute_win_credits.rb
app/models/concerns/purchase/dispute_win_credits.rb
# frozen_string_literal: true module Purchase::DisputeWinCredits extend ActiveSupport::Concern def create_credit_for_dispute_won_for_affiliate!(flow_of_funds, amount_cents: 0) return if affiliate_credit_cents == 0 || amount_cents == 0 affiliate_issued_amount = BalanceTransaction::Amount.create_issued_amount_for_affiliate( flow_of_funds:, issued_affiliate_cents: amount_cents ) affiliate_holding_amount = BalanceTransaction::Amount.create_holding_amount_for_affiliate( flow_of_funds:, issued_affiliate_cents: amount_cents ) Credit.create_for_dispute_won!( merchant_account: affiliate_merchant_account, user: affiliate_credit.affiliate_user, dispute: charge.present? ? charge.dispute : dispute, chargedback_purchase: self, balance_transaction_issued_amount: affiliate_issued_amount, balance_transaction_holding_amount: affiliate_holding_amount ) end def create_credit_for_dispute_won_for_seller!(flow_of_funds, amount_cents:) return unless charged_using_gumroad_merchant_account? seller_issued_amount = BalanceTransaction::Amount.create_issued_amount_for_seller( flow_of_funds:, issued_net_cents: amount_cents ) seller_holding_amount = BalanceTransaction::Amount.create_holding_amount_for_seller( flow_of_funds:, issued_net_cents: amount_cents ) Credit.create_for_dispute_won!( merchant_account:, user: seller, dispute: charge.present? ? charge.dispute : dispute, chargedback_purchase: self, balance_transaction_issued_amount: seller_issued_amount, balance_transaction_holding_amount: seller_holding_amount ) end def create_credit_for_dispute_won!(flow_of_funds) unless stripe_partially_refunded? # Short circuit for full refund, or dispute seller_disputed_cents = payment_cents - affiliate_credit_cents affiliate_disputed_cents = affiliate_credit_cents else disputed_fee_cents = ((fee_cents.to_f / price_cents.to_f) * amount_refundable_cents).floor seller_disputed_cents = amount_refundable_cents - disputed_fee_cents if affiliate_credit_cents == 0 affiliate_disputed_cents = 0 else affiliate_disputed_cents = ((affiliate.affiliate_basis_points / 10_000.0) * amount_refundable_cents).floor seller_disputed_cents = seller_disputed_cents - affiliate_disputed_cents end end create_credit_for_dispute_won_for_affiliate!(flow_of_funds, amount_cents: affiliate_disputed_cents) create_credit_for_dispute_won_for_seller!(flow_of_funds, amount_cents: seller_disputed_cents) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/audience_member.rb
app/models/concerns/purchase/audience_member.rb
# frozen_string_literal: true module Purchase::AudienceMember extend ActiveSupport::Concern included do after_save :update_audience_member_details after_destroy :remove_from_audience_member_details end def should_be_audience_member? result = can_contact? result &= purchase_state.in?(%w[successful gift_receiver_purchase_successful not_charged]) result &= !is_gift_sender_purchase? result &= EmailFormatValidator.valid?(email) if subscription_id.nil? result &= !stripe_refunded? result &= chargeback_date.blank? || chargeback_reversed? else result &= is_original_subscription_purchase? result &= !is_archived_original_subscription_purchase? result &= subscription.deactivated_at.nil? result &= !subscription.is_test_subscription? end result end def audience_member_details { id:, country: country_or_ip_country.to_s, created_at: created_at.iso8601, product_id: link_id, variant_ids: variant_attributes.ids, price_cents:, }.compact_blank end def add_to_audience_member_details return unless should_be_audience_member? member = AudienceMember.find_or_initialize_by(email:, seller:) return if member.details["purchases"]&.any? { _1["id"] == id } member.details["purchases"] ||= [] member.details["purchases"] << audience_member_details member.save! end def remove_from_audience_member_details(email = attributes["email"]) member = AudienceMember.find_by(email:, seller:) return if member.nil? member.details["purchases"]&.delete_if { _1["id"] == id } member.valid? ? member.save! : member.destroy! end private def update_audience_member_details return if !previous_changes.keys.intersect?(%w[can_contact purchase_state stripe_refunded flags chargeback_date email]) remove_from_audience_member_details(email_previously_was) if email_previously_changed? && !previously_new_record? return remove_from_audience_member_details unless should_be_audience_member? add_to_audience_member_details end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/searchable.rb
app/models/concerns/purchase/searchable.rb
# frozen_string_literal: true module Purchase::Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model include ElasticsearchModelAsyncCallbacks include SearchIndexModelCommon include RelatedPurchaseCallbacks index_name "purchases" settings number_of_shards: 1, number_of_replicas: 0, index: { analysis: { filter: { autocomplete_filter: { type: "edge_ngram", min_gram: 1, max_gram: 20, token_chars: ["letter", "digit"] }, full_autocomplete_filter: { type: "edge_ngram", min_gram: 1, max_gram: 20 } }, analyzer: { full_name: { tokenizer: "whitespace", filter: ["lowercase", "autocomplete_filter"] }, search_full_name: { tokenizer: "whitespace", filter: "lowercase" }, email: { tokenizer: "whitespace", filter: ["lowercase", "autocomplete_filter"] }, search_email: { tokenizer: "whitespace", filter: "lowercase" }, product_name: { tokenizer: "whitespace", filter: ["lowercase", "full_autocomplete_filter"] }, search_product_name: { tokenizer: "whitespace", filter: "lowercase" } } } } mapping dynamic: :strict do indexes :id, type: :long indexes :can_contact, type: :boolean indexes :chargeback_date, type: :date indexes :country_or_ip_country, type: :keyword indexes :created_at, type: :date indexes :latest_charge_date, type: :date indexes :email, type: :text, analyzer: :email, search_analyzer: :search_email do indexes :raw, type: :keyword end indexes :email_domain, type: :text, analyzer: :email, search_analyzer: :search_email indexes :paypal_email, type: :text, analyzer: :email, search_analyzer: :search_email do indexes :raw, type: :keyword end indexes :fee_cents, type: :long indexes :full_name, type: :text, analyzer: :full_name, search_analyzer: :search_full_name indexes :not_chargedback_or_chargedback_reversed, type: :boolean indexes :not_refunded_except_subscriptions, type: :boolean indexes :not_subscription_or_original_subscription_purchase, type: :boolean indexes :successful_authorization_or_without_preorder, type: :boolean indexes :price_cents, type: :long indexes :purchase_state, type: :keyword indexes :amount_refunded_cents, type: :long indexes :fee_refunded_cents, type: :long indexes :tax_refunded_cents, type: :long indexes :selected_flags, type: :keyword indexes :stripe_refunded, type: :boolean indexes :tax_cents, type: :long indexes :monthly_recurring_revenue, type: :float indexes :ip_country, type: :keyword indexes :ip_state, type: :keyword indexes :referrer_domain, type: :keyword indexes :license_serial, type: :keyword # one-to-many associations indexes :variant_ids, type: :long # computed associations indexes :product_ids_from_same_seller_purchased_by_purchaser, type: :long indexes :variant_ids_from_same_seller_purchased_by_purchaser, type: :long # one-to-one associations indexes :affiliate_credit_id, type: :long indexes :affiliate_credit_affiliate_user_id, type: :long indexes :affiliate_credit_amount_cents, type: :long indexes :affiliate_credit_fee_cents, type: :long indexes :affiliate_credit_amount_partially_refunded_cents, type: :long indexes :affiliate_credit_fee_partially_refunded_cents, type: :long indexes :product_id, type: :long indexes :product_unique_permalink, type: :keyword indexes :product_name, type: :text, analyzer: :product_name, search_analyzer: :search_product_name indexes :product_description, type: :text indexes :seller_id, type: :long indexes :seller_name, type: :text, analyzer: :full_name, search_analyzer: :search_full_name indexes :purchaser_id, type: :long indexes :subscription_id, type: :long indexes :subscription_cancelled_at, type: :date indexes :subscription_deactivated_at, type: :date indexes :taxonomy_id, type: :long end ATTRIBUTE_TO_SEARCH_FIELDS = { "id" => "id", "can_contact" => "can_contact", "chargeback_date" => %w[ chargeback_date not_chargedback_or_chargedback_reversed ], "country" => "country_or_ip_country", "created_at" => "created_at", "email" => ["email", "email_domain"], "fee_cents" => "fee_cents", "flags" => %w[ selected_flags not_chargedback_or_chargedback_reversed not_subscription_or_original_subscription_purchase referrer_domain ], "full_name" => "full_name", "ip_country" => ["country_or_ip_country", "ip_country"], "ip_state" => "ip_state", "referrer" => "referrer_domain", "price_cents" => "price_cents", "purchase_state" => %w[ purchase_state latest_charge_date successful_authorization_or_without_preorder ], "stripe_refunded" => %w[ stripe_refunded not_refunded_except_subscriptions ], "tax_cents" => "tax_cents", "card_visual" => "paypal_email", "subscription_id" => "subscription_id", "license_serial" => "license_serial", } def search_field_value(field_name) case field_name when "id", "can_contact", "created_at", "full_name", "price_cents", "chargeback_date", "purchase_state", "ip_country", "ip_state", "fee_cents", "tax_cents" attributes[field_name] when "email" email&.downcase when "email_domain" email.downcase.split("@")[1] if email.present? when "selected_flags" selected_flags.map(&:to_s) when "stripe_refunded" stripe_refunded? when "not_chargedback_or_chargedback_reversed" chargeback_date.nil? || selected_flags.include?(:chargeback_reversed) when "not_refunded_except_subscriptions" !stripe_refunded? || subscription_id? when "not_subscription_or_original_subscription_purchase" subscription_id.nil? || (selected_flags.include?(:is_original_subscription_purchase) && !selected_flags.include?(:is_archived_original_subscription_purchase)) when "successful_authorization_or_without_preorder" purchase_state.in?(["preorder_authorization_successful", "preorder_concluded_successfully"]) || preorder_id.nil? when "country_or_ip_country" country_or_ip_country when "amount_refunded_cents" amount_refunded_cents when "fee_refunded_cents" fee_refunded_cents when "tax_refunded_cents" tax_refunded_cents when "referrer_domain" was_product_recommended? ? REFERRER_DOMAIN_FOR_GUMROAD_RECOMMENDED_PRODUCTS : Referrer.extract_domain(referrer) when /\Aaffiliate_credit_(id|affiliate_user_id|amount_cents|fee_cents|amount_partially_refunded_cents|fee_partially_refunded_cents)\z/ affiliate_credit.public_send($LAST_MATCH_INFO[1]) if affiliate_credit.present? when /\Aproduct_(id|unique_permalink|name)\z/ link.attributes[$LAST_MATCH_INFO[1]] when "product_description" link.plaintext_description when /\Aseller_(id|name)\z/ seller.attributes[$LAST_MATCH_INFO[1]] when /\Apurchaser_(id)\z/ purchaser.attributes[$LAST_MATCH_INFO[1]] if purchaser.present? when /\Asubscription_(id|cancelled_at|deactivated_at)\z/ subscription.attributes[$LAST_MATCH_INFO[1]] if subscription.present? when "taxonomy_id" link.taxonomy_id when "variant_ids" variant_attributes.ids when "product_ids_from_same_seller_purchased_by_purchaser" seller.sales.by_email(email).select("distinct link_id").map(&:link_id) when "variant_ids_from_same_seller_purchased_by_purchaser" purchases_sql = seller.sales.by_email(email).select(:id).to_sql variants_sql = <<~SQL select distinct base_variant_id from base_variants_purchases where purchase_id IN (#{purchases_sql}) SQL ActiveRecord::Base.connection.execute(variants_sql).to_a.flatten when "latest_charge_date" if is_original_subscription_purchase? && subscription.present? subscription.purchases. force_index(:index_purchases_on_subscription_id). successful.order(created_at: :desc, id: :desc). select(:created_at).first&.created_at end when "monthly_recurring_revenue" if is_original_subscription_purchase? && subscription&.last_payment_option&.price&.recurrence recurrence = subscription.last_payment_option.price.recurrence price_cents.to_f / BasePrice::Recurrence.number_of_months_in_recurrence(recurrence) end when "paypal_email" card_visual&.downcase if card_type == CardType::PAYPAL when "license_serial" license&.serial end.as_json end end module SubscriptionCallbacks extend ActiveSupport::Concern include TransactionalAttributeChangeTracker included do after_commit :update_purchase_index, on: :update end def update_purchase_index tracked_columns = %w[cancelled_at deactivated_at] changed_tracked_columns = attributes_committed & tracked_columns if changed_tracked_columns.present? purchases.select(:id).find_each do |purchase| options = { "record_id" => purchase.id, "class_name" => "Purchase", "fields" => changed_tracked_columns.map { |name| ["subscription_#{name}"] }.flatten } ElasticsearchIndexerWorker.perform_in(2.seconds, "update", options) end end end end module RelatedPurchaseCallbacks extend ActiveSupport::Concern included do after_commit :update_related_purchase_documents, on: [:create, :update] after_commit :update_same_purchaser_subscription_purchase_documents, on: [:create, :update] end private def update_related_purchase_documents successful_states = %w[successful gift_receiver_purchase_successful preorder_authorization_successful] # no need to update if the purchase is not successful, as the seller will never be aware of it return unless successful_states.include?(purchase_state) # no need to update if the state didn't change return unless previous_changes.key?(:purchase_state) # no need to update if the state changed but is still successful return if successful_states.include?(previous_changes[:purchase_state]) query = PurchaseSearchService.new( seller:, email:, exclude_purchase: self ).query options = { "source_record_id" => id, "query" => query.deep_stringify_keys, "class_name" => "Purchase", "fields" => [ "product_ids_from_same_seller_purchased_by_purchaser", "variant_ids_from_same_seller_purchased_by_purchaser" ] } ElasticsearchIndexerWorker.set(queue: "low").perform_in(rand(72.hours), "update_by_query", options) end def update_same_purchaser_subscription_purchase_documents should_update = successful? should_update &= previous_changes.key?(:purchase_state) should_update &= !is_original_subscription_purchase? should_update &= subscription.present? && subscription.original_purchase.present? return unless should_update options = { "record_id" => subscription.original_purchase.id, "class_name" => "Purchase", "fields" => [ "latest_charge_date", ] } ElasticsearchIndexerWorker.perform_in(2.seconds, "update", options) end end module VariantAttributeCallbacks def self.variants_changed(purchase) options = { "record_id" => purchase.id, "class_name" => "Purchase", "fields" => [ "variant_ids", "variant_ids_from_same_seller_purchased_by_purchaser" ] } ElasticsearchIndexerWorker.perform_in(2.seconds, "update", options) query = PurchaseSearchService.new( seller: purchase.seller, email: purchase.email, exclude_purchase: purchase ).query options = { "source_record_id" => purchase.id, "query" => query.deep_stringify_keys, "class_name" => "Purchase", "fields" => [ "variant_ids_from_same_seller_purchased_by_purchaser" ] } ElasticsearchIndexerWorker.set(queue: "low").perform_in(rand(72.hours), "update_by_query", options) end end module AffiliateCreditCallbacks extend ActiveSupport::Concern included do after_commit :update_purchase_index, on: [:create, :update] end def update_purchase_index tracked_columns = %w[ id affiliate_user_id amount_cents fee_cents ] changed_tracked_columns = previous_changes.keys & tracked_columns return if changed_tracked_columns.blank? options = { "record_id" => purchase.id, "class_name" => "Purchase", "fields" => changed_tracked_columns.map { |name| ["affiliate_credit_#{name}"] }.flatten } ElasticsearchIndexerWorker.perform_in(2.seconds, "update", options) end end module AffiliatePartialRefundCallbacks extend ActiveSupport::Concern included do after_commit :update_purchase_index, on: [:create, :update] end def update_purchase_index return unless previous_changes.key?("amount_cents") options = { "record_id" => purchase.id, "class_name" => "Purchase", "fields" => ["affiliate_credit_amount_partially_refunded_cents", "affiliate_credit_amount_fee_partially_refunded_cents"] } ElasticsearchIndexerWorker.perform_in(2.seconds, "update", options) end end module ProductCallbacks extend ActiveSupport::Concern included do after_commit :update_sales_taxonomy_id, on: :update end def update_sales_taxonomy_id return unless previous_changes.key?("taxonomy_id") first_sale_id = sales.pick(:id) return if first_sale_id.nil? query = PurchaseSearchService.new(product: self).query options = { "class_name" => Purchase.name, "fields" => ["taxonomy_id"], "source_record_id" => first_sale_id, "query" => query.deep_stringify_keys } ElasticsearchIndexerWorker.set(queue: "low").perform_in(rand(72.hours), "update_by_query", options) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/reportable.rb
app/models/concerns/purchase/reportable.rb
# frozen_string_literal: true module Purchase::Reportable extend ActiveSupport::Concern def price_cents_net_of_refunds net_of_refunds_cents(:price_cents, :amount_cents) end def fee_cents_net_of_refunds net_of_refunds_cents(:fee_cents, :fee_cents) end def tax_cents_net_of_refunds net_of_refunds_cents(:tax_cents, :creator_tax_cents) end def gumroad_tax_cents_net_of_refunds net_of_refunds_cents(:gumroad_tax_cents, :gumroad_tax_cents) end def total_cents_net_of_refunds net_of_refunds_cents(:total_transaction_cents, :total_transaction_cents) end private def net_of_refunds_cents(purchase_attribute, refund_attribute) # Fully refunded or Chargebacked not reversed return 0 if chargedback_not_reversed_or_refunded? # No chargeback or refunds return self.send(purchase_attribute) unless stripe_partially_refunded? || chargedback_not_reversed_or_refunded? refunded_cents = refunds.sum(refund_attribute) # No refunded amount return self.send(purchase_attribute) unless refunded_cents > 0 # Partially refunded amount net_cents = self.send(purchase_attribute) - refunded_cents return net_cents if net_cents > 0 Rails.logger.info "Unknown #{purchase_attribute} for purchase: #{self.id}" # Something is wrong, we have more refunds than actual collection of fees, just ignore 0 end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/charge_events_handler.rb
app/models/concerns/purchase/charge_events_handler.rb
# frozen_string_literal: true module Purchase::ChargeEventsHandler extend ActiveSupport::Concern class_methods do def handle_charge_event(event) logger.info("Charge event: #{event.to_h.to_json}") chargeable = Charge::Chargeable.find_by_stripe_event(event) if chargeable.nil? Bugsnag.notify("Could not find a Chargeable on Gumroad for Stripe Charge ID: #{event.charge_id}, " \ "charge reference: #{event.charge_reference} for event id: #{event.charge_event_id}.") return end chargeable.handle_event(event) end end def handle_event(event) case event.type when ChargeEvent::TYPE_DISPUTE_FORMALIZED handle_event_dispute_formalized!(event) when ChargeEvent::TYPE_DISPUTE_WON handle_event_dispute_won!(event) when ChargeEvent::TYPE_DISPUTE_LOST handle_event_dispute_lost!(event) when ChargeEvent::TYPE_SETTLEMENT_DECLINED handle_event_settlement_declined!(event) when ChargeEvent::TYPE_CHARGE_SUCCEEDED handle_event_succeeded!(event) when ChargeEvent::TYPE_PAYMENT_INTENT_FAILED handle_event_failed!(event) when ChargeEvent::TYPE_CHARGE_REFUND_UPDATED handle_event_refund_updated!(event) when ChargeEvent::TYPE_INFORMATIONAL handle_event_informational!(event) end charged_purchases.each { _1.update!(stripe_status: event.comment) } end def handle_event_settlement_declined!(event) unless charged_purchases.any?(&:successful?) Bugsnag.notify("Invalid charge event received for failed #{self.class.name} #{external_id} - " \ "received settlement declined notification with ID #{event.charge_event_id}") return end charged_purchases.each do |purchase| purchase_event = Event.where(purchase_id: purchase.id, event_name: "purchase").last unless purchase_event.nil? Event.create( event_name: "settlement_declined", purchase_id: purchase_event.purchase_id, browser_fingerprint: purchase_event.browser_fingerprint, ip_address: purchase_event.ip_address ) end flow_of_funds = is_a?(Charge) ? purchase.build_flow_of_funds_from_combined_charge(event.flow_of_funds) : event.flow_of_funds purchase.refund_purchase!(flow_of_funds, nil) if purchase.link.is_recurring_billing subscription = Subscription.find_by(id: purchase.subscription_id) subscription.cancel_effective_immediately!(by_buyer: true) end purchase.mark_giftee_purchase_as_chargeback if purchase.is_gift_sender_purchase purchase.mark_product_purchases_as_chargedback! end # TODO: Send failure email w/ settlement declined notification. end def handle_event_succeeded!(event) handle_event_informational!(event) charged_purchases.each do |purchase| if purchase.in_progress? && purchase.is_an_off_session_charge_on_indian_card? stripe_charge = ChargeProcessor.get_charge(StripeChargeProcessor.charge_processor_id, event.charge_id, merchant_account: purchase.merchant_account) purchase.save_charge_data(stripe_charge) # Recurring charges on Indian cards remain in processing for 26 hours after which we receive this charge.succeeded webhook. # Setting purchase.succeeded_at to be same as purchase.created_at here, instead of setting it as current timestamp, # as we use succeeded_at to calculate the membership period and termination dates etc. and do not want those to shift by a day. # For all other purchases, the succeeded_at and created_at are only a few seconds apart, # as all other charges succeed immediately in-sync and do not have an intermediate processing state. succeeded_at = Time.current > purchase.created_at + 1.hour ? purchase.created_at : nil if purchase.subscription.present? purchase.subscription.handle_purchase_success(purchase, succeeded_at:) else purchase.update_balance_and_mark_successful! ActivateIntegrationsWorker.perform_async(purchase.id) end end end end def handle_event_failed!(event) handle_event_informational!(event) charged_purchases.each do |purchase| if purchase.in_progress? && purchase.is_an_off_session_charge_on_indian_card? if purchase.subscription.present? purchase.subscription.handle_purchase_failure(purchase) else purchase.mark_failed! end end end end def handle_event_informational!(event) transaction_fee_cents = event.extras.try(:[], "fee_cents") update_processor_fee_cents!(processor_fee_cents: transaction_fee_cents) if transaction_fee_cents end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/paypal.rb
app/models/concerns/purchase/paypal.rb
# frozen_string_literal: true module Purchase::Paypal extend ActiveSupport::Concern included do scope :paypal, -> { where(charge_processor_id: PaypalChargeProcessor.charge_processor_id) } scope :paypal_orders, -> { where.not(paypal_order_id: nil) } scope :unsuccessful_paypal_orders, lambda { |created_after_timestamp, created_before_timestamp| not_successful.paypal_orders.created_after(created_after_timestamp).created_before(created_before_timestamp) } end def paypal_email card_visual.presence if paypal_charge_processor? end def charged_using_paypal_connect_account? merchant_account.present? && merchant_account.is_a_paypal_connect_account? end def seller_native_paypal_payment_enabled? seller.present? && seller.native_paypal_payment_enabled? end def paypal_refund_expired? created_at < 6.months.ago && card_type == CardType::PAYPAL end def paypal_fee_usd_cents return 0 unless paypal_charge_processor? return 0 if processor_fee_cents_currency.blank? return 0 if processor_fee_cents.to_i == 0 get_usd_cents(processor_fee_cents_currency, processor_fee_cents) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/custom_fields.rb
app/models/concerns/purchase/custom_fields.rb
# frozen_string_literal: true module Purchase::CustomFields extend ActiveSupport::Concern included do has_many :purchase_custom_fields, dependent: :destroy end def custom_fields purchase_custom_fields.map do |field| { name: field.name, value: field.value, type: field.type } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/receipt.rb
app/models/concerns/purchase/receipt.rb
# frozen_string_literal: true module Purchase::Receipt extend ActiveSupport::Concern included do has_many :email_infos has_many :installments, through: :email_infos has_one :receipt_email_info_from_purchase, -> { order(id: :desc) }, class_name: "CustomerEmailInfo" end def receipt_email_info @_receipt_email_info ||= if uses_charge_receipt? charge.receipt_email_info else receipt_email_info_from_purchase end end def send_receipt after_commit do next if destroyed? SendPurchaseReceiptJob.set(queue: link.has_stampable_pdfs? ? "default" : "critical").perform_async(id) unless uses_charge_receipt? enqueue_send_last_post_job end end def enqueue_send_last_post_job return unless is_original_subscription_purchase && link.should_include_last_post SendLastPostJob.perform_async(id) end def resend_receipt if is_preorder_authorization CustomerMailer.preorder_receipt(preorder.id).deliver_later(queue: "critical", wait: 3.seconds) else queue = link.has_stampable_pdfs? ? "default" : "critical" SendPurchaseReceiptJob.set(queue:).perform_async(id) SendPurchaseReceiptJob.set(queue:).perform_async(gift.giftee_purchase.id) if is_gift_sender_purchase && gift.present? end end def has_invoice? subscription.present? ? !is_free_trial_purchase? : !free_purchase? end def invoice_url Rails.application.routes.url_helpers.generate_invoice_by_buyer_url( external_id, email: email, host: UrlService.domain_with_protocol ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/blockable.rb
app/models/concerns/purchase/blockable.rb
# frozen_string_literal: true module Purchase::Blockable extend ActiveSupport::Concern included do include AttributeBlockable attr_blockable :browser_guid attr_blockable :ip_address attr_blockable :email attr_blockable :paypal_email, object_type: :email attr_blockable :gifter_email, object_type: :email attr_blockable :charge_processor_fingerprint attr_blockable :purchaser_email, object_type: :email attr_blockable :recent_stripe_fingerprint, object_type: :charge_processor_fingerprint attr_blockable :email_domain attr_blockable :paypal_email_domain, object_type: :email_domain attr_blockable :gifter_email_domain, object_type: :email_domain attr_blockable :purchaser_email_domain, object_type: :email_domain delegate :email, to: :purchaser, prefix: true, allow_nil: true end # Max number of failed purchase card fingerprints before a buyer's browser guid gets banned MAX_NUMBER_OF_FAILED_FINGERPRINTS = 4 CARD_TESTING_WATCH_PERIOD = 7.days private_constant :CARD_TESTING_WATCH_PERIOD CARD_TESTING_IP_ADDRESS_WATCH_PERIOD = 1.day private_constant :CARD_TESTING_IP_ADDRESS_WATCH_PERIOD CARD_TESTING_IP_ADDRESS_BLOCK_DURATION = 7.days private_constant :CARD_TESTING_IP_ADDRESS_BLOCK_DURATION IGNORED_ERROR_CODES = [PurchaseErrorCode::PERCEIVED_PRICE_CENTS_NOT_MATCHING, PurchaseErrorCode::NOT_FOR_SALE, PurchaseErrorCode::TEMPORARILY_BLOCKED_PRODUCT, PurchaseErrorCode::BLOCKED_CHARGE_PROCESSOR_FINGERPRINT, PurchaseErrorCode::BLOCKED_CUSTOMER_EMAIL_ADDRESS, PurchaseErrorCode::BLOCKED_CUSTOMER_CHARGE_PROCESSOR_FINGERPRINT] private_constant :IGNORED_ERROR_CODES MAX_PURCHASER_AGE_FOR_SUSPENSION = 6.hours private_constant :MAX_PURCHASER_AGE_FOR_SUSPENSION def buyer_blocked? blocked_by_browser_guid? || blocked_by_email? || blocked_by_paypal_email? || blocked_by_gifter_email? || blocked_by_purchaser_email? || blocked_by_ip_address? || blocked_by_charge_processor_fingerprint? || blocked_by_recent_stripe_fingerprint? end def block_buyer!(blocking_user_id: nil, comment_content: nil) block_by_browser_guid!(by_user_id: blocking_user_id) block_by_email!(by_user_id: blocking_user_id) block_by_paypal_email!(by_user_id: blocking_user_id) block_by_gifter_email!(by_user_id: blocking_user_id) block_by_purchaser_email!(by_user_id: blocking_user_id) block_by_ip_address!(by_user_id: blocking_user_id, expires_in: BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months) block_by_charge_processor_fingerprint!(by_user_id: blocking_user_id) block_by_recent_stripe_fingerprint!(by_user_id: blocking_user_id) blocking_user = User.find_by(id: blocking_user_id) if blocking_user_id.present? update!(is_buyer_blocked_by_admin: true) if blocking_user&.is_team_member? create_blocked_buyer_comments!(blocking_user:, comment_content:) end def unblock_buyer! unblock_by_browser_guid! unblock_by_email! unblock_by_paypal_email! unblock_by_gifter_email! unblock_by_purchaser_email! unblock_by_ip_address! unblock_by_charge_processor_fingerprint! unblock_by_recent_stripe_fingerprint! update!(is_buyer_blocked_by_admin: false) if is_buyer_blocked_by_admin? end def charge_processor_fingerprint stripe_charge_processor? ? stripe_fingerprint : card_visual end def pause_payouts_for_seller_based_on_chargeback_rate! return unless seller.present? return if [User::PAYOUT_PAUSE_SOURCE_ADMIN, User::PAYOUT_PAUSE_SOURCE_SYSTEM].include?(seller.payouts_paused_by_source) chargeback_stats = seller.lost_chargebacks chargeback_volume_percentage = chargeback_stats[:volume] return if chargeback_volume_percentage == "NA" volume_rate = chargeback_volume_percentage.to_f return if volume_rate <= User::MAX_CHARGEBACK_RATE_ALLOWED_FOR_PAYOUTS seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM) seller.comments.create( content: "Payouts automatically paused due to chargeback rate (#{chargeback_volume_percentage}) exceeding #{User::MAX_CHARGEBACK_RATE_ALLOWED_FOR_PAYOUTS}% volume.", comment_type: Comment::COMMENT_TYPE_ON_PROBATION, author_name: "pause_payouts_for_seller_based_on_chargeback_rate" ) end private def recent_stripe_fingerprint Purchase.with_stripe_fingerprint .where("purchaser_id = ? or email = ?", purchaser_id, email) .last&.stripe_fingerprint end def blockable_emails_if_fraudulent_transaction [purchaser_email, paypal_email, email, gifter_email].compact_blank.uniq end [:purchaser_email, :paypal_email, :gifter_email, :email].each do |email_attribute| define_method("#{email_attribute}_domain") do send(email_attribute).presence && Mail::Address.new(send(email_attribute)).domain end end def blocked_by_email_domain_if_fraudulent_transaction? blocked_by_email_domain? || blocked_by_paypal_email_domain? || blocked_by_gifter_email_domain? || blocked_by_purchaser_email_domain? end def ban_fraudulent_buyer_browser_guid! return unless stripe_fingerprint unique_failed_fingerprints = Purchase.failed.select("distinct stripe_fingerprint").where( "browser_guid = ? and stripe_fingerprint is not null", browser_guid ) return if unique_failed_fingerprints.count < MAX_NUMBER_OF_FAILED_FINGERPRINTS BlockedObject.block!(BLOCKED_OBJECT_TYPES[:browser_guid], browser_guid, nil) end def ban_buyer_on_fraud_related_error_code! failure_code = stripe_error_code || error_code return if PurchaseErrorCode::FRAUD_RELATED_ERROR_CODES.exclude?(failure_code) block_buyer! end def suspend_buyer_on_fraudulent_card_decline! return if Feature.inactive?(:suspend_fraudulent_buyers) failure_code = stripe_error_code || error_code return unless failure_code == PurchaseErrorCode::CARD_DECLINED_FRAUDULENT return unless purchaser.present? return if purchaser.created_at < MAX_PURCHASER_AGE_FOR_SUSPENSION.ago purchaser.flag_for_fraud!(author_name: "fraudulent_purchases_blocker") purchaser.suspend_for_fraud!(author_name: "fraudulent_purchases_blocker") end def ban_card_testers! return unless stripe_fingerprint return if Feature.inactive?(:ban_card_testers) block_buyer_based_on_recent_failures! block_ip_address_based_on_recent_failures! end def block_buyer_based_on_recent_failures! unique_failed_fingerprints = Purchase.failed.stripe.with_stripe_fingerprint .select("distinct stripe_fingerprint") .where("email = ? or browser_guid = ?", email, browser_guid) .where(created_at: CARD_TESTING_WATCH_PERIOD.ago..) return if unique_failed_fingerprints.count < MAX_NUMBER_OF_FAILED_FINGERPRINTS block_buyer! end def pause_payouts_for_seller_based_on_recent_failures! return if Feature.inactive?(:block_seller_based_on_recent_failures) return if IGNORED_ERROR_CODES.include?(error_code) failed_seller_purchases_watch_minutes, max_seller_failed_purchases_price_cents, seller_age_threshold_days = $redis.mget( RedisKey.failed_seller_purchases_watch_minutes, RedisKey.max_seller_failed_purchases_price_cents, RedisKey.seller_age_threshold_days ) seller_age_threshold_days = seller_age_threshold_days.try(:to_i) || 730 # 2 years return if seller.created_at < seller_age_threshold_days.days.ago failed_seller_purchases_watch_minutes = failed_seller_purchases_watch_minutes.try(:to_i) || 60 # 1 hour max_seller_failed_purchases_price_cents = max_seller_failed_purchases_price_cents.try(:to_i) || 200_000 # $2000 failed_seller_purchases = seller.sales.failed.with_stripe_fingerprint .where(created_at: failed_seller_purchases_watch_minutes.minutes.ago..) failed_price_cents = failed_seller_purchases.sum(:price_cents) if failed_price_cents > max_seller_failed_purchases_price_cents seller.update!(payouts_paused_internally: true, payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM) failed_price_amount = MoneyFormatter.format(failed_price_cents, :usd, no_cents_if_whole: true, symbol: true) seller.comments.create( content: "Payouts paused due to high volume of failed purchases (#{failed_price_amount} USD in #{failed_seller_purchases_watch_minutes} minutes).", comment_type: Comment::COMMENT_TYPE_ON_PROBATION, author_name: "pause_payouts_for_seller_based_on_recent_failures" ) end end def block_ip_address_based_on_recent_failures! return if BlockedObject.ip_address.find_active_object(ip_address).present? unique_failed_fingerprints = Purchase.failed.stripe.with_stripe_fingerprint .select("distinct stripe_fingerprint") .where("ip_address = ?", ip_address) .where(created_at: CARD_TESTING_IP_ADDRESS_WATCH_PERIOD.ago..) return if unique_failed_fingerprints.count < MAX_NUMBER_OF_FAILED_FINGERPRINTS BlockedObject.block!( BLOCKED_OBJECT_TYPES[:ip_address], ip_address, nil, expires_in: CARD_TESTING_IP_ADDRESS_BLOCK_DURATION ) end def block_purchases_on_product! return if Feature.inactive?(:block_purchases_on_product) return if IGNORED_ERROR_CODES.include?(error_code) card_testing_product_watch_minutes, max_number_of_failed_purchases, card_testing_product_block_hours, max_number_of_failed_purchases_in_a_row, failed_purchases_in_a_row_watch_days = $redis.mget( RedisKey.card_testing_product_watch_minutes, RedisKey.card_testing_product_max_failed_purchases_count, RedisKey.card_testing_product_block_hours, RedisKey.card_testing_max_number_of_failed_purchases_in_a_row, RedisKey.card_testing_failed_purchases_in_a_row_watch_days ) card_testing_product_watch_minutes = card_testing_product_watch_minutes.try(:to_i) || 10 max_number_of_failed_purchases = max_number_of_failed_purchases.try(:to_i) || 60 card_testing_product_block_hours = card_testing_product_block_hours.try(:to_i) || 6 max_number_of_failed_purchases_in_a_row = max_number_of_failed_purchases_in_a_row.try(:to_i) || 10 failed_purchases_in_a_row_watch_days = failed_purchases_in_a_row_watch_days.try(:to_i) || 2 failed_purchase_attempts_count = link.sales .failed .not_recurring_charge .where("price_cents > 0") .where("error_code NOT IN (?) OR error_code IS NULL", IGNORED_ERROR_CODES) .where(created_at: card_testing_product_watch_minutes.minutes.ago..).count recent_purchases_failed_in_a_row = failed_purchases_count_redis_namespace.incr(failed_purchases_count_redis_key) failed_purchases_count_redis_namespace.expire(failed_purchases_count_redis_key, failed_purchases_in_a_row_watch_days.days.to_i) return if failed_purchase_attempts_count < max_number_of_failed_purchases \ && recent_purchases_failed_in_a_row < max_number_of_failed_purchases_in_a_row BlockedObject.block!( BLOCKED_OBJECT_TYPES[:product], link_id, nil, expires_in: card_testing_product_block_hours.hours ) end def block_fraudulent_free_purchases! return if total_transaction_cents.nonzero? free_purchases_watch_hours, max_allowed_free_purchases_of_same_product, fraudulent_free_purchases_block_hours = $redis.mget( RedisKey.free_purchases_watch_hours, RedisKey.max_allowed_free_purchases_of_same_product, RedisKey.fraudulent_free_purchases_block_hours ) free_purchases_watch_hours = free_purchases_watch_hours&.to_i || 4 max_allowed_free_purchases_of_same_product = max_allowed_free_purchases_of_same_product&.to_i || 2 fraudulent_free_purchases_block_hours = fraudulent_free_purchases_block_hours&.to_i || 24 # 1 day recent_free_purchases_of_same_product = link.sales .successful .not_recurring_charge .where(total_transaction_cents: 0) .where(ip_address:) .where(created_at: free_purchases_watch_hours.hours.ago..).count return if recent_free_purchases_of_same_product <= max_allowed_free_purchases_of_same_product BlockedObject.block!( BLOCKED_OBJECT_TYPES[:ip_address], ip_address, nil, expires_in: fraudulent_free_purchases_block_hours.hours ) end def delete_failed_purchases_count failed_purchases_count_redis_namespace.del(failed_purchases_count_redis_key) end def failed_purchases_count_redis_key "product_#{link_id}" end def failed_purchases_count_redis_namespace @_failed_purchases_count_redis_namespace ||= Redis::Namespace.new(:failed_purchases_count, redis: $redis) end def create_blocked_buyer_comments!(blocking_user: nil, comment_content:) comment_params = { content: comment_content, comment_type: "note", author_id: blocking_user&.id || GUMROAD_ADMIN_ID } if comment_params[:content].blank? if blocking_user&.is_team_member? comment_params[:content] = "Buyer blocked by Admin (#{blocking_user.email})" elsif blocking_user.present? comment_params[:content] = "Buyer blocked by #{blocking_user.email}" else comment_params[:content] = "Buyer blocked" end end purchaser.comments.create!(comment_params.merge(purchase: self)) if purchaser.present? comments.create!(comment_params) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/recommended.rb
app/models/concerns/purchase/recommended.rb
# frozen_string_literal: true module Purchase::Recommended extend ActiveSupport::Concern def handle_recommended_purchase return unless successful? || preorder_authorization_successful? || is_free_trial_purchase? return if RecommendedPurchaseInfo.where(purchase_id: id).present? if RecommendationType.is_product_recommendation?(recommended_by) recommendation_type = RecommendationType::PRODUCT_RECOMMENDATION recommended_by_link = Link.find_by(unique_permalink: recommended_by) else recommendation_type = recommended_by recommended_by_link = nil end purchase_info_params = { purchase: self, recommended_link: link, recommended_by_link:, recommendation_type:, recommender_model_name:, } if was_discover_fee_charged? purchase_info_params[:discover_fee_per_thousand] = link.discover_fee_per_thousand end RecommendedPurchaseInfo.create!(purchase_info_params) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/purchase/creator_analytics_callbacks.rb
app/models/concerns/purchase/creator_analytics_callbacks.rb
# frozen_string_literal: true module Purchase::CreatorAnalyticsCallbacks extend ActiveSupport::Concern included do after_commit :update_creator_analytics_cache, on: :update def update_creator_analytics_cache(force: false) return if !force && !%w[chargeback_date flags purchase_state stripe_refunded].intersect?(previous_changes.keys) # Do not attempt to update the cache if the purchase exists for the seller's Today, # as we're not caching data for that day. purchase_cache_date = created_at.in_time_zone(seller.timezone).to_date today_date = Time.now.in_time_zone(seller.timezone).to_date return if purchase_cache_date == today_date RegenerateCreatorAnalyticsCacheWorker.perform_in(2.seconds, seller_id, purchase_cache_date.to_s) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/workflow/abandoned_cart_products.rb
app/models/concerns/workflow/abandoned_cart_products.rb
# frozen_string_literal: true module Workflow::AbandonedCartProducts extend ActiveSupport::Concern included do include Rails.application.routes.url_helpers end def abandoned_cart_products(only_product_and_variant_ids: false) return [] unless abandoned_cart_type? include_all_products = bought_products.blank? && bought_variants.blank? query = seller.links.visible_and_not_archived.includes(:alive_variants) query = query.includes(thumbnail_alive: { file_attachment: { blob: { variant_records: { image_attachment: :blob } } } }) if !only_product_and_variant_ids query.filter_map.filter_map do |product| next if not_bought_products&.include?(product.unique_permalink) has_selected_product_variant = bought_variants.present? && (bought_variants & product.alive_variants.map(&:external_id)).any? if include_all_products || has_selected_product_variant || bought_products&.include?(product.unique_permalink) variants = product.alive_variants.filter_map do next if not_bought_variants&.include?(_1.external_id) { external_id: _1.external_id, name: _1.name } if include_all_products || bought_products&.include?(product.unique_permalink) || bought_variants&.include?(_1.external_id) end if only_product_and_variant_ids [product.id, variants.map { ObfuscateIds.decrypt(_1[:external_id]) }] else { unique_permalink: product.unique_permalink, external_id: product.external_id, name: product.name, thumbnail_url: product.for_email_thumbnail_url, url: product.long_url, variants:, seller: { name: seller.display_name, avatar_url: seller.avatar_url, profile_url: seller.profile_url, } } 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/admin/sales_report.rb
app/models/admin/sales_report.rb
# frozen_string_literal: true class Admin::SalesReport include ActiveModel::Model YYYY_MM_DD_FORMAT = /\A\d{4}-\d{2}-\d{2}\z/ INVALID_DATE_FORMAT_MESSAGE = "Invalid date format. Please use YYYY-MM-DD format" ACCESSORS = %i[country_code start_date end_date sales_type].freeze attr_accessor(*ACCESSORS) ACCESSORS.each do |accessor| define_method("#{accessor}?") do public_send(accessor).present? end end validates :country_code, presence: { message: "Please select a country" } validates :start_date, presence: { message: INVALID_DATE_FORMAT_MESSAGE } validates :end_date, presence: { message: INVALID_DATE_FORMAT_MESSAGE } validates :start_date, comparison: { less_than: :end_date, message: "must be before end date", if: %i[start_date? end_date?] } validates :start_date, comparison: { less_than_or_equal_to: -> { Date.current }, message: "cannot be in the future", if: :start_date? } validates_inclusion_of :sales_type, in: GenerateSalesReportJob::SALES_TYPES, message: "Invalid sales type, should be #{GenerateSalesReportJob::SALES_TYPES.join(" or ")}." class << self def fetch_job_history job_data = $redis.lrange(RedisKey.sales_report_jobs, 0, 19) job_data.map { |data| JSON.parse(data) } rescue JSON::ParserError [] end end def generate_later job_id = GenerateSalesReportJob.perform_async( country_code, start_date.to_s, end_date.to_s, sales_type, true, nil ) store_job_details(job_id) end def errors_hash { sales_report: errors.to_hash } end def start_date=(value) @start_date = parse_date(value) end def end_date=(value) @end_date = parse_date(value) end private def parse_date(date) return date if date.is_a?(Date) return if date.blank? return unless date.match?(YYYY_MM_DD_FORMAT) Date.parse(date) rescue Date::Error, ArgumentError Rails.logger.warn("Invalid date format: #{date}, set to nil") nil end def store_job_details(job_id) job_details = { job_id:, country_code:, start_date: start_date.to_s, end_date: end_date.to_s, sales_type:, enqueued_at: Time.current.to_s, status: "processing" } $redis.lpush(RedisKey.sales_report_jobs, job_details.to_json) $redis.ltrim(RedisKey.sales_report_jobs, 0, 19) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/help_center/category.rb
app/models/help_center/category.rb
# frozen_string_literal: true class HelpCenter::Category < ActiveYaml::Base include ActiveHash::Associations include ActiveHash::Enum set_root_path "app/models" has_many :articles, class_name: "HelpCenter::Article" enum_accessor :title def to_param slug end def categories_for_same_audience @_categories_for_same_audience ||= HelpCenter::Category.where(audience: audience) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/help_center/article.rb
app/models/help_center/article.rb
# frozen_string_literal: true # Explicitly require the dependency HelpCenter::Category to avoid circular # dependency that results in a deadlock during loading. require "help_center/category" class HelpCenter::Article < ActiveYaml::Base include ActiveHash::Associations set_root_path "app/models" belongs_to :category, class_name: "HelpCenter::Category" def to_param slug end def to_partial_path "help_center/articles/contents/#{slug}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mailer_info/encryption.rb
app/models/mailer_info/encryption.rb
# frozen_string_literal: true module MailerInfo::Encryption extend self include Kernel def encrypt(value) return value if value.nil? cipher = OpenSSL::Cipher.new("aes-256-cbc") cipher.encrypt key_version = current_key_version cipher.key = derive_key(key_version) iv = cipher.random_iv encrypted = cipher.update(value.to_s) + cipher.final "v#{key_version}:#{Base64.strict_encode64(iv)}:#{Base64.strict_encode64(encrypted)}" end def decrypt(encrypted_value) return encrypted_value if encrypted_value.nil? version, iv, encrypted = encrypted_value.split(":") key_version = version.delete_prefix("v").to_i cipher = OpenSSL::Cipher.new("aes-256-cbc") cipher.decrypt cipher.key = derive_key(key_version) cipher.iv = Base64.strict_decode64(iv) cipher.update(Base64.strict_decode64(encrypted)) + cipher.final end private def derive_key(version) key = encryption_keys.fetch(version) { Kernel.raise "Unknown key version: #{version}" } Digest::SHA256.digest(key) end def encryption_keys { 1 => GlobalConfig.get("MAILER_HEADERS_ENCRYPTION_KEY_V1"), # Add new keys as needed, old keys must be kept for old emails # 2 => GlobalConfig.get("MAILER_HEADERS_ENCRYPTION_KEY_V2"), } end def current_key_version encryption_keys.keys.max end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mailer_info/header_builder.rb
app/models/mailer_info/header_builder.rb
# frozen_string_literal: true require "openssl" class MailerInfo::HeaderBuilder attr_reader :mailer_class, :email_provider attr_reader :mailer_args attr_reader :mailer_method def self.perform(mailer_class:, mailer_method:, mailer_args:, email_provider:) new(mailer_class:, mailer_method:, mailer_args:, email_provider:).perform end def initialize(mailer_class:, mailer_method:, mailer_args:, email_provider:) @mailer_class = mailer_class @mailer_method = mailer_method @mailer_args = mailer_args @email_provider = email_provider end def perform if email_provider == MailerInfo::EMAIL_PROVIDER_RESEND build_for_resend else build_for_sendgrid end end def build_for_sendgrid purchase_id, charge_id = determine_receipt_record_ids { MailerInfo.header_name(:email_provider) => MailerInfo::EMAIL_PROVIDER_SENDGRID, # This header field name must match the one used by SendGrid # https://www.twilio.com/docs/sendgrid/for-developers/sending-email/building-an-x-smtpapi-header MailerInfo::SENDGRID_X_SMTPAPI_HEADER => { environment: Rails.env, category: [mailer_class, "#{mailer_class}.#{mailer_method}"], unique_args: { MailerInfo::FIELD_MAILER_CLASS => mailer_class, MailerInfo::FIELD_MAILER_METHOD => mailer_method, MailerInfo::FIELD_MAILER_ARGS => truncated_mailer_args.inspect, MailerInfo::FIELD_PURCHASE_ID => purchase_id, MailerInfo::FIELD_CHARGE_ID => charge_id, }.compact }.to_json }.compact end def build_for_resend purchase_id, charge_id = determine_receipt_record_ids post_purchase_id, follower_id, affiliate_id, post_id = determine_installment_record_ids workflow_ids = determine_cart_abandoned_workflow_ids headers = { MailerInfo::FIELD_ENVIRONMENT => Rails.env, MailerInfo::FIELD_MAILER_CLASS => mailer_class, MailerInfo::FIELD_MAILER_METHOD => mailer_method, MailerInfo::FIELD_MAILER_ARGS => truncated_mailer_args, MailerInfo::FIELD_CATEGORY => [mailer_class, mailer_method.presence && "#{mailer_class}.#{mailer_method}"].compact.to_json, MailerInfo::FIELD_PURCHASE_ID => purchase_id || post_purchase_id, MailerInfo::FIELD_CHARGE_ID => charge_id, MailerInfo::FIELD_WORKFLOW_IDS => workflow_ids, MailerInfo::FIELD_FOLLOWER_ID => follower_id, MailerInfo::FIELD_AFFILIATE_ID => affiliate_id, MailerInfo::FIELD_POST_ID => post_id }.compact.transform_keys { MailerInfo.header_name(_1) } .transform_values { MailerInfo.encrypt(_1) } headers[MailerInfo.header_name(:email_provider)] = MailerInfo::EMAIL_PROVIDER_RESEND headers end def determine_installment_record_ids purchase_id, follower_id, affiliate_id, post_id = nil, nil, nil, nil if EmailEventInfo::TRACKED_INSTALLMENT_MAILER_METHODS.include?(mailer_method) post_id = mailer_args[1] end if mailer_method == EmailEventInfo::PURCHASE_INSTALLMENT_MAILER_METHOD purchase_id = mailer_args[0] elsif mailer_method == EmailEventInfo::FOLLOWER_INSTALLMENT_MAILER_METHOD follower_id = mailer_args[0] elsif mailer_method == EmailEventInfo::DIRECT_AFFILIATE_INSTALLMENT_MAILER_METHOD affiliate_id = mailer_args[0] end [purchase_id, follower_id, affiliate_id, post_id] end def determine_receipt_record_ids return [nil, nil] unless receipt_email? purchase_id, charge_id = mailer_args.slice(0, 2) if mailer_method == SendgridEventInfo::RECEIPT_MAILER_METHOD # Ensures the correct EmailInfo record will be used, and no duplicates are created # Use case: # 1. Sending the first receipt uses charge_id, and EmailInfo + EmailInfoCharge records are created # 2. Resending the receipt uses purchase_id. # We want the 2nd receipt to update the existing EmailInfo record (with a charge), not create a new one chargeable = Charge::Chargeable.find_by_purchase_or_charge!( purchase: Purchase.find_by(id: purchase_id), charge: Charge.find_by(id: charge_id) ) chargeable.is_a?(Charge) ? [nil, chargeable.id] : [purchase_id, nil] elsif mailer_method == SendgridEventInfo::PREORDER_RECEIPT_MAILER_METHOD [Preorder.find(purchase_id).authorization_purchase.id, nil] else [nil, nil] end end def receipt_email? return false if mailer_class != CustomerMailer.to_s mailer_method.in? SendgridEventInfo::PREORDER_RECEIPT_MAILER_METHOD end def determine_cart_abandoned_workflow_ids return nil unless abandoned_cart_email? raise ArgumentError.new("Abandoned cart email event has unexpected mailer_args size: #{mailer_args.inspect}") if mailer_args.size != 2 mailer_args.second.keys.to_json end def abandoned_cart_email? mailer_class == CustomerMailer.to_s && mailer_method == EmailEventInfo::ABANDONED_CART_MAILER_METHOD end # Minimize the chances for the unique arguments to surpass 10k bytes # https://docs.sendgrid.com/for-developers/sending-email/unique-arguments def truncated_mailer_args mailer_args.map { |argument| argument.is_a?(String) ? argument[0..19] : argument } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mailer_info/router.rb
app/models/mailer_info/router.rb
# frozen_string_literal: true module MailerInfo::Router extend self include Kernel def determine_email_provider(domain) raise ArgumentError, "Invalid domain: #{domain}" unless MailerInfo::DeliveryMethod::DOMAINS.include?(domain) return MailerInfo::EMAIL_PROVIDER_SENDGRID if Feature.inactive?(:resend) return MailerInfo::EMAIL_PROVIDER_RESEND if Feature.active?(:force_resend) # If counters are not set, both return 0, which would default to SendGrid current_count = get_current_count(domain) max_count = get_max_count(domain) Rails.logger.info("[Router] #{domain}: count=#{current_count}/#{max_count}") return MailerInfo::EMAIL_PROVIDER_SENDGRID if max_count_reached?(domain) rand_val = Kernel.rand prob = get_probability(domain) Rails.logger.info("[Router] #{domain}: rand=#{rand_val}, prob=#{prob}") if rand_val <= prob $redis.incr(current_count_key(domain)) MailerInfo::EMAIL_PROVIDER_RESEND else MailerInfo::EMAIL_PROVIDER_SENDGRID end end def set_probability(domain, date, probability) raise ArgumentError, "Invalid domain: #{domain}" unless MailerInfo::DeliveryMethod::DOMAINS.include?(domain) $redis.set(probability_key(domain, date: date.to_date), probability, ex: 3.months) end def set_max_count(domain, date, count) raise ArgumentError, "Invalid domain: #{domain}" unless MailerInfo::DeliveryMethod::DOMAINS.include?(domain) $redis.set(max_count_key(domain, date: date.to_date), count, ex: 3.months) end # Easily readable stats for a domain def domain_stats(domain) raise ArgumentError, "Invalid domain: #{domain}" unless MailerInfo::DeliveryMethod::DOMAINS.include?(domain) stats = [] # Rough range of dates to get stats for, around the time when the migration happened 1.month.ago.to_date.step(1.month.from_now.to_date) do |date| probability = get_probability(domain, date:, allow_nil: true) max_count = get_max_count(domain, date:, allow_nil: true) current_count = get_current_count(domain, date:, allow_nil: true) # Ignore dates where the counters are not set next if probability.nil? && max_count.nil? && current_count.nil? stats << { date: date.to_s, probability:, max_count:, current_count:, } end stats end def stats MailerInfo::DeliveryMethod::DOMAINS.index_with { domain_stats(_1) } end private def get_probability(domain, date: today, allow_nil: false) val = $redis.get(probability_key(domain, date:)) allow_nil && val.nil? ? nil : val.to_f end def get_max_count(domain, date: today, allow_nil: false) val = $redis.get(max_count_key(domain, date:)) allow_nil && val.nil? ? nil : val.to_i end def get_current_count(domain, date: today, allow_nil: false) val = $redis.get(current_count_key(domain, date:)) allow_nil && val.nil? ? nil : val.to_i end def max_count_reached?(domain, date: today) max_count = get_max_count(domain, date:) current_count = get_current_count(domain, date:) current_count >= max_count end def today Date.current.to_s end def current_count_key(domain, date: today) "mail_router:counter:#{domain}:#{date}" end def max_count_key(domain, date: today) "mail_router:max_count:#{domain}:#{date}" end def probability_key(domain, date: today) "mail_router:probability:#{domain}:#{date}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/mailer_info/delivery_method.rb
app/models/mailer_info/delivery_method.rb
# frozen_string_literal: true module MailerInfo::DeliveryMethod extend self include Kernel DOMAIN_GUMROAD = :gumroad DOMAIN_FOLLOWERS = :followers DOMAIN_CREATORS = :creators DOMAIN_CUSTOMERS = :customers DOMAINS = [DOMAIN_GUMROAD, DOMAIN_FOLLOWERS, DOMAIN_CREATORS, DOMAIN_CUSTOMERS] def options(domain:, email_provider:, seller: nil) raise ArgumentError, "Invalid domain: #{domain}" unless DOMAINS.include?(domain) raise ArgumentError, "Seller is only allowed for customers domain" if seller && domain != DOMAIN_CUSTOMERS if seller.present? { address: EMAIL_CREDENTIALS[email_provider][domain][:address], domain: EMAIL_CREDENTIALS[email_provider][domain][:levels][seller.mailer_level][:domain], user_name: EMAIL_CREDENTIALS[email_provider][domain][:levels][seller.mailer_level][:username], password: EMAIL_CREDENTIALS[email_provider][domain][:levels][seller.mailer_level][:password], } else { address: EMAIL_CREDENTIALS[email_provider][domain][:address], domain: EMAIL_CREDENTIALS[email_provider][domain][:domain], user_name: EMAIL_CREDENTIALS[email_provider][domain][:username], password: EMAIL_CREDENTIALS[email_provider][domain][:password], } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/sendable_to_kindle.rb
app/modules/sendable_to_kindle.rb
# frozen_string_literal: true module SendableToKindle extend ActiveSupport::Concern included do def send_to_kindle(kindle_email) raise ArgumentError, "Please enter a valid Kindle email address" unless kindle_email.match(KINDLE_EMAIL_REGEX) CustomerMailer.send_to_kindle(kindle_email, id).deliver_later(queue: "critical") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/recommendation_type.rb
app/modules/recommendation_type.rb
# frozen_string_literal: true module RecommendationType GUMROAD_DISCOVER_RECOMMENDATION = "discover" GUMROAD_SEARCH_RECOMMENDATION = "search" GUMROAD_RECEIPT_RECOMMENDATION = "receipt" GUMROAD_LIBRARY_RECOMMENDATION = "library" GUMROAD_MORE_LIKE_THIS_RECOMMENDATION = "more_like_this" GUMROAD_PRODUCTS_FOR_YOU_RECOMMENDATION = "products_for_you" GUMROAD_STAFF_PICKS_RECOMMENDATION = "staff_picks" GUMROAD_DISCOVER_WISHLIST_RECOMMENDATION = "discover_wishlist" PRODUCT_RECOMMENDATION = "product" WISHLIST_RECOMMENDATION = "wishlist" ALL = [ GUMROAD_DISCOVER_RECOMMENDATION, GUMROAD_SEARCH_RECOMMENDATION, GUMROAD_RECEIPT_RECOMMENDATION, GUMROAD_LIBRARY_RECOMMENDATION, GUMROAD_STAFF_PICKS_RECOMMENDATION, PRODUCT_RECOMMENDATION, WISHLIST_RECOMMENDATION, ].freeze private_constant :ALL def self.all ALL end def self.is_product_recommendation?(rec_type) [ GUMROAD_DISCOVER_RECOMMENDATION, GUMROAD_SEARCH_RECOMMENDATION, GUMROAD_RECEIPT_RECOMMENDATION, GUMROAD_LIBRARY_RECOMMENDATION, GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, GUMROAD_PRODUCTS_FOR_YOU_RECOMMENDATION, GUMROAD_STAFF_PICKS_RECOMMENDATION, WISHLIST_RECOMMENDATION, ].exclude?(rec_type) end def self.is_free_recommendation_type?(rec_typ) [GUMROAD_LIBRARY_RECOMMENDATION, GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, WISHLIST_RECOMMENDATION].include?(rec_typ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/platform.rb
app/modules/platform.rb
# frozen_string_literal: true module Platform WEB = "web" IPHONE = "iphone" ANDROID = "android" OTHER = "other" def self.all [ WEB, IPHONE, ANDROID, OTHER ] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/with_product_files_many_to_many.rb
app/modules/with_product_files_many_to_many.rb
# frozen_string_literal: true # A module to include the WithProductFiles module # and allow for has_and_belongs_to_many relationships # for product files module WithProductFilesManyToMany extend ActiveSupport::Concern included do include WithProductFiles has_and_belongs_to_many :product_files end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/timestamp_scopes.rb
app/modules/timestamp_scopes.rb
# frozen_string_literal: true module TimestampScopes extend ActiveSupport::Concern included do scope :created_between, ->(range) { where(created_at: range) if range } scope :column_between_with_offset, lambda { |column_name, range, offset| where("date(convert_tz(#{table_name}.#{column_name}, '+00:00', ?)) BETWEEN ? AND ?", offset, range.first.to_s, range.last.to_s) } scope :created_at_between_with_offset, lambda { |range, offset| column_between_with_offset("created_at", range, offset) } scope :created_between_dates_in_timezone, lambda { |range, timezone| created_on_or_after_start_of_date_in_timezone(range.begin, timezone) .created_before_end_of_date_in_timezone(range.end, timezone) } scope :created_before_end_of_date_in_timezone, lambda { |day, timezone| where("#{table_name}.created_at < ?", day.tomorrow.in_time_zone(timezone).beginning_of_day) } scope :created_on_or_after_start_of_date_in_timezone, lambda { |day, timezone| where("#{table_name}.created_at >= ?", day.in_time_zone(timezone).beginning_of_day) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/deletable.rb
app/modules/deletable.rb
# frozen_string_literal: true # Module for anything that uses soft deletion functionality. module Deletable extend ActiveSupport::Concern included do scope :alive, -> { where(deleted_at: nil) } scope :deleted, -> { where.not(deleted_at: nil) } end def mark_deleted! self.deleted_at = Time.current save! end def mark_deleted(validate: true) self.deleted_at = Time.current save(validate:) end def mark_undeleted! self.deleted_at = nil save! end def mark_undeleted self.deleted_at = nil save end def alive? deleted_at.nil? end alias_method :alive, :alive? def deleted? deleted_at.present? end def being_marked_as_deleted? deleted_at_changed?(from: nil) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/subdomain.rb
app/modules/subdomain.rb
# frozen_string_literal: true module Subdomain USERNAME_REGEXP = /[a-z0-9-]+/ class << self def find_seller_by_request(request) find_seller_by_hostname(request.host) end def find_seller_by_hostname(hostname) if subdomain_request?(hostname) subdomain = ActionDispatch::Http::URL.extract_subdomains(hostname, 1)[0] return User.alive.find_by(external_id: subdomain) if /^[0-9]+$/.match?(subdomain) # Convert hyphens to underscores before looking up with usernames. # Related conversation: https://git.io/JJgBN User.alive.find_by(username: subdomain.tr("-", "_")) end end def from_username(username) return unless username.present? "#{username.tr("_", "-")}.#{ROOT_DOMAIN}" end private def subdomain_request?(hostname) # Strip port from ROOT_DOMAIN in development and test environments since request.host doesn't contain port. domain = if Rails.env.development? || Rails.env.test? URI("#{PROTOCOL}://#{ROOT_DOMAIN}").host else ROOT_DOMAIN end # Allows lowercase letters, numbers and hyphens (to support usernames with underscores). # Subdomain should contain at least one letter. hostname =~ /\A#{USERNAME_REGEXP.source}.#{domain}\z/ end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/multipart_transfer.rb
app/modules/multipart_transfer.rb
# frozen_string_literal: true module MultipartTransfer # Public: Transfer an item from some arbitrary url source to our s3 bucket using multipart transfer # # source_file_url - The url of the file you wish to copy # destination_filename - Optional, the destination filename of the file you want to copy over, used in renaming # existing_s3_object - Optional, the existing s3 object in our system you are looking to copy over. Providing this # object allows us to use AWS's multipart transfer implementation. # def self.transfer_to_s3(source_file_url, destination_filename: nil, existing_s3_object: nil) s3_guid = (SecureRandom.uuid.split("")[1..-1] - ["-"]).join + SecureRandom.random_number(10).to_s uri = URI(source_file_url) if destination_filename.present? file_name = destination_filename else file_name = uri.path file_name = file_name[1..-1] if file_name.start_with?("/") end destination_key = "attachments/#{s3_guid}/original/#{file_name}" if existing_s3_object.present? Aws::S3::Resource.new.bucket(S3_BUCKET).object(destination_key).copy_from(existing_s3_object, multipart_copy: (existing_s3_object.content_length > 5.megabytes), content_type: existing_s3_object.content_type) else transfer_non_s3_file_to_s3(destination_key, s3_guid, uri) end destination_key end def self.transfer_non_s3_file_to_s3(destination_key, s3_guid, uri) http_req = Net::HTTP.new(uri.host, uri.port) http_req.use_ssl = uri.scheme == "https" http_req.start do |http| request = Net::HTTP::Get.new uri http.request request do |response| extname = File.extname(uri.path) temp_file = Tempfile.new([s3_guid, extname], encoding: "ascii-8bit") response.read_body do |chunk| temp_file.write(chunk) end Aws::S3::Resource.new.bucket(S3_BUCKET).object(destination_key).upload_file(temp_file.path, content_type: fetch_content_type(uri)) temp_file.close(true) end end end def self.fetch_content_type(uri) HTTParty.head(uri).headers["content-type"] end private_class_method :fetch_content_type end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/utilities.rb
app/modules/utilities.rb
# frozen_string_literal: true module Utilities module_function def sign_with_aws_secret_key(to_sign) Base64.encode64( OpenSSL::HMAC.digest( OpenSSL::Digest.new("sha1"), AWS_SECRET_KEY, to_sign ) ).delete("\n") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/discount_code.rb
app/modules/discount_code.rb
# frozen_string_literal: true # DiscountCode is where all discounts for ServiceCharges are kept. They are broken into 2 types: # cents & percentage just like OfferCodes. There is either an amount directly correlated to the type # (e.g. type: :percentage, amount: 50 --> 50% off) or a function name which is used to calculate the # amount and is used in accordance with the type. The reason for this is because invite_credit is based # off of one month's black charge and there are 2 types of recurrence so we cannot set a fixed amount here # and instead have to calculate it on the fly. module DiscountCode INVITE_CREDIT_DISCOUNT_CODE = :invite_credit DISCOUNT_CODES = { invite_credit: { type: :cents, function: :invite_discount_amount } }.freeze end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/with_product_files.rb
app/modules/with_product_files.rb
# frozen_string_literal: true module WithProductFiles def self.included(base) base.class_eval do has_many :product_files has_many :ordered_alive_product_files, -> { alive.in_order }, class_name: "ProductFile" has_many :product_files_archives has_many :product_folders, -> { alive }, foreign_key: :product_id attr_accessor :cached_alive_product_files, :cached_rich_content_files_and_folders end end # Public: Returns a potentially cached list of alive files associated with the product. # # Retrieving the list of files from the same Link object happens often within certain controller actions. # Use this method in order to hit the db once and cache the results on the Link object and reuse them later. # Call this method only if you're sure that you're not changing the files within the same action. def alive_product_files cached_alive_product_files || self.cached_alive_product_files = product_files.alive.in_order.to_a end def has_files? product_files.alive.exists? end def save_files!(files_params, rich_content_params = []) files_to_keep = [] new_product_files = [] existing_files = alive_product_files existing_files_by_external_id = existing_files.index_by(&:external_id) should_check_pdf_stampability = false files_params.each do |file_params| next unless file_params[:url].present? begin external_id = file_params.delete(:external_id) || file_params.delete(:id) product_file = existing_files_by_external_id[external_id] || product_files.build(url: file_params[:url]) files_to_keep << product_file # Defaults to true so that usage sites of this function continue # to work even if they do not take advantage of this optimization modified = ActiveModel::Type::Boolean.new.cast(file_params.delete(:modified) || true) next unless modified if product_file.new_record? new_product_files << product_file file_params[:is_linked_to_existing_file] = true if link && link.user.alive_product_files_excluding_product.where("product_files.url = ? AND product_files.link_id != ?", file_params[:url], link.id).any? WithProductFiles.associate_dropbox_file_and_product_file(product_file) end file_params.delete(:folder_id) if file_params[:folder_id].nil? && !(product_file.folder&.alive?) # TODO(product_edit_react) remove fallback subtitle_files_params = file_params.delete(:subtitle_files) || file_params.delete(:subtitles)&.values thumbnail_signed_id = file_params.delete(:thumbnail)&.dig(:signed_id) || file_params.delete(:thumbnail_signed_id) product_file.update!(file_params) should_check_pdf_stampability = true if product_file.saved_change_to_pdf_stamp_enabled? && product_file.pdf_stamp_enabled? # Update file embed IDs in rich content params before persisting changes if external_id != product_file.external_id rich_content_params.each { update_rich_content_file_id(_1, external_id, product_file.external_id) } end save_subtitle_files(product_file, subtitle_files_params) product_file.thumbnail.attach thumbnail_signed_id if thumbnail_signed_id.present? rescue ActiveRecord::RecordInvalid => e link&.errors&.add(:base, "#{file_params[:url]} is not a valid URL.") if e.message.include?("#{file_params[:url]} is not a valid URL.") link&.errors&.add(:base, "Please upload a thumbnail in JPG, PNG, or GIF format.") if e.message.include?("Please upload a thumbnail in JPG, PNG, or GIF format.") link&.errors&.add(:base, "Could not process your thumbnail, please upload an image with size smaller than 5 MB.") if e.message.include?("Could not process your thumbnail, please upload an image with size smaller than 5 MB.") raise e end end (existing_files - files_to_keep).each(&:mark_deleted) self.cached_alive_product_files = nil generate_entity_archive! if is_a?(Installment) && needs_updated_entity_archive? link.content_updated_at = Time.current if new_product_files.any?(&:link_id?) PdfUnstampableNotifierJob.perform_in(5.seconds, link.id) if is_a?(Link) && should_check_pdf_stampability link&.enqueue_index_update_for(["filetypes"]) end def transcode_videos!(queue: TranscodeVideoForStreamingWorker.sidekiq_options["queue"], first_batch_size: 30, additional_delay_after_first_batch: 5.minutes) # If we attempt to transcode too many videos at once, most would end up being processed on AWS Elemental Mediaconvert, # which is expensive, while our main Gumroad Mediaconvert is essentially free to use. # Spreading out transcodings for the same product allows other videos from other creators to still be processed # in a reasonable amount of time while preventing a high and unlimited AWS cost to be generated. # For context, the vast majority of products that have videos to transcode have less than 10 of them. alive_product_files.select(&:queue_for_transcoding?).each_with_index do |product_file, i| delay = i >= first_batch_size ? additional_delay_after_first_batch * i : 0 TranscodeVideoForStreamingWorker.set(queue:).perform_in(delay, product_file.id, product_file.class.name) end end def has_been_transcoded? alive_product_files.each do |product_file| next unless product_file.streamable? return false unless product_file.transcoded_videos.alive.completed.exists? end true end def has_stream_only_files? alive_product_files.any?(&:stream_only?) end def stream_only? alive_product_files.all?(&:stream_only?) end def map_rich_content_files_and_folders return cached_rich_content_files_and_folders if cached_rich_content_files_and_folders return {} if alive_product_files.empty? || is_a?(Installment) pages = rich_contents&.alive has_only_one_page = pages.size == 1 untitled_page_count = 0 self.cached_rich_content_files_and_folders = pages.each_with_object({}) do |page, mapping| page.title = page.title.presence || (has_only_one_page ? nil : "Untitled #{untitled_page_count += 1}") untitled_folder_count = 0 page.description.each do |node| if node["type"] == RichContent::FILE_EMBED_NODE_TYPE file = alive_product_files.find { |file| file.external_id == node.dig("attrs", "id") } mapping[file.id] = rich_content_mapping(page:, folder: nil, file:) if file.present? elsif node["type"] == RichContent::FILE_EMBED_GROUP_NODE_TYPE node["attrs"]["name"] = node.dig("attrs", "name").presence || "Untitled #{untitled_folder_count += 1}" node["content"].each do |file_node| file = alive_product_files.find { |file| file.external_id == file_node.dig("attrs", "id") } mapping[file.id] = rich_content_mapping(page:, folder: node["attrs"], file:) if file.present? end end end end end def folder_to_files_mapping map_rich_content_files_and_folders.each_with_object({}) do |(file_id, info), mapping| folder_id = info[:folder_id] next unless folder_id (mapping[folder_id] ||= []) << file_id end end def generate_folder_archives!(for_files: []) archives = product_files_archives.folder_archives.alive archived_folders = archives.pluck(:folder_id) folder_to_files = folder_to_files_mapping rich_content_folders = folder_to_files.keys existing_folders = archived_folders & rich_content_folders deleted_folders = archived_folders - rich_content_folders new_folders = rich_content_folders - archived_folders folders_need_updating = existing_folders.select do |folder_id| for_files.any? { folder_to_files[folder_id]&.include?(_1.id) } || archives.find_by(folder_id:)&.needs_updating?(product_files.alive) end archives.where(folder_id: (folders_need_updating + deleted_folders)).find_each(&:mark_deleted!) (folders_need_updating + new_folders).each do |folder_id| files_to_archive = alive_product_files.select { |file| folder_to_files[folder_id]&.include?(file.id) && file.archivable? } next if files_to_archive.count <= 1 create_archive!(files_to_archive, folder_id) end end def generate_entity_archive! product_files_archives.entity_archives.alive.each(&:mark_deleted!) files_to_archive = alive_product_files.select(&:archivable?) return if files_to_archive.empty? create_archive!(files_to_archive, nil) end def has_stampable_pdfs? false end # Internal: Check if a zip archive should ever be generated for this product # This is for a product in general, not a specific purchase of a product. # # Examples: # # If there are stamped PDFs, this can never be included in a download all, so # don't generate a zip archive. Return false. # # If a product is rent_only, no files can be downloaded, so don't bother generating # a zip file. Return false. # # If a product is rentable and buyable, there is the possibility for some buyers to # download product_files. A zip archive should be prepared. Return true. def is_downloadable? return false if has_stampable_pdfs? return false if stream_only? true end def needs_updated_entity_archive? return false unless is_downloadable? archive = product_files_archives.latest_ready_entity_archive archive.nil? || archive.needs_updating?(product_files.alive) end private def create_archive!(files_to_archive, folder_id = nil) product_files_archive = product_files_archives.new(folder_id:) product_files_archive.product_files = files_to_archive product_files_archive.save! product_files_archive.set_url_if_not_present product_files_archive.save! end def rich_content_mapping(page:, folder: nil, file:) { page_id: page.external_id, page_title: page.title.presence, folder_id: folder&.fetch("uid", nil), folder_name: folder&.fetch("name", nil), file_id: file.external_id, file_name: file.name_displayable } end def save_subtitle_files(product_file, subtitle_files_params) product_file.save_subtitle_files!(subtitle_files_params || {}) rescue ActiveRecord::RecordInvalid => e errors.add(:base, e.message) raise e end # Private: associate_dropbox_file_and_product_file # # product_file - The product file we are looking to associate to a dropbox file # # This method associates a newly created product file and an existing dropbox file if it exists. # We must do this to prevent a user from seeing a previouly associated dropbox file when they visit # the product edit page or product creation page. Once a dropbox file is associated to a product file # the dropbox file should never be displayed to the user in the ui. # def self.associate_dropbox_file_and_product_file(product_file) return if product_file.link.try(:user).nil? user_dropbox_files = product_file.link.user.dropbox_files dropbox_file = user_dropbox_files.where(s3_url: product_file.url, product_file_id: nil).first return if dropbox_file.nil? dropbox_file.product_file = product_file dropbox_file.link = product_file.link dropbox_file.save! end def update_rich_content_file_id(rich_content, from, to) if rich_content["type"] == "fileEmbed" && rich_content["attrs"]["id"] == from rich_content["attrs"]["id"] = to end rich_content["content"].each { update_rich_content_file_id(_1, from, to) } if rich_content["content"].present? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/money_formatter.rb
app/modules/money_formatter.rb
# frozen_string_literal: true module MoneyFormatter module_function def format(amount, currency_type, opts = {}) amount ||= 0 # use the default symbol unless explicitly stated not to use one opts[:symbol] = CURRENCY_CHOICES[currency_type][:symbol] unless opts[:symbol] == false Money.new(amount, currency_type).format(opts) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/cdn_deletable.rb
app/modules/cdn_deletable.rb
# frozen_string_literal: true module CdnDeletable extend ActiveSupport::Concern included do scope :alive_in_cdn, -> { where(deleted_from_cdn_at: nil) } scope :cdn_deletable, -> { s3.deleted.alive_in_cdn } end def deleted_from_cdn? deleted_from_cdn_at.present? end def mark_deleted_from_cdn update_column(:deleted_from_cdn_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/modules/integrations.rb
app/modules/integrations.rb
# frozen_string_literal: true module Integrations def find_integration_by_name(name) active_integrations.by_name(name).first end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/paypal_api_response.rb
app/modules/paypal_api_response.rb
# frozen_string_literal: true module PaypalApiResponse def open_struct_to_hash(object, hash = {}) case object when OpenStruct object.each_pair do |key, value| hash[key] = case value when OpenStruct then open_struct_to_hash(value) when Array then value.map { |v| open_struct_to_hash(v) } else value end end when Array object.map { |v| open_struct_to_hash(v) } else object end hash end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/with_file_properties.rb
app/modules/with_file_properties.rb
# frozen_string_literal: true module WithFileProperties include InfosHelper MAX_DOWNLOAD_SIZE = 1_073_741_824 # 1gb MAX_VIDEO_DOWNLOAD_SIZE = 40.gigabytes def file_info(require_shipping = false) # One-off for not showing image properties for a physical product. return {} if filegroup == "image" && require_shipping attributes = { Size: size_displayable, Duration: duration_displayable(duration), Length: pagelength_displayable, Resolution: resolution_displayable }.delete_if { |_k, v| v.blank? } attributes end def determine_and_set_filegroup(extension) # CONVENTION: the filegroup is what follows the last underscore self.filetype = extension FILE_REGEX.each do |k, v| if extension.match(v) self.filegroup = k.split("_")[-1] break end end # Case filetype is unidentified self.filegroup = "url" if filegroup.nil? end def analyze return if deleted? || !s3? clear_properties confirm_s3_key! begin self.size = s3_object.content_length rescue Aws::S3::Errors::NotFound => e raise e.exception("Key = #{s3_key} -- #{self.class.name}.id = #{id}") end file_uuid = SecureRandom.uuid logger.info("Analyze -- writing #{s3_url} to #{file_uuid}") FILE_REGEX.each do |file_type, regex| next unless filetype.match(regex) if methods.grep(/assign_#{file_type}_attributes/) != [] && size && size < max_download_size_for_file_type(file_type) temp_file = Tempfile.new([file_uuid, File.extname(s3_url)], encoding: "ascii-8bit") begin s3_object.get(response_target: temp_file) temp_file.rewind path = temp_file.path if path.present? action = :"assign_#{file_type}_attributes" respond_to?(action) && send(action, path) end ensure temp_file.close! end end break end save! end def clear_properties self.duration = nil self.bitrate = nil self.framerate = nil self.width = nil self.height = nil self.pagelength = nil end def log_uncountable logger.info("Could not get pagecount for #{self.class} #{id}") end def assign_video_attributes(path) if filetype == "mov" probe = Ffprobe.new(path).parse self.framerate = probe.framerate self.duration = probe.duration.to_i self.width = probe.width self.height = probe.height self.bitrate = probe.bit_rate.to_i else movie = FFMPEG::Movie.new(path) self.framerate = movie.frame_rate self.duration = movie.duration self.width = movie.width self.height = movie.height self.bitrate = movie.bitrate if movie.bitrate.present? end self.analyze_completed = true if respond_to?(:analyze_completed=) save! video_file_analysis_completed rescue NoMethodError logger.info("Could not analyze movie product file #{id}") end def assign_audio_attributes(path) song = FFMPEG::Movie.new(path) self.duration = song.duration self.bitrate = song.bitrate rescue ArgumentError logger.error("Cannot Analyze product file: #{id} of filetype: #{filetype}. FFMPEG cannot handle certain .wav files.") end def assign_image_attributes(path) image = ImageSorcery.new(path) self.width = image.dimensions[:x] self.height = image.dimensions[:y] end def assign_epub_document_attributes(path) epub_section_info = {} book = EPUB::Parser.parse(path) section_count = book.spine.items.count self.pagelength = section_count book.spine.items.each_with_index do |item, index| section_name = item.content_document.nokogiri.xpath("//xmlns:title").try(:text) section_number = index + 1 # Since the index is 0-based and section number is 1-based. section_id = item.id epub_section_info[section_id] = { "section_number" => section_number, "section_name" => section_name } end self.epub_section_info = epub_section_info rescue NoMethodError, Archive::Zip::EntryError, ArgumentError => e logger.info("Could not analyze epub product file #{id} (#{e.class}: #{e.message})") end def assign_document_attributes(path) count_pages(path) end def assign_psd_attributes(path) image = ImageSorcery.new(path) self.width = image.dimensions[:x] self.height = image.dimensions[:y] end def count_pages(path) counter = :"count_pages_#{ filetype }" if respond_to?(counter) # is there a counter method corresponding to this filetype? begin send(counter, path) rescue StandardError log_uncountable end else log_uncountable end end def count_pages_doc(path) self.pagelength = Subexec.run("wvSummary #{path}").output.scan(/Number of Pages = (\d+)/)[0][0] end def count_pages_docx(path) Zip::File.open(path) do |zipfile| self.pagelength = zipfile.file.read("docProps/app.xml").scan(%r{<Pages>(\d+)</Pages>})[0][0] end end def count_pages_pdf(path) self.pagelength = PDF::Reader.new(path).page_count end def count_pages_ppt(path) self.pagelength = Subexec.run("wvSummary #{path} | grep \"Number of Slides\"").output.scan(/Number of Slides = (\d+)/)[0][0] end def count_pages_pptx(path) Zip::File.open(path) do |zipfile| self.pagelength = zipfile.file.read("docProps/app.xml").scan(%r{<Slides>(\d+)</Slides>})[0][0] end end private def max_download_size_for_file_type(file_type) file_type == "video" ? MAX_VIDEO_DOWNLOAD_SIZE : MAX_DOWNLOAD_SIZE end def transcode_video(streamable) TranscodeVideoForStreamingWorker.perform_in(10.seconds, streamable.id, streamable.class.name) end def video_file_analysis_completed end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/mongo_collections.rb
app/modules/mongo_collections.rb
# frozen_string_literal: true module MongoCollections EXTRA_EVENT_DATA = "extra_event_data" USER_SUSPENSION_TIME = "user_suspension_time" USER_FLAG_TIME = "user_flag_time" USER_RISK_STATE = "user_risk_state" SCIENCE_OF_DOGS_CARDS = "science_of_dogs_cards" LINK = "Link" PURCHASE = "Purchase" USER = "User" PURCHASE_RISK_LEVELS = "purchase_risk_levels" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/twitter_cards.rb
app/modules/twitter_cards.rb
# frozen_string_literal: true module TwitterCards TWITTER_CARD_DOMAIN = "Gumroad" module_function def twitter_product_card(link, product_description: nil) card = "summary" preview = {} description = if product_description.present? product_description elsif link.description.present? link.plaintext_description else "Available on Gumroad" end if link.preview_image_path? card = "summary_large_image" preview = { image: link.preview_url } elsif link.preview_oembed.present? card = "player" preview = { image: link.preview_oembed_thumbnail_url, player: link.preview_oembed_url, "player:width" => link.preview_oembed_width, "player:height" => link.preview_oembed_height } elsif link.preview_video_path? card = "player" preview = { # we don't really have a placeholder for audio/video previews image: "https://gumroad.com/assets/icon.png", player: link.preview_url, "player:width" => link.preview_width, "player:height" => link.preview_height } end user = link.user.twitter_handle? ? { creator: "@" + link.user.twitter_handle } : {} description = description[0, 197] + "..." if description.length > 200 card_properties = { card:, title: link.name, domain: TWITTER_CARD_DOMAIN, description: }.merge(user).merge(preview) card_properties.map do |name, value| twitter_meta_tag(name, value) end.join("\n") + "\n" end module_function def twitter_post_card(post) # No information from pundit_user is needed to generate the card # TODO: use a dedicated presenter for this that encapulates the logic below to build the Hash post_presenter = PostPresenter.new( pundit_user: SellerContext.logged_out, post:, purchase_id_param: nil ) post_properties = { title: post.name, domain: TWITTER_CARD_DOMAIN, description: post_presenter.snippet } image_properties = if post_presenter.social_image.present? { card: "summary_large_image", image: post_presenter.social_image.url, 'image:alt': post_presenter.social_image.caption } else { card: "summary" } end card_properties = post_properties.merge(image_properties) card_properties.map do |name, value| twitter_meta_tag(name, value) end.join("\n") + "\n" end def twitter_meta_tag(name, value) value = value.to_s.html_safe? ? value.to_s : CGI.escapeHTML(value.to_s) value = %("#{value}") "<meta property=\"twitter:#{name}\" value=#{value} />" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/mongoable.rb
app/modules/mongoable.rb
# frozen_string_literal: true module Mongoable def time_fields raise NotImplementedError end def to_mongo attributes_to_save = attributes attributes_to_save["updated_at"] = Time.current time_fields.each do |field| attributes_to_save[field] = send(field.to_sym).utc.to_time if send(field.to_sym).present? end Mongoer.async_write(self.class.to_s, JSON.parse(JSON.dump(attributes_to_save))) end # Public: Returns a mongo query to get the history of this record as stored in the mongo database. # Call `one` on the result of this function to get the first, or `limit(...)` to set the limit and # `to_a` to get all the results. Use `sort(field: 1 or -1)` to sort. def history MONGO_DATABASE[self.class.to_s].find("id" => id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/vertical.rb
app/modules/vertical.rb
# frozen_string_literal: true module Vertical FILM = "film" MUSIC = "music" PUBLISHING = "publishing" EDUCATION = "education" SOFTWARE = "software" PHYSICAL = "physical" OTHER = "other" NOTHING = "nothing" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/obfuscate_ids.rb
app/modules/obfuscate_ids.rb
# frozen_string_literal: true require "openssl" require "base64" module ObfuscateIds CIPHER_KEY = GlobalConfig.get("OBFUSCATE_IDS_CIPHER_KEY") NUMERIC_CIPHER_KEY = GlobalConfig.get("OBFUSCATE_IDS_NUMERIC_CIPHER_KEY").to_i MAX_BYTES_FOR_NUMERIC_ENCRYPTION = 30 def self.encrypt(id, padding: true) c = cipher.encrypt c.key = Digest::SHA256.digest(CIPHER_KEY) Base64.urlsafe_encode64(c.update(id.to_s) + c.final, padding:) end def self.cipher OpenSSL::Cipher.new("aes-256-cbc") end def self.decrypt(id) c = cipher.decrypt c.key = Digest::SHA256.digest(CIPHER_KEY) begin (c.update(Base64.urlsafe_decode64(id.to_s)) + c.final).to_i rescue ArgumentError, OpenSSL::Cipher::CipherError => e Rails.logger.warn "could not decrypt #{id}: #{e.message} #{e.backtrace}" nil end end # Public: Encrypt id using NUMERIC_CIPHER_KEY # # id - id to be encrypted # # Examples # # encrypt_numeric(1) # # => 302841629 # # Returns encrypted numeric id def self.encrypt_numeric(id) raise ArgumentError, "Numeric encryption does not support ids greater than #{max_numeric_id}" if id > max_numeric_id extended_and_reversed_binary_id = id.to_s(2).rjust(MAX_BYTES_FOR_NUMERIC_ENCRYPTION, "0") binary_id = xor(extended_and_reversed_binary_id, NUMERIC_CIPHER_KEY.to_s(2), 30).reverse binary_id.to_i(2) end # Public: Decrypt id using NUMERIC_CIPHER_KEY # # id - id to be decrypted # # Examples # # decrypt_numeric(302841629) # # => 1 # # Returns decrypted numeric id def self.decrypt_numeric(encrypted_id) binary_id = encrypted_id.to_s(2).rjust(MAX_BYTES_FOR_NUMERIC_ENCRYPTION, "0").reverse extended_binary_id = xor(binary_id, NUMERIC_CIPHER_KEY.to_s(2), MAX_BYTES_FOR_NUMERIC_ENCRYPTION) extended_binary_id.to_i(2) end # Private: Maximum numeric id that can be encrypted # # Returns integer def self.max_numeric_id (2**MAX_BYTES_FOR_NUMERIC_ENCRYPTION) - 1 end private_class_method :max_numeric_id # Private: Bitwise xor of two binary strings of length n # # binary_string_a, binary_string_b - strings to be xor'd # n - number of bits in strings # # Example # # xor("1000", "0011", 4) # # => "1011" # # Returns string that is xor of inputs def self.xor(binary_string_a, binary_string_b, n) ((0..n - 1).map { |index| (binary_string_a[index].to_i ^ binary_string_b[index].to_i) }).join("") end private_class_method :xor end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/purchase_error_code.rb
app/modules/purchase_error_code.rb
# frozen_string_literal: true module PurchaseErrorCode INVALID_NUMBER = "invalid_number" HIGH_RISK_COUNTRY = "high_risk_country" PRICE_TOO_HIGH = "price_too_high" BLOCKED_BROWSER_GUID = "blocked_browser_guid" BLOCKED_EMAIL_DOMAIN = "blocked_email_domain" BLOCKED_IP_ADDRESS = "blocked_ip_address" BLOCKED_CHARGE_PROCESSOR_FINGERPRINT = "blocked_charge_processor_fingerprint" BLOCKED_CUSTOMER_EMAIL_ADDRESS = "blocked_customer_email_address" BLOCKED_CUSTOMER_CHARGE_PROCESSOR_FINGERPRINT = "blocked_customer_charge_processor_fingerprint" TEMPORARILY_BLOCKED_EMAIL_ADDRESS = "email_temporarily_blocked" SUSPENDED_BUYER = "suspended_buyer" STRIPE_UNAVAILABLE = "stripe_unavailable" PAYPAL_UNAVAILABLE = "paypal_unavailable" PROCESSING_ERROR = "processing_error" HIGH_PROXY_SCORE_AND_ADDITIONAL_CONTRIBUTION = "high_proxy_score_can_only_buy_once" BUYER_CHARGED_BACK = "buyer_has_charged_back" PRICE_CENTS_TOO_LOW = "price_cents_too_low" CONTRIBUTION_TOO_LOW = "contribution_too_low" BAD_PLUGINS = "bad_plugins" CREDIT_CARD_NOT_PROVIDED = "credit_card_not_provided" OFFER_CODE_INACTIVE = "offer_code_inactive" OFFER_CODE_INSUFFICIENT_QUANTITY = "offer_code_insufficient_quantity" OFFER_CODE_INVALID = "offer_code_invalid" OFFER_CODE_SOLD_OUT = "offer_code_sold_out" EXCEEDING_OFFER_CODE_QUANTITY = "exceeding_offer_code_quantity" SUBSCRIPTION_INACTIVE = "subscription_inactive" PERCEIVED_PRICE_CENTS_NOT_MATCHING = "perceived_price_cents_not_matching" PRODUCT_SOLD_OUT = "product_sold_out" INVALID_QUANTITY = "invalid_quantity" EXCEEDING_PRODUCT_QUANTITY = "exceeding_product_quantity" VARIANT_SOLD_OUT = "variant_sold_out" EXCEEDING_VARIANT_QUANTITY = "exceeding_variant_quantity" MISSING_VARIANTS = "missing_variants" NOT_FOR_SALE = "not_for_sale" TEMPORARILY_BLOCKED_PRODUCT = "product_temporarily_blocked" TAX_VALIDATION_FAILED = "tax_location_validation_failed" ONLY_FOR_RENT = "only_for_rent" NOT_FOR_RENT = "not_for_rent" NO_SHIPPING_COUNTRY_CONFIGURED = "cant_ship_to_country" BLOCKED_SHIPPING_COUNTRY = "compliance_blocked_country" PPP_CARD_COUNTRY_NOT_MATCHING = "ppp_card_country_not_matching" PAYPAL_MERCHANT_ACCOUNT_RESTRICTED = "paypal_merchant_account_restricted" PAYPAL_PAYER_CANCELLED_BILLING_AGREEMENT = "paypal_payer_cancelled_billing_agreement" PAYPAL_PAYER_ACCOUNT_DECLINED_PAYMENT = "paypal_payer_account_declined_payment" STRIPE_INSUFFICIENT_FUNDS = "card_declined_insufficient_funds" NET_NEGATIVE_SELLER_REVENUE = "net_negative_seller_revenue" CARD_DECLINED_FRAUDULENT = "card_declined_fraudulent" BRAZILIAN_MERCHANT_ACCOUNT_WITH_AFFILIATE = "brazilian_merchant_account_with_affiliate" PAYPAL_ERROR_CODES = { "2000" => "Do Not Honor", "2001" => "Insufficient Funds", "2002" => "Limit Exceeded", "2003" => "Cardholder's Activity Limit Exceeded", "2004" => "Expired Card", "2005" => "Invalid Credit Card Number", "2006" => "Invalid Expiration Date", "2007" => "No Account", "2008" => "Card Account Length Error", "2009" => "No Such Issuer", "2010" => "Card Issuer Declined CVV", "2011" => "Voice Authorization Required", "2012" => "Processor Declined - Possible Lost Card", "2013" => "Processor Declined - Possible Stolen Card", "2014" => "Processor Declined - Fraud Suspected", "2015" => "Transaction Not Allowed", "2016" => "Duplicate Transaction", "2017" => "Cardholder Stopped Billing", "2018" => "Cardholder Stopped All Billing", "2019" => "Invalid Transaction", "2020" => "Violation", "2021" => "Security Violation", "2022" => "Declined - Updated Cardholder Available", "2023" => "Processor Does Not Support This Feature", "2024" => "Card Type Not Enabled", "2025" => "Set Up Error - Merchant", "2026" => "Invalid Merchant ID", "2027" => "Set Up Error - Amount", "2028" => "Set Up Error - Hierarchy", "2029" => "Set Up Error - Card", "2030" => "Set Up Error - Terminal", "2031" => "Encryption Error", "2032" => "Surcharge Not Permitted", "2033" => "Inconsistent Data", "2034" => "No Action Taken", "2035" => "Partial Approval For Amount In Group III Version", "2036" => "Authorization could not be found", "2037" => "Already Reversed", "2038" => "Processor Declined", "2039" => "Invalid Authorization Code", "2040" => "Invalid Store", "2041" => "Declined - Call For Approval", "2042" => "Invalid Client ID", "2043" => "Error - Do Not Retry, Call Issuer", "2044" => "Declined - Call Issuer", "2045" => "Invalid Merchant Number", "2046" => "Declined", "2047" => "Call Issuer. Pick Up Card", "2048" => "Invalid Amount", "2049" => "Invalid SKU Number", "2050" => "Invalid Credit Plan", "2051" => "Credit Card Number does not match method of payment", "2053" => "Card reported as lost or stolen", "2054" => "Reversal amount does not match authorization amount", "2055" => "Invalid Transaction Division Number", "2056" => "Transaction amount exceeds the transaction division limit", "2057" => "Issuer or Cardholder has put a restriction on the card", "2058" => "Merchant not Mastercard SecureCode enabled", "2059" => "Address Verification Failed", "2060" => "Address Verification and Card Security Code Failed", "2061" => "Invalid Transaction Data", "2062" => "Invalid Tax Amount", "2063" => "PayPal Business Account preference resulted in the transaction failing", "2064" => "Invalid Currency Code", "2065" => "Refund Time Limit Exceeded", "2066" => "PayPal Business Account Restricted", "2067" => "Authorization Expired", "2068" => "PayPal Business Account Locked or Closed", "2069" => "PayPal Blocking Duplicate Order IDs", "2070" => "PayPal Buyer Revoked Pre-Approved Payment Authorization", "2071" => "PayPal Payee Account Invalid Or Does Not Have a Confirmed Email", "2072" => "PayPal Payee Email Incorrectly Formatted", "2073" => "PayPal Validation Error", "2074" => "Funding Instrument In The PayPal Account Was Declined By The Processor Or Bank, Or It Can't Be Used For This Payment", "2075" => "Payer Account Is Locked Or Closed", "2076" => "Payer Cannot Pay For This Transaction With PayPal", "2077" => "Transaction Refused Due To PayPal Risk Model", "2079" => "PayPal Merchant Account Configuration Error", "2081" => "PayPal pending payments are not supported", "2082" => "PayPal Domestic Transaction Required", "2083" => "PayPal Phone Number Required", "2084" => "PayPal Tax Info Required", "2085" => "PayPal Payee Blocked Transaction", "2086" => "PayPal Transaction Limit Exceeded", "2087" => "PayPal reference transactions not enabled for your account", "2088" => "Currency not enabled for your PayPal seller account", "2089" => "PayPal payee email permission denied for this request", "2090" => "PayPal account not configured to refund more than settled amount", "2091" => "Currency of this transaction must match currency of your PayPal account", "2092" => "No Data Found - Try Another Verification Method", "2093" => "PayPal payment method is invalid", "2094" => "PayPal payment has already been completed", "2095" => "PayPal refund is not allowed after partial refund", "2096" => "PayPal buyer account can't be the same as the seller account", "2097" => "PayPal authorization amount limit exceeded", "2098" => "PayPal authorization count limit exceeded", "2099" => "Cardholder Authentication Required", "2100" => "PayPal channel initiated billing not enabled for your account", "2101-2999" => "Processor Declined", # No need to match these just placeholder. "3000" => "Processor Network Unavailable - Try Again", PAYPAL_PAYER_CANCELLED_BILLING_AGREEMENT => "Customer has cancelled the billing agreement on PayPal.", PAYPAL_PAYER_ACCOUNT_DECLINED_PAYMENT => "Customer PayPal account has declined the payment.", "paypal_capture_failure" => "The transaction was declined for an unknown reason.", }.freeze STRIPE_ERROR_CODES = { "authentication_required" => "The card was declined as the transaction requires authentication.", "approve_with_id" => "The payment cannot be authorized.", "call_issuer" => "The card has been declined for an unknown reason.", "card_not_supported" => "The card does not support this type of purchase.", "card_velocity_exceeded" => "The customer has exceeded the balance or credit limit available on their card.", "currency_not_supported" => "The card does not support the specified currency.", "do_not_honor" => "The card has been declined for an unknown reason.", "do_not_try_again" => "The card has been declined for an unknown reason.", "duplicate_transaction" => "A transaction with identical amount and credit card information was submitted very recently.", "expired_card" => "The card has expired.", "fraudulent" => "The payment has been declined as Stripe suspects it is fraudulent.", "generic_decline" => "The card has been declined for an unknown reason.", "incorrect_number" => "The card number is incorrect.", "incorrect_cvc" => "The CVC number is incorrect.", "incorrect_pin" => "The PIN entered is incorrect. This decline code only applies to payments made with a card reader.", "incorrect_zip" => "The ZIP/postal code is incorrect.", "insufficient_funds" => "The card has insufficient funds to complete the purchase.", "invalid_amount" => "The payment amount is invalid, or exceeds the amount that is allowed.", "invalid_cvc" => "The CVC number is incorrect.", "invalid_expiry_month" => "The expiration month is invalid.", "invalid_expiry_year" => "The expiration year is invalid.", "invalid_number" => "The card number is incorrect.", "invalid_pin" => "The PIN entered is incorrect. This decline code only applies to payments made with a card reader.", "issuer_not_available" => "The card issuer could not be reached, so the payment could not be authorized.", "lost_card" => "The payment has been declined because the card is reported lost.", "merchant_blacklist" => "The payment has been declined because it matches a value on the Stripe user’s block list.", "new_account_information_available" => "The card, or account the card is connected to, is invalid.", "no_action_taken" => "The card has been declined for an unknown reason.", "not_permitted" => "The payment is not permitted.", "offline_pin_required" => "The card has been declined as it requires a PIN.", "online_or_offline_pin_required" => "The card has been declined as it requires a PIN.", "pickup_card" => "The card cannot be used to make this payment (it is possible it has been reported lost or stolen).", "pin_try_exceeded" => "The allowable number of PIN tries has been exceeded.", "processing_error" => "An error occurred while processing the card.", "reenter_transaction" => "The payment could not be processed by the issuer for an unknown reason.", "restricted_card" => "The card cannot be used to make this payment (it is possible it has been reported lost or stolen).", "revocation_of_all_authorizations" => "The card has been declined for an unknown reason.", "revocation_of_authorization" => "The card has been declined for an unknown reason.", "security_violation" => "The card has been declined for an unknown reason.", "service_not_allowed" => "The card has been declined for an unknown reason.", "stolen_card" => "The payment has been declined because the card is reported stolen.", "stop_payment_order" => "The card has been declined for an unknown reason.", "testmode_decline" => "A Stripe test card number was used.", "transaction_not_allowed" => "The card has been declined for an unknown reason.", "try_again_later" => "The card has been declined for an unknown reason.", "withdrawal_count_limit_exceeded" => "The customer has exceeded the balance or credit limit available on their card." }.freeze FRAUD_RELATED_ERROR_CODES = [CARD_DECLINED_FRAUDULENT, "card_declined_lost_card", "card_declined_pickup_card", "card_declined_stolen_card"].freeze PAYMENT_ERROR_CODES = PAYPAL_ERROR_CODES.keys .concat(STRIPE_ERROR_CODES.keys) .concat([ STRIPE_UNAVAILABLE, PAYPAL_UNAVAILABLE, PROCESSING_ERROR, CREDIT_CARD_NOT_PROVIDED, ]) UNBLOCK_BUYER_ERROR_CODES = FRAUD_RELATED_ERROR_CODES + [TEMPORARILY_BLOCKED_EMAIL_ADDRESS] def self.customer_error_message(error = nil) error || "Your card was declined. Please try a different card or contact your bank." end def self.is_temporary_network_error?(error_code) error_code == STRIPE_UNAVAILABLE || error_code == PAYPAL_UNAVAILABLE || error_code == PROCESSING_ERROR end def self.is_error_retryable?(error_code) error_code == STRIPE_INSUFFICIENT_FUNDS end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/elasticsearch_model_async_callbacks.rb
app/modules/elasticsearch_model_async_callbacks.rb
# frozen_string_literal: true module ElasticsearchModelAsyncCallbacks extend ActiveSupport::Concern include TransactionalAttributeChangeTracker included do after_commit lambda { send_to_elasticsearch("index") }, on: :create after_commit lambda { send_to_elasticsearch("update") }, on: :update after_commit lambda { send_to_elasticsearch("delete") }, on: :destroy private def send_to_elasticsearch(action) options = { "record_id" => id, "class_name" => self.class.name } if action == "update" fields = self.class::ATTRIBUTE_TO_SEARCH_FIELDS.values_at(*attributes_committed).flatten.uniq.compact return if fields.empty? options["fields"] = fields end delay = action == "index" ? 2.seconds : 4.seconds ElasticsearchIndexerWorker.perform_in(delay, action, options) # Mitigation of small replica lag issues: ElasticsearchIndexerWorker.perform_in(3.minutes, action, options) if action.in?(%w[index update]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/lograge_helper.rb
app/modules/lograge_helper.rb
# frozen_string_literal: true module LogrageHelper def append_info_to_payload(payload) super payload[:remote_ip] = request.remote_ip payload[:uuid] = request.uuid payload[:headers] = { "CF-RAY" => request.headers["HTTP_CF_RAY"], "X-Amzn-Trace-Id" => request.headers["HTTP_X_AMZN_TRACE_ID"], "X-Revision" => REVISION } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/modules/with_cdn_url.rb
app/modules/with_cdn_url.rb
# frozen_string_literal: true module WithCdnUrl include CdnUrlHelper extend ActiveSupport::Concern class_methods do def has_cdn_url(*attributes) attributes.each do |attribute| define_method attribute do replace_s3_urls_with_cdn_urls(self.attributes[attribute.to_s]) 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/modules/external_id.rb
app/modules/external_id.rb
# frozen_string_literal: true module ExternalId extend ActiveSupport::Concern def external_id ObfuscateIds.encrypt(id) end def external_id_numeric ObfuscateIds.encrypt_numeric(id) end class_methods do def to_external_id(id) ObfuscateIds.encrypt(id) end def from_external_id(external_id) ObfuscateIds.decrypt(external_id) end def find_by_external_id(external_id) find_by(id: from_external_id(external_id)) end def find_by_external_id!(external_id) find_by!(id: from_external_id(external_id)) end def find_by_external_id_numeric(id) find_by(id: ObfuscateIds.decrypt_numeric(id)) end def find_by_external_id_numeric!(id) find_by!(id: ObfuscateIds.decrypt_numeric(id)) end def by_external_ids(external_ids) where(id: Array.wrap(external_ids).map { from_external_id(it) }) end def external_id?(id_or_external_id) raise ArgumentError, "value can't be blank" if id_or_external_id.blank? id_or_external_id.to_i.to_s != id_or_external_id end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false