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/mailer_info.rb
app/models/mailer_info.rb
# frozen_string_literal: true module MailerInfo extend self include Kernel EMAIL_PROVIDER_SENDGRID = "sendgrid" EMAIL_PROVIDER_RESEND = "resend" SENDGRID_X_SMTPAPI_HEADER = "X-SMTPAPI" FIELD_NAMES = %i[ email_provider environment category mailer_class mailer_method mailer_args purchase_id charge_id workflow_ids post_id follower_id affiliate_id ].freeze FIELD_EMAIL_PROVIDER = :email_provider FIELD_ENVIRONMENT = :environment FIELD_CATEGORY = :category FIELD_MAILER_CLASS = :mailer_class FIELD_MAILER_METHOD = :mailer_method FIELD_MAILER_ARGS = :mailer_args FIELD_PURCHASE_ID = :purchase_id FIELD_CHARGE_ID = :charge_id FIELD_WORKFLOW_IDS = :workflow_ids FIELD_POST_ID = :post_id FIELD_FOLLOWER_ID = :follower_id FIELD_AFFILIATE_ID = :affiliate_id def build_headers(mailer_class:, mailer_method:, mailer_args:, email_provider:) MailerInfo::HeaderBuilder.perform(mailer_class:, mailer_method:, mailer_args:, email_provider:) end GUMROAD_HEADER_PREFIX = "X-GUM-" def header_name(name) raise ArgumentError, "Invalid header field: #{name}" unless FIELD_NAMES.include?(name) GUMROAD_HEADER_PREFIX + name.to_s.split("_").map(&:capitalize).join("-") end def encrypt(value) MailerInfo::Encryption.encrypt(value) end def decrypt(encrypted_value) MailerInfo::Encryption.decrypt(encrypted_value) end # Sample Resend headers: # [ # { # "name": "X-Gum-Environment", # "value": "v1:T4Atudv1nP58+gprjqKMJA==:fGNbbVO69Zrw7kSnULg2mw==" # }, # { # "name": "X-Gum-Mailer-Class", # "value": "v1:4/KqqxSld7KZg35TizeOzg==:roev9VWcJg5De5uJ95tWbQ==" # } # ] def parse_resend_webhook_header(headers_json, header_name) header_field_name = header_name(header_name) header_value = headers_json &.find { _1["name"].downcase == header_field_name.downcase } &.dig("value") decrypt(header_value) end def random_email_provider(domain) MailerInfo::Router.determine_email_provider(domain) end def random_delivery_method_options(domain:, seller: nil) MailerInfo::DeliveryMethod.options(domain:, email_provider: random_email_provider(domain), seller:) end def default_delivery_method_options(domain:) MailerInfo::DeliveryMethod.options(domain:, email_provider: EMAIL_PROVIDER_SENDGRID) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase.rb
app/models/purchase.rb
# frozen_string_literal: true class Purchase < ApplicationRecord has_paper_trail include Rails.application.routes.url_helpers include ActionView::Helpers::DateHelper, CurrencyHelper, ProductsHelper, Mongoable, PurchaseErrorCode, ExternalId, JsonData, TimestampScopes, Accounting, Blockable, CardCountrySource, Targeting, Refundable, Reviews, PingNotification, Searchable, Risk, CreatorAnalyticsCallbacks, FlagShihTzu, AfterCommitEverywhere, CompletionHandler, Integrations, ChargeEventsHandler, AudienceMember, Reportable, Recommended, CustomFields, Charge::Disputable, Charge::Chargeable, Charge::Refundable, DisputeWinCredits, Order::Orderable, Paypal, Receipt, UnusedColumns, SecureExternalId, ChargeProcessable extend PreorderHelper extend ProductsHelper unused_columns :custom_fields # If a sku-enabled product has no skus (i.e. the product has no variants), then the sku id of the purchase will be "pid_#{external_product_id}". SKU_ID_PREFIX_FOR_PRODUCT_WITH_NO_SKUS = "pid_" # Gumroad's fees per transaction GUMROAD_FEE_PER_THOUSAND = 85 GUMROAD_DISCOVER_EXTRA_FEE_PER_THOUSAND = 100 GUMROAD_NON_PRO_FEE_PERCENTAGE = 60 GUMROAD_FLAT_FEE_PER_THOUSAND = 100 GUMROAD_DISCOVER_FEE_PER_THOUSAND = 300 GUMROAD_FIXED_FEE_CENTS = 50 PROCESSOR_FEE_PER_THOUSAND = 29 PROCESSOR_FIXED_FEE_CENTS = 30 MAX_PRICE_RANGE = (-2_147_483_647..2_147_483_647) CHARGED_SUCCESS_STATES = %w[preorder_authorization_successful successful] NON_GIFT_SUCCESS_STATES = CHARGED_SUCCESS_STATES.dup.push("not_charged") ALL_SUCCESS_STATES = NON_GIFT_SUCCESS_STATES.dup.push("gift_receiver_purchase_successful") ALL_SUCCESS_STATES_INCLUDING_TEST = ALL_SUCCESS_STATES.dup.push("test_successful") ALL_SUCCESS_STATES_EXCEPT_PREORDER_AUTH = ALL_SUCCESS_STATES.dup - ["preorder_authorization_successful"] ALL_SUCCESS_STATES_EXCEPT_PREORDER_AUTH_AND_GIFT = ALL_SUCCESS_STATES_EXCEPT_PREORDER_AUTH.dup - ["gift_receiver_purchase_successful"] COUNTS_REVIEWS_STATES = %w[successful gift_receiver_purchase_successful not_charged] ACTIVE_SALES_SEARCH_OPTIONS = { state: NON_GIFT_SUCCESS_STATES, exclude_refunded_except_subscriptions: true, exclude_unreversed_chargedback: true, exclude_non_original_subscription_purchases: true, exclude_deactivated_subscriptions: true, exclude_bundle_product_purchases: true, exclude_commission_completion_purchases: true, }.freeze # State "preorder_concluded_successfully" and filter `exclude_non_successful_preorder_authorizations` need to be included # to be able to return preorders from the time they were created instead of when they were concluded. # https://github.com/gumroad/web/pull/17699 CHARGED_SALES_SEARCH_OPTIONS = { state: CHARGED_SUCCESS_STATES + ["preorder_concluded_successfully"], exclude_giftees: true, exclude_refunded: true, exclude_unreversed_chargedback: true, exclude_non_successful_preorder_authorizations: true, exclude_bundle_product_purchases: true, exclude_commission_completion_purchases: true, }.freeze attr_json_data_accessor :locale, default: -> { "en" } attr_json_data_accessor :card_country_source attr_json_data_accessor :chargeback_reason attr_json_data_accessor :perceived_price_cents attr_json_data_accessor :recommender_model_name attr_json_data_accessor :custom_fee_per_thousand alias_attribute :total_transaction_cents_usd, :total_transaction_cents belongs_to :link, optional: true has_one :url_redirect has_one :gift_given, class_name: "Gift", foreign_key: :gifter_purchase_id has_one :gift_received, class_name: "Gift", foreign_key: :giftee_purchase_id has_one :license has_one :shipment belongs_to :purchaser, class_name: "User", optional: true belongs_to :seller, class_name: "User", optional: true belongs_to :credit_card, optional: true belongs_to :subscription, optional: true belongs_to :price, optional: true has_many :events has_many :refunds has_many :disputes belongs_to :offer_code, optional: true belongs_to :preorder, optional: true belongs_to :zip_tax_rate, optional: true belongs_to :merchant_account, optional: true has_many :comments, as: :commentable has_many :media_locations has_one :processor_payment_intent has_one :commission_as_deposit, class_name: "Commission", foreign_key: :deposit_purchase_id has_one :commission_as_completion, class_name: "Commission", foreign_key: :completion_purchase_id has_one :utm_link_driven_sale has_one :utm_link, through: :utm_link_driven_sale has_many :balance_transactions belongs_to :purchase_success_balance, class_name: "Balance", optional: true belongs_to :purchase_chargeback_balance, class_name: "Balance", optional: true belongs_to :purchase_refund_balance, class_name: "Balance", optional: true has_and_belongs_to_many :variant_attributes, class_name: "BaseVariant" has_many :base_variants_purchases, class_name: "BaseVariantsPurchase" # used for preloading variant ids without having to also query their records has_one :call, autosave: true has_one :affiliate_credit has_many :affiliate_partial_refunds belongs_to :affiliate, optional: true has_one :purchase_sales_tax_info has_one :purchase_taxjar_info has_one :recommended_purchase_info, dependent: :destroy has_one :purchase_wallet_type has_one :purchase_offer_code_discount has_one :purchasing_power_parity_info, dependent: :destroy has_one :upsell_purchase, dependent: :destroy has_one :purchase_refund_policy, dependent: :destroy has_one :order_purchase, dependent: :destroy has_one :order, through: :order_purchase, dependent: :destroy has_one :charge_purchase, dependent: :destroy has_one :charge, through: :charge_purchase, dependent: :destroy has_one :early_fraud_warning, dependent: :destroy has_one :tip, dependent: :destroy has_many :purchase_integrations has_many :live_purchase_integrations, -> { alive }, class_name: "PurchaseIntegration" has_many :active_integrations, through: :live_purchase_integrations, source: :integration has_many :consumption_events has_many :product_purchase_records, class_name: "BundleProductPurchase", foreign_key: :bundle_purchase_id has_many :product_purchases, through: :product_purchase_records has_one :bundle_purchase_record, class_name: "BundleProductPurchase", foreign_key: :product_purchase_id has_one :bundle_purchase, through: :bundle_purchase_record, source: :bundle_purchase has_one :call # Normal purchase state transitions: # # in_progress β†’ successful # ↓ # failed # # # Test purchases: # # in_progress β†’ test_successful # # β†’ test_preorder_successful # # # Preorders: # # in_progress β†’ preorder_authorization_successful β†’ preorder_concluded_successfully # ↓ ↓ # preorder_authorization_failed preorder_concluded_unsuccessfully # # There are two purchases associated with each preorder: one at the time of the preorder # authorization that goes through the above state machine. The second for when the # preorder is released and the card is actually charged once the product is released. # The second purchase goes through the normal purchase state machine and transition # to successful it moves the preorder purchase to 'preorder_concluded_successfully'. # # Giftee purchases: # # in_progress β†’ gift_receiver_purchase_successful # ↓ # gift_receiver_purchase_failed # # Gift purchases use a normal purchase and a giftee purchase: the gifter's # purchase triggers the creation of the giftee purchase, which always has # price=0. # The gifter will receive a receipt, but the seller's emails and the webhooks # will all use the giftee's email. # # Subscription purchases: # # (a) Initial purchase of a product without a free trial: Follows the normal purchase # state transitions. # # (b) Initial purchase of a product with free trials enabled: # # in_progress β†’ not_charged # ↓ # failed # # (c) Upgrading or downgrading a subscription: Generates a new "original" subscription # purchase with a "not_charged" state # # in_progress β†’ not_charged # ↓ # failed state_machine :purchase_state, initial: :in_progress do before_transition in_progress: any, do: :zip_code_from_geoip after_transition any => %i[successful not_charged gift_receiver_purchase_successful test_successful], :do => :create_artifacts_and_send_receipt!, unless: lambda { |purchase| purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged], :do => :schedule_subscription_jobs, if: lambda { |purchase| purchase.link.is_recurring_billing && !purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged gift_receiver_purchase_successful], :do => :schedule_rental_expiration_reminder_emails, if: lambda { |purchase| purchase.is_rental } after_transition any => %i[successful not_charged gift_receiver_purchase_successful], :do => :schedule_workflow_jobs, if: lambda { |purchase| purchase.seller.has_workflows? && !purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged test_successful], :do => :notify_seller!, unless: lambda { |purchase| purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged], do: :notify_affiliate!, if: lambda { |purchase| purchase.affiliate.present? && !purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged], do: :create_product_affiliate, if: lambda { |purchase| purchase.affiliate.present? && purchase.affiliate.global? && !purchase.not_charged_and_not_free_trial? } after_transition any => :failed, :do => :ban_fraudulent_buyer_browser_guid! after_transition any => :failed, :do => :ban_card_testers! after_transition any => :failed, :do => :block_purchases_on_product!, if: lambda { |purchase| purchase.price_cents.nonzero? && !purchase.is_recurring_subscription_charge } after_transition any => :failed, :do => :pause_payouts_for_seller_based_on_recent_failures!, if: lambda { |purchase| purchase.price_cents.nonzero? } after_transition any => :failed, :do => :ban_buyer_on_fraud_related_error_code! after_transition any => :failed, :do => :suspend_buyer_on_fraudulent_card_decline! after_transition any => :failed, :do => :send_failure_email after_transition any => %i[failed successful not_charged], :do => :check_purchase_heuristics after_transition any => %i[failed successful not_charged], :do => :score_product after_transition any => %i[preorder_authorization_successful successful not_charged preorder_concluded_unsuccessfully], :do => :queue_product_cache_invalidation after_transition any => %i[successful preorder_authorization_successful], :do => :touch_variants_if_limited_quantity, unless: lambda { |purchase| purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged preorder_authorization_successful], :do => :update_product_search_index!, unless: lambda { |purchase| purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful not_charged], do: :delete_failed_purchases_count after_transition any => %i[successful gift_receiver_purchase_successful not_charged], do: :transcode_product_videos, if: lambda { |purchase| purchase.link.transcode_videos_on_purchase? && !purchase.not_charged_and_not_free_trial? } after_transition any => %i[successful gift_receiver_purchase_successful preorder_authorization_successful test_successful test_preorder_successful not_charged], :do => :send_notification_webhook, unless: lambda { |purchase| purchase.not_charged_and_not_free_trial? } after_transition any => :successful, :do => :block_fraudulent_free_purchases! after_transition any => any, :do => :log_transition after_transition any => [:successful, :not_charged, :gift_receiver_purchase_successful], :do => :trigger_iffy_moderation, if: lambda { |purchase| purchase.price_cents > 0 && !purchase.link.moderated_by_iffy } # normal purchase transitions: event :mark_successful do transition %i[in_progress] => :successful, if: ->(purchase) { !purchase.is_preorder_authorization && !purchase.is_gift_receiver_purchase } end event :mark_failed do transition in_progress: :failed, if: ->(purchase) { !purchase.is_preorder_authorization } end # giftee purchase transitions: event :mark_gift_receiver_purchase_successful do transition in_progress: :gift_receiver_purchase_successful, if: ->(purchase) { purchase.is_gift_receiver_purchase } end event :mark_gift_receiver_purchase_failed do transition in_progress: :gift_receiver_purchase_failed, if: ->(purchase) { purchase.is_gift_receiver_purchase } end # preorder authorization transitions: event :mark_preorder_authorization_successful do transition in_progress: :preorder_authorization_successful, if: ->(purchase) { purchase.is_preorder_authorization } end event :mark_preorder_authorization_failed do transition in_progress: :preorder_authorization_failed, if: ->(purchase) { purchase.is_preorder_authorization } end event :mark_preorder_concluded_successfully do transition preorder_authorization_successful: :preorder_concluded_successfully end event :mark_preorder_concluded_unsuccessfully do transition preorder_authorization_successful: :preorder_concluded_unsuccessfully end event :mark_test_successful do transition in_progress: :test_successful end event :mark_test_preorder_successful do transition in_progress: :test_preorder_successful end state :successful do validate { |purchase| purchase.send(:financial_transaction_validation) } # Read http://rdoc.info/github/pluginaweek/state_machine/master/StateMachine/Integrations/ActiveRecord # section "Validations" for why this validator is called in this way. end # updating subscription transitions. `not_charged` state is used when upgrading # subscriptions. Newly-created "original subscription purchases" are never charged, # but are simply used as a template for charges going forward. event :mark_not_charged do transition any => :not_charged end end before_validation :downcase_email, if: :email_changed? validate :must_have_valid_email validate :not_double_charged, on: :create validate :seller_is_link_user validate :free_trial_purchase_set_correctly, on: :create validate :gift_purchases_cannot_be_on_installment_plans %w[seller price_cents total_transaction_cents fee_cents].each do |f| validates f.to_sym, presence: true end # address exists for products that require shipping and not recurring purchase and preorders that are not physical # this ensures preorders that require shipping at a later date will pass this validation %w[full_name street_address country state zip_code city].each do |f| validates f.to_sym, presence: true, on: :create, if: -> { link.is_physical || (link.require_shipping? && !is_recurring_subscription_charge && !is_preorder_charge?) } validates f.to_sym, presence: true, on: :update, if: -> { is_updated_original_subscription_purchase && (link.is_physical || link.require_shipping?) && !is_recurring_subscription_charge && !is_preorder_charge? } end validates :call, presence: true, if: -> { link.native_type == Link::NATIVE_TYPE_CALL } validates_inclusion_of :recommender_model_name, in: RecommendedProductsService::MODELS, allow_nil: true validates :purchaser, presence: true, if: -> { is_gift_receiver_purchase && gift&.is_recipient_hidden? } validates :custom_fee_per_thousand, allow_nil: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 } # before_create instead of validate since we want to persist the purchases that fail these. before_create :product_is_sellable before_create :product_is_not_blocked before_create :validate_purchase_type before_create :variants_available before_create :variants_satisfied before_create :sold_out before_create :validate_offer_code before_create :price_not_too_low before_create :price_not_too_high before_create :perceived_price_cents_matches_price_cents before_create :validate_subscription before_create :validate_shipping before_create :validate_quantity before_create :assign_is_multiseat_license before_create :check_for_fraud before_save :assign_default_rental_expired before_save :to_mongo before_save :truncate_referrer after_commit :attach_credit_card_to_purchaser, on: :update, if: -> (purchase) { Feature.active?(:attach_credit_card_to_purchaser) && purchase.previous_changes[:purchaser_id].present? && purchase.purchaser && purchase.subscription } after_commit :enqueue_update_sales_related_products_infos_job, if: -> (purchase) { purchase.purchase_state_previously_changed? && purchase.purchase_state == "successful" } # Entities that store the product price, tax information and transaction price # price_cents - Price cents is the cost of the product as seen by the seller, including Gumroad fees. # tax_cents - Tax that the seller is responsible for. This amount is remitted to the seller. # The tax amount(tax_cents) is either intrinsic or added on to price_cents. # This is controlled by the flag was_tax_excluded_from_price and done at the time of processing (see #process!) # gumroad_tax_cents - Tax that Gumroad is responsible for. This amount is NOT remitted to the seller. # Eg. VAT an EU buyer is charged. # shipping_cents - Shipping that is calculated. # total_transaction_cents - Total transaction cents is the amount the buyer is charged # This amount includes charges that are not within the scope of the seller - like VAT # Is equivalent to price_cents + gumroad_tax_cents has_flags 1 => :is_additional_contribution, 2 => :is_refund_chargeback_fee_waived, # Only used for refunds, as chargeback fees are always waived as of now 3 => :is_original_subscription_purchase, 4 => :is_preorder_authorization, 5 => :is_multi_buy, 6 => :is_gift_receiver_purchase, 7 => :is_gift_sender_purchase, 8 => :DEPRECATED_credit_card_zipcode_required, 9 => :was_product_recommended, 10 => :chargeback_reversed, 11 => :was_zipcode_check_performed, 12 => :is_upgrade_purchase, 13 => :was_purchase_taxable, 14 => :was_tax_excluded_from_price, 15 => :is_rental, # Before we introduced the flat 10% fee `was_discover_fee_charged` was set if the discover fee was charged. # Now it is set if the improved product placement fee is charged. 16 => :was_discover_fee_charged, 17 => :is_archived, 18 => :is_archived_original_subscription_purchase, 19 => :is_free_trial_purchase, 20 => :is_deleted_by_buyer, 21 => :is_buyer_blocked_by_admin, 22 => :is_multiseat_license, 23 => :should_exclude_product_review, 24 => :is_purchasing_power_parity_discounted, 25 => :is_access_revoked, 26 => :is_bundle_purchase, 27 => :is_bundle_product_purchase, 28 => :is_part_of_combined_charge, 29 => :is_commission_deposit_purchase, 30 => :is_commission_completion_purchase, 31 => :is_installment_payment, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false attr_accessor :chargeable, :card_data_handling_error, :save_card, :price_range, :friend_actions, :discount_code, :url_parameters, :purchaser_plugins, :is_automatic_charge, :sales_tax_country_code_election, :business_vat_id, :save_shipping_address, :flow_of_funds, :prorated_discount_price_cents, :original_variant_attributes, :original_price, :is_updated_original_subscription_purchase, :is_applying_plan_change, :setup_intent, :charge_intent, :setup_future_charges, :skip_preparing_for_charge, :installment_plan delegate :email, :name, to: :seller, prefix: "seller" delegate :name, to: :link, prefix: "link", allow_nil: true delegate :display_product_reviews?, to: :link scope :by_email, ->(email) { where(email:) } scope :with_stripe_fingerprint, -> { where.not(stripe_fingerprint: nil) } scope :successful, -> { where(purchase_state: "successful") } scope :test_successful, -> { where(purchase_state: "test_successful") } scope :in_progress, -> { where(purchase_state: "in_progress") } scope :in_progress_or_successful_including_test, -> { where(purchase_state: %w(in_progress successful test_successful)) } scope :not_in_progress, -> { where.not(purchase_state: "in_progress") } scope :not_successful, -> { without_purchase_state(:successful) } scope :successful_gift_or_nongift, -> { where(purchase_state: ["successful", "gift_receiver_purchase_successful"]) } scope :failed, -> { where(purchase_state: "failed") } scope :preorder_authorization_successful, -> { where(purchase_state: "preorder_authorization_successful") } scope :preorder_authorization_successful_or_gift, -> { where(purchase_state: ["preorder_authorization_successful", "gift_receiver_purchase_successful"]) } scope :successful_or_preorder_authorization_successful, -> { where(purchase_state: Purchase::CHARGED_SUCCESS_STATES) } scope :preorder_authorization_failed, -> { where(purchase_state: "preorder_authorization_failed") } scope :not_charged, -> { where(purchase_state: "not_charged") } scope :all_success_states, -> { where(purchase_state: Purchase::ALL_SUCCESS_STATES) } scope :all_success_states_including_test, -> { where(purchase_state: Purchase::ALL_SUCCESS_STATES_INCLUDING_TEST) } scope :all_success_states_except_preorder_auth_and_gift, -> { where(purchase_state: Purchase::ALL_SUCCESS_STATES_EXCEPT_PREORDER_AUTH_AND_GIFT) } scope :exclude_not_charged_except_free_trial, -> { where("purchases.purchase_state != 'not_charged' OR purchases.flags & ? != 0", Purchase.flag_mapping["flags"][:is_free_trial_purchase]) } scope :stripe_failed, -> { failed.where("purchases.stripe_fingerprint IS NOT NULL AND purchases.stripe_fingerprint != ''") } scope :non_free, -> { where("purchases.price_cents != 0") } scope :successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback, lambda { where(purchase_state: %w[successful preorder_authorization_successful gift_receiver_purchase_successful]). not_fully_refunded. not_chargedback_or_chargedback_reversed. not_is_gift_receiver_purchase } scope :paid, -> { successful.where("purchases.price_cents > 0").where("stripe_refunded is null OR stripe_refunded = 0") } scope :not_fully_refunded, -> { where("purchases.stripe_refunded IS NULL OR purchases.stripe_refunded = 0") } # always include subscription purchase regardless if refunded or not to show up in library and customers tab: scope :not_refunded_except_subscriptions, lambda { where("(purchases.subscription_id IS NULL AND (purchases.stripe_refunded IS NULL OR purchases.stripe_refunded = 0)) OR " \ "purchases.subscription_id IS NOT NULL") } scope :chargedback, -> { successful.where("purchases.chargeback_date IS NOT NULL") } scope :not_chargedback, -> { where("purchases.chargeback_date IS NULL") } scope :not_chargedback_or_chargedback_reversed, lambda { where("purchases.chargeback_date IS NULL OR " \ "(purchases.chargeback_date IS NOT NULL AND purchases.flags & ? != 0)", Purchase.flag_mapping["flags"][:chargeback_reversed]) } scope :not_additional_contribution, -> { where("purchases.flags IS NULL OR purchases.flags & ? = 0", Purchase.flag_mapping["flags"][:is_additional_contribution]) } scope :for_products, ->(products) { where(link_id: products) if products.present? } scope :not_subscription_or_original_purchase, -> { where("purchases.subscription_id IS NULL OR purchases.flags & ? = ?", Purchase.flag_mapping["flags"][:is_original_subscription_purchase], Purchase.flag_mapping["flags"][:is_original_subscription_purchase]) } # TODO: since Memberships, `not_recurring_charge` & `recurring_charge` are not an accurate names for what the scopes filter, and they should be renamed. scope :not_recurring_charge, lambda { not_subscription_or_original_purchase } scope :recurring_charge, -> { where("purchases.subscription_id IS NOT NULL AND purchases.flags & ? = 0", Purchase.flag_mapping["flags"][:is_original_subscription_purchase]) } scope :has_active_subscription, lambda { without_purchase_state(:test_successful).joins("INNER JOIN subscriptions ON subscriptions.id = purchases.subscription_id") .where("subscriptions.failed_at IS NULL AND subscriptions.ended_at IS NULL AND (subscriptions.cancelled_at IS NULL OR subscriptions.cancelled_at > ?)", Time.current) } scope :no_or_active_subscription, lambda { joins("LEFT OUTER JOIN subscriptions ON subscriptions.id = purchases.subscription_id") .where("subscriptions.deactivated_at IS NULL") } scope :inactive_subscription, lambda { joins("LEFT OUTER JOIN subscriptions ON subscriptions.id = purchases.subscription_id") .where("subscriptions.deactivated_at IS NOT NULL") } scope :can_access_content, lambda { joins(:link) .joins("LEFT OUTER JOIN subscriptions ON subscriptions.id = purchases.subscription_id") .where("subscriptions.deactivated_at IS NULL OR links.flags & ? = 0", Link.flag_mapping["flags"][:block_access_after_membership_cancellation]) } scope :counts_towards_inventory, lambda { where(purchase_state: ["preorder_authorization_successful", "in_progress", "successful", "not_charged"]) .left_joins(:subscription) .not_subscription_or_original_purchase .not_additional_contribution .not_is_archived_original_subscription_purchase .where(subscription: { deactivated_at: nil }) } scope :counts_towards_offer_code_uses, lambda { where(purchase_state: NON_GIFT_SUCCESS_STATES) .not_recurring_charge .not_is_archived_original_subscription_purchase } scope :counts_towards_volume, lambda { successful .not_fully_refunded .not_chargedback_or_chargedback_reversed } scope :created_after, ->(start_at) { where("purchases.created_at > ?", start_at) if start_at.present? } scope :created_before, ->(end_at) { where("purchases.created_at < ?", end_at) if end_at.present? } scope :with_credit_card_id, -> { where.not(credit_card_id: nil) } scope :not_rental_expired, -> { where(rental_expired: [nil, false]) } scope :rentals_to_expire, -> { time_now = Time.current where(rental_expired: false) .joins(:url_redirect) .where( "url_redirects.created_at < ? OR url_redirects.rental_first_viewed_at < ?", time_now - UrlRedirect::TIME_TO_WATCH_RENTED_PRODUCT_AFTER_PURCHASE, time_now - UrlRedirect::TIME_TO_WATCH_RENTED_PRODUCT_AFTER_FIRST_PLAY ) } scope :for_mobile_listing, -> { all_success_states .not_is_deleted_by_buyer .not_is_additional_contribution .not_recurring_charge .not_is_gift_sender_purchase .not_refunded_except_subscriptions .not_chargedback_or_chargedback_reversed .not_is_archived_original_subscription_purchase .not_rental_expired .order(:id) .includes(:preorder, :purchaser, :seller, :subscription, url_redirect: { purchase: { link: [:user, :thumbnail] } }) } scope :for_library, lambda { all_success_states .not_is_additional_contribution .not_recurring_charge .not_is_gift_sender_purchase .not_refunded_except_subscriptions .not_chargedback_or_chargedback_reversed .not_is_archived_original_subscription_purchase .not_is_access_revoked } scope :for_sales_api, -> { all_success_states_except_preorder_auth_and_gift.exclude_not_charged_except_free_trial } scope :for_sales_api_ordered_by_date, ->(subquery_details) { subqueries = [successful, not_charged.is_free_trial_purchase] subqueries_sqls = subqueries.map do |subquery| "(" + subquery_details.call(subquery).to_sql + ")" end from("(" + subqueries_sqls.join(" UNION ") + ") AS #{table_name}") } scope :for_displaying_installments, ->(email:) { all_success_states_including_test .can_access_content .not_fully_refunded .not_chargedback_or_chargedback_reversed .not_is_gift_sender_purchase .where(email:) } scope :for_visible_posts, ->(purchaser_id:) { all_success_states .not_fully_refunded .not_chargedback_or_chargedback_reversed .where(purchaser_id:) } scope :for_admin_listing, -> { where(purchase_state: %w[preorder_authorization_successful preorder_concluded_unsuccessfully successful failed not_charged]) .exclude_not_charged_except_free_trial .order(created_at: :desc, id: :desc) } scope :for_affiliate_user, ->(user) { where(affiliate: user.direct_affiliate_accounts) } scope :stripe, -> { where(charge_processor_id: StripeChargeProcessor.charge_processor_id) } scope :not_access_revoked_or_is_paid, -> { not_is_access_revoked.or(paid) } # Public: Get a JSON response representing a Purchase object # # version - Supported versions # 1 - initial version # 2 - `price` is no longer `formatted_display_price`, and is now `price_cents`. # - `link_id` has been renamed to `product_id`, and now shows the `external_id`. # - `link_name` has been renamed to `product_name` # - `custom_fields` is no longer an array containing strings `"field: value"` and instead is now a proper hash. # - `variants` is no longer an string containing the list of variants `variant: selection, variant2: selection2` and instead is now a proper hash. # default - version 1 # - changes made for later versions that do not change fields in previous versions may be included # # Returns a JSON representation of the Purchase def as_json(options = {}) version = options[:version] || 1 return as_json_for_admin_review if options[:admin_review] pundit_user = options[:pundit_user] json = { id: ObfuscateIds.encrypt(id), email: purchaser_email_or_email, seller_id: ObfuscateIds.encrypt(seller.id), timestamp: "#{time_ago_in_words(created_at)} ago", daystamp: created_at.in_time_zone(seller.timezone).to_fs(:long_formatted_datetime), created_at:, link_name: (link.name if version == 1), product_name: link.name, product_has_variants: (link.association_cached?(:variant_categories_alive) ? !link.variant_categories_alive.empty? : link.variant_categories_alive.exists?), price: version == 1 ? formatted_display_price : price_cents, gumroad_fee: fee_cents, is_bundle_purchase:, is_bundle_product_purchase:, } return json.merge!(additional_fields_for_creator_app_api) if options[:creator_app_api] if options[:include_variant_details] variants_for_json = variant_details_hash elsif version == 1 variants_for_json = variants_list else variants_for_json = variant_names_hash end json.merge!( subscription_duration:, formatted_display_price:, transaction_url_for_seller:, formatted_total_price:, currency_symbol: symbol_for(displayed_price_currency_type), amount_refundable_in_currency:, link_id: (link.unique_permalink if version == 1), product_id: link.external_id, product_permalink: link.unique_permalink, refunded: stripe_refunded, partially_refunded: stripe_partially_refunded,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/payment.rb
app/models/payment.rb
# frozen_string_literal: true class Payment < ApplicationRecord include ExternalId, Payment::Stats, JsonData, FlagShihTzu, TimestampScopes, Payment::FailureReason CREATING = "creating" PROCESSING = "processing" UNCLAIMED = "unclaimed" COMPLETED = "completed" FAILED = "failed" CANCELLED = "cancelled" REVERSED = "reversed" RETURNED = "returned" NON_TERMINAL_STATES = [CREATING, PROCESSING, UNCLAIMED, COMPLETED].freeze belongs_to :user, optional: true belongs_to :bank_account, optional: true has_and_belongs_to_many :balances, join_table: "payments_balances" has_one :credit, foreign_key: :returned_payment_id has_flags 1 => :was_created_in_split_mode, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false attr_json_data_accessor :split_payments_info attr_json_data_accessor :arrival_date attr_json_data_accessor :payout_type attr_json_data_accessor :gumroad_fee_cents # Payment state transitions: # # creating # ↓ # processing β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ ↓ # ↓ ↓ ↓ # ↓ β†’ β†’ β†’ β†’ β†’ failed cancelled ↓ # ↓ ↑ β†— ↓ # ↓ β†’ β†’ β†’ β†’ unclaimed β†’ β†’ β†’ reversed ← ←↓ # ↓ ↓ β†˜οΈŽ ↓ # ↓ β†’ β†’ β†’ β†’ completed β†’ β†’ β†’ returned ← ←↓ # state_machine(:state, initial: :creating) do event :mark_processing do transition creating: :processing end event :mark_cancelled do transition processing: :cancelled transition unclaimed: :cancelled, if: ->(payment) { payment.processor == PayoutProcessorType::PAYPAL } end event :mark_completed do transition %i[processing unclaimed] => :completed end event :mark_failed do transition %i[creating processing] => :failed end event :mark_reversed do transition %i[processing unclaimed] => :reversed end event :mark_returned do transition %i[processing unclaimed] => :returned transition completed: :returned, if: ->(payment) { payment.processor != PayoutProcessorType::PAYPAL } end event :mark_unclaimed do transition processing: :unclaimed, if: ->(payment) { payment.processor == PayoutProcessorType::PAYPAL } end before_transition any => :failed, do: ->(payment, transition) { payment.failure_reason = transition.args.first } after_transition %i[creating processing] => %i[cancelled failed], do: :mark_balances_as_unpaid after_transition processing: :failed, do: :send_cannot_pay_email, if: ->(payment) { payment.failure_reason == FailureReason::CANNOT_PAY } after_transition processing: :failed, do: :send_debit_card_limit_email, if: ->(payment) { payment.failure_reason == FailureReason::DEBIT_CARD_LIMIT } after_transition processing: :failed, do: :add_payment_failure_reason_comment after_transition %i[processing unclaimed] => :completed, do: :mark_balances_as_paid after_transition any => :completed, do: :generate_default_abandoned_cart_workflow after_transition unclaimed: %i[cancelled reversed returned failed], do: :mark_balances_as_unpaid after_transition completed: :returned, do: :mark_balances_as_unpaid after_transition completed: :returned, do: :send_deposit_returned_email after_transition processing: %i[completed unclaimed], do: :send_deposit_email after_transition any => any, :do => :log_transition state any do validates_presence_of :processor end state any - %i[creating processing] do validates_presence_of :correlation_id, if: proc { |p| p.processor == PayoutProcessorType::PAYPAL } end state any - %i[creating processing cancelled failed] do validates :stripe_transfer_id, :stripe_connect_account_id, presence: true, if: proc { |p| p.processor == PayoutProcessorType::STRIPE } end state :completed do validates_presence_of :txn_id, if: proc { |p| p.processor == PayoutProcessorType::PAYPAL } validates_presence_of :amount_cents_in_local_currency, if: proc { |p| p.processor == PayoutProcessorType::ZENGIN } validates_presence_of :processor_fee_cents end end validate :split_payment_validation scope :processed_by, ->(processor) { where(processor:) } scope :processing, -> { where(state: "processing") } scope :completed, -> { where(state: "completed") } scope :completed_or_processing, -> { where("state = 'completed' or state = 'processing'") } scope :failed, -> { where(state: "failed").order(id: :desc) } scope :failed_cannot_pay, -> { failed.where(failure_reason: "cannot_pay") } scope :displayable, -> { where("created_at >= ?", PayoutsHelper::OLDEST_DISPLAYABLE_PAYOUT_PERIOD_END_DATE) } def mark(state) send("mark_#{state}") end def mark!(state) send("mark_#{state}!") end def displayed_amount Money.new(amount_cents, currency).format(no_cents_if_whole: true, symbol: true, with_currency: currency != Currency::USD) end def credits Credit.where(balance_id: balances) end def credit_amount_cents credits.where(fee_retention_refund_id: nil).sum("amount_cents") end def send_deposit_email CustomerLowPriorityMailer.deposit(id).deliver_later(queue: "low") end def send_deposit_returned_email ContactingCreatorMailer.payment_returned(id).deliver_later(queue: "critical") end def send_cannot_pay_email return if user.payout_date_of_last_payment_failure_email.present? && Date.parse(user.payout_date_of_last_payment_failure_email) >= payout_period_end_date ContactingCreatorMailer.cannot_pay(id).deliver_later(queue: "critical") user.payout_date_of_last_payment_failure_email = payout_period_end_date user.save! end def send_payout_failure_email # This would already be done from callback/ We dont't to clean that up rn return if failure_reason === FailureReason::CANNOT_PAY ContactingCreatorMailer.cannot_pay(id).deliver_later(queue: "critical") user.payout_date_of_last_payment_failure_email = payout_period_end_date user.save! end def send_debit_card_limit_email ContactingCreatorMailer.debit_card_limit_reached(id).deliver_later(queue: "critical") end def humanized_failure_reason if processor == PayoutProcessorType::PAYPAL failure_reason.present? ? "#{failure_reason}: #{PAYPAL_MASS_PAY[failure_reason]}" : nil else failure_reason end end def reversed_by?(reversing_payout_id) processor_reversing_payout_id.present? && processor_reversing_payout_id == reversing_payout_id end def sync_with_payout_processor return unless NON_TERMINAL_STATES.include?(state) sync_with_paypal if processor == PayoutProcessorType::PAYPAL end def as_json(options = {}) json = { id: external_id, amount: format("%.2f", (amount_cents || 0) / 100.0), currency: currency, status: state, created_at: created_at, processed_at: state == COMPLETED ? updated_at : nil, payment_processor: processor, bank_account_visual: bank_account&.account_number_visual, paypal_email: payment_address } if options[:include_sales] json[:sales] = successful_sales.map(&:external_id) json[:refunded_sales] = refunded_sales.map(&:external_id) json[:disputed_sales] = disputed_sales.map(&:external_id) end json end def successful_sales Purchase.where(purchase_success_balance_id: balance_ids) .includes(:link) .distinct .order(created_at: :desc, id: :desc) end def refunded_sales Purchase.where(purchase_refund_balance_id: balance_ids) .includes(:link) .distinct .order(created_at: :desc, id: :desc) end def disputed_sales Purchase.where(purchase_chargeback_balance_id: balance_ids) .includes(:link) .distinct .order(created_at: :desc, id: :desc) end private def balance_ids @balance_ids ||= balances.pluck(:id) end def mark_balances_as_paid balances.each(&:mark_paid!) end def mark_balances_as_unpaid balances.each(&:mark_unpaid!) end def log_transition logger.info "Payment: payment ID #{id} transitioned to #{state}" end def split_payment_validation return if was_created_in_split_mode && split_payments_info.present? return if !was_created_in_split_mode && split_payments_info.blank? errors.add(:base, "A split payment needs to have the was_created_in_split_mode flag set and needs to have split_payments_info") end def sync_with_paypal return unless processor == PayoutProcessorType::PAYPAL # For split mode payouts we only sync if we have the txn_ids of individual split parts, # and do not look up or search by PayPal email address. # As these are large payouts (usually over $5k or $10k), they include multiple parts with same amount, # like 3 split parts of $3k each or similar. if was_created_in_split_mode? split_payments_info.each_with_index do |split_payment_info, index| new_payment_state = PaypalPayoutProcessor.get_latest_payment_state_from_paypal(split_payment_info["amount_cents"], split_payment_info["txn_id"], created_at.beginning_of_day - 1.day, split_payment_info["state"]) split_payments_info[index]["state"] = new_payment_state end save! if split_payments_info.map { _1["state"] }.uniq.count > 1 errors.add :base, "Not all split payout parts are in the same state for payout #{id}. This needs to be handled manually." else PaypalPayoutProcessor.update_split_payment_state(self) end else paypal_response = PaypalPayoutProcessor.search_payment_on_paypal(amount_cents:, transaction_id: txn_id, payment_address:, start_date: created_at.beginning_of_day - 1.day, end_date: created_at.end_of_day + 1.day) if paypal_response.nil? transition_to_new_state("failed") else transition_to_new_state(paypal_response[:state], transaction_id: paypal_response[:transaction_id], correlation_id: paypal_response[:correlation_id], paypal_fee: paypal_response[:paypal_fee]) end end rescue => e Rails.logger.error("Error syncing PayPal payout #{id}: #{e.message}") errors.add :base, e.message end def transition_to_new_state(new_state, transaction_id: nil, correlation_id: nil, paypal_fee: nil) return unless NON_TERMINAL_STATES.include?(state) return unless new_state.present? return if new_state == state return unless [FAILED, UNCLAIMED, COMPLETED, CANCELLED, REVERSED, RETURNED].include?(new_state) self.txn_id = transaction_id if transaction_id.present? && self.txn_id.blank? self.correlation_id = correlation_id if correlation_id.present? && self.correlation_id.blank? self.processor_fee_cents = (100 * paypal_fee.to_f).round.abs if paypal_fee.present? && self.processor_fee_cents.blank? # If payout got stuck in 'creating', transition it to 'processing' state # so we can transition it to whatever the new state is on PayPal. mark!(PROCESSING) if state?(CREATING) if new_state == FAILED && transaction_id.blank? mark_failed!("Transaction not found") else mark!(new_state) end end def generate_default_abandoned_cart_workflow DefaultAbandonedCartWorkflowGeneratorService.new(seller: user).generate if user.present? rescue => e Rails.logger.error("Failed to generate default abandoned cart workflow for user #{user.id}: #{e.message}") Bugsnag.notify(e) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_offer_code_discount.rb
app/models/purchase_offer_code_discount.rb
# frozen_string_literal: true class PurchaseOfferCodeDiscount < ApplicationRecord belongs_to :purchase, optional: true belongs_to :offer_code, optional: true validates :purchase, presence: true, uniqueness: true validates :offer_code, presence: true validates :offer_code_amount, presence: true validates :pre_discount_minimum_price_cents, presence: true alias_attribute :duration_in_billing_cycles, :duration_in_months end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/argentina_bank_account.rb
app/models/argentina_bank_account.rb
# frozen_string_literal: true class ArgentinaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "AR" ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{22}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX validate :validate_account_number def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::ARG.alpha2 end def currency Currency::ARS end def account_number_visual "******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_profile_rich_text_section.rb
app/models/seller_profile_rich_text_section.rb
# frozen_string_literal: true class SellerProfileRichTextSection < SellerProfileSection validate :limit_text_size after_save :trigger_iffy_ingest, if: -> { saved_change_to_json_data? || saved_change_to_header? } private def limit_text_size errors.add(:base, "Text is too large") if text.to_json.length > 500_000 end def trigger_iffy_ingest Iffy::Profile::IngestJob.perform_async(seller_id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/cambodia_bank_account.rb
app/models/cambodia_bank_account.rb
# frozen_string_literal: true class CambodiaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "KH" BANK_CODE_FORMAT_REGEX = /^[0-9a-zA-Z]{8,11}$/ ACCOUNT_NUMBER_FORMAT_REGEX = /^[0-9a-zA-Z]{5,15}$/ private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number bank_code.to_s end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::KHM.alpha2 end def currency Currency::KHR end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/rich_content.rb
app/models/rich_content.rb
# frozen_string_literal: true class RichContent < ApplicationRecord include Deletable, ExternalId, Versionable has_paper_trail FILE_EMBED_NODE_TYPE = "fileEmbed" FILE_EMBED_GROUP_NODE_TYPE = "fileEmbedGroup" ORDERED_LIST_NODE_TYPE = "orderedList" BULLET_LIST_NODE_TYPE = "bulletList" LIST_ITEM_NODE_TYPE = "listItem" BLOCKQUOTE_NODE_TYPE = "blockquote" LICENSE_KEY_NODE_TYPE = "licenseKey" POSTS_NODE_TYPE = "posts" SHORT_ANSWER_NODE_TYPE = "shortAnswer" LONG_ANSWER_NODE_TYPE = "longAnswer" FILE_UPLOAD_NODE_TYPE = "fileUpload" MORE_LIKE_THIS_NODE_TYPE = "moreLikeThis" CUSTOM_FIELD_NODE_TYPES = [SHORT_ANSWER_NODE_TYPE, LONG_ANSWER_NODE_TYPE, FILE_UPLOAD_NODE_TYPE].freeze COMMON_CONTAINER_NODE_TYPES = [ORDERED_LIST_NODE_TYPE, BULLET_LIST_NODE_TYPE, LIST_ITEM_NODE_TYPE, BLOCKQUOTE_NODE_TYPE].freeze FILE_EMBED_CONTAINER_NODE_TYPES = [FILE_EMBED_GROUP_NODE_TYPE, *COMMON_CONTAINER_NODE_TYPES].freeze DESCRIPTION_JSON_SCHEMA = { type: "array", items: { "$ref": "#/$defs/content" }, "$defs": { content: { type: "object", properties: { type: { type: "string" }, attrs: { type: "object", additionalProperties: true }, content: { type: "array", items: { "$ref": "#/$defs/content" } }, marks: { type: "array", items: { type: "object", properties: { type: { type: "string" }, attrs: { type: "object", additionalProperties: true } }, required: ["type"], additionalProperties: true } }, text: { type: "string" } }, additionalProperties: true } } } belongs_to :entity, polymorphic: true, optional: true validates :entity, presence: true validates :description, json: { schema: DESCRIPTION_JSON_SCHEMA, message: :invalid } after_update :reset_moderated_by_iffy_flag, if: -> { saved_change_to_description? && alive? } def embedded_product_file_ids_in_order description.flat_map { select_file_embed_ids(_1) }.compact.uniq end def custom_field_nodes select_custom_field_nodes(description).uniq end def has_license_key? contains_license_key_node = ->(node) do node["type"] == LICENSE_KEY_NODE_TYPE || (node["type"].in?(COMMON_CONTAINER_NODE_TYPES) && node["content"].to_s.include?(LICENSE_KEY_NODE_TYPE) && node["content"].any? { |child_node| contains_license_key_node.(child_node) }) end description.any? { |node| contains_license_key_node.(node) } end def has_posts? contains_posts_node = ->(node) do node["type"] == POSTS_NODE_TYPE || (node["type"].in?(COMMON_CONTAINER_NODE_TYPES) && node["content"].to_s.include?(POSTS_NODE_TYPE) && node["content"].any? { |child_node| contains_posts_node.(child_node) }) end description.any? { |node| contains_posts_node.(node) } end def self.human_attribute_name(attr, _) attr == "description" ? "Content" : super end private def select_file_embed_ids(node) if node["type"] == FILE_EMBED_NODE_TYPE id = node.dig("attrs", "id") return id.present? ? ObfuscateIds.decrypt(id) : nil end if node["type"].in?(FILE_EMBED_CONTAINER_NODE_TYPES) && node["content"].to_s.include?(FILE_EMBED_NODE_TYPE) node["content"].flat_map { select_file_embed_ids(_1) } end end def select_custom_field_nodes(nodes) nodes.flat_map do |node| if CUSTOM_FIELD_NODE_TYPES.include?(node["type"]) next [node] end if COMMON_CONTAINER_NODE_TYPES.include?(node["type"]) next select_custom_field_nodes(node["content"]) end [] end end def reset_moderated_by_iffy_flag return unless entity.is_a?(Link) entity.update_attribute(:moderated_by_iffy, false) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/last_read_community_chat_message.rb
app/models/last_read_community_chat_message.rb
# frozen_string_literal: true class LastReadCommunityChatMessage < ApplicationRecord include ExternalId belongs_to :user belongs_to :community belongs_to :community_chat_message validates :user_id, uniqueness: { scope: :community_id } def self.set!(user_id:, community_id:, community_chat_message_id:) record = find_or_initialize_by(user_id:, community_id:) if record.new_record? || (record.community_chat_message.created_at < CommunityChatMessage.find(community_chat_message_id).created_at) record.update!(community_chat_message_id:) end record end def self.unread_count_for(user_id:, community_id:, community_chat_message_id: nil) community_chat_message_id ||= find_by(user_id:, community_id:)&.community_chat_message_id if community_chat_message_id message = CommunityChatMessage.find(community_chat_message_id) CommunityChatMessage.where(community_id:).alive.where("created_at > ?", message.created_at).count else CommunityChatMessage.where(community_id:).alive.count end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/integration.rb
app/models/integration.rb
# frozen_string_literal: true class Integration < ApplicationRecord include FlagShihTzu include JsonData include TimestampScopes CIRCLE = "circle" DISCORD = "discord" ZOOM = "zoom" GOOGLE_CALENDAR = "google_calendar" ALL_NAMES = [CIRCLE, DISCORD, ZOOM, GOOGLE_CALENDAR] has_one :product_integration, dependent: :destroy scope :by_name, -> (name) { where(type: Integration.type_for(name)) } has_flags 1 => :keep_inactive_members, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false def as_json(*) { name:, keep_inactive_members:, integration_details: json_data } end def self.type_for(name) "#{name.capitalize.camelize}Integration" end def self.class_for(name) case name when CIRCLE CircleIntegration when DISCORD DiscordIntegration when ZOOM ZoomIntegration when GOOGLE_CALENDAR GoogleCalendarIntegration end end def self.enabled_integrations_for(purchase) ALL_NAMES.index_with { |name| class_for(name).is_enabled_for(purchase) } end def name type.chomp("Integration").underscore end def disconnect! true end def same_connection?(integration) false end def self.connection_settings [] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_tagging.rb
app/models/product_tagging.rb
# frozen_string_literal: true class ProductTagging < ApplicationRecord belongs_to :tag, optional: true belongs_to :product, class_name: "Link", optional: true validates_uniqueness_of :product_id, scope: :tag_id scope :owned_by_user, lambda { |user| joins(:product).where(links: { user_id: user.id }) } scope :has_tag_name, lambda { |name| joins(:tag).where(tags: { name: }) } scope :sorted_by_tags_usage_for_products, lambda { |products| join_products_on = "products_subq.id = product_taggings.product_id" products = products.select(:id) select("product_taggings.tag_id, count(tag_id) as tag_count") .joins("INNER JOIN (#{products.to_sql}) products_subq ON #{join_products_on}") .group("tag_id") .order("tag_count DESC") } after_commit :update_product_search_index! def update_product_search_index! product&.enqueue_index_update_for(["tags"]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/wishlist_follower.rb
app/models/wishlist_follower.rb
# frozen_string_literal: true class WishlistFollower < ApplicationRecord include ExternalId include Deletable belongs_to :wishlist belongs_to :follower_user, class_name: "User" validates :follower_user, uniqueness: { scope: [:wishlist_id, :deleted_at], message: "is already following this wishlist." } validate :cannot_follow_own_wishlist after_create :increment_follower_count after_update :update_follower_count, if: :saved_change_to_deleted_at? private def cannot_follow_own_wishlist if follower_user_id.present? && follower_user_id == wishlist&.user_id errors.add(:base, "You cannot follow your own wishlist.") end end def increment_follower_count wishlist.increment!(:follower_count) end def update_follower_count if deleted_at.present? wishlist.decrement!(:follower_count) else wishlist.increment!(:follower_count) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bhutan_bank_account.rb
app/models/bhutan_bank_account.rb
# frozen_string_literal: true class BhutanBankAccount < BankAccount BANK_ACCOUNT_TYPE = "BT" BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /^([0-9a-zA-Z]){1,17}$/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::BTN.alpha2 end def currency Currency::BTN end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/stamped_pdf.rb
app/models/stamped_pdf.rb
# frozen_string_literal: true class StampedPdf < ApplicationRecord include S3Retrievable, Deletable, CdnDeletable has_s3_fields :url belongs_to :url_redirect, optional: true belongs_to :product_file, optional: true validates_presence_of :url_redirect, :product_file, :url def user product_file.try(:link).try(:user) end def has_alive_duplicate_files? = false end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/team_membership.rb
app/models/team_membership.rb
# frozen_string_literal: true class TeamMembership < ApplicationRecord include ExternalId include TimestampStateFields has_paper_trail ROLES = %w(owner accountant admin marketing support).freeze ROLES.each do |role| self.const_set("ROLE_#{role.upcase}", role) scope "role_#{role}", -> { where(role:) } scope "role_not_#{role}", -> { where.not(role:) } define_method("role_#{role}?") do attributes["role"] == role end define_method("role_not_#{role}?") do attributes["role"] != role end end timestamp_state_fields :deleted belongs_to :seller, class_name: "User", foreign_key: :seller_id, optional: true belongs_to :user, optional: true validates_presence_of :user, :seller validates :role, inclusion: { in: ROLES, allow_nil: false } validates_uniqueness_of :seller, scope: %i[user deleted_at], if: :not_deleted? validate :owner_membership_must_exist validate :owner_role_cannot_be_assigned_to_other_users validate :only_owner_role_can_be_assigned_to_natural_owner private def owner_role_cannot_be_assigned_to_other_users return if role_not_owner? return if user == seller errors.add(:seller_id, "must match user for owner role") end def only_owner_role_can_be_assigned_to_natural_owner return if user != seller return if role_owner? errors.add(:role, "cannot be assigned to owner's membership") end def owner_membership_must_exist return if role_owner? return if user && user.user_memberships.one?(&:role_owner?) errors.add(:user_id, "requires owner membership to be created first") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/email_event_info.rb
app/models/email_event_info.rb
# frozen_string_literal: true class EmailEventInfo RECEIPT_MAILER_METHOD = "receipt" PREORDER_RECEIPT_MAILER_METHOD = "preorder_receipt" PURCHASE_INSTALLMENT_MAILER_METHOD = "purchase_installment" FOLLOWER_INSTALLMENT_MAILER_METHOD = "follower_installment" DIRECT_AFFILIATE_INSTALLMENT_MAILER_METHOD = "direct_affiliate_installment" TRACKED_RECEIPT_MAILER_METHODS = [RECEIPT_MAILER_METHOD, PREORDER_RECEIPT_MAILER_METHOD] TRACKED_INSTALLMENT_MAILER_METHODS = [PURCHASE_INSTALLMENT_MAILER_METHOD, FOLLOWER_INSTALLMENT_MAILER_METHOD, DIRECT_AFFILIATE_INSTALLMENT_MAILER_METHOD] # We don't have this mailer class in the app now, but we use the class name for backwards compatibility in the data. CREATOR_CONTACTING_CUSTOMERS_MAILER_CLASS = "CreatorContactingCustomersMailer" # Subset of events from: # - https://docs.sendgrid.com/for-developers/tracking-events/event#event-objects # - https://resend.com/docs/dashboard/webhooks/event-types EVENTS = { bounced: { MailerInfo::EMAIL_PROVIDER_SENDGRID => "bounce", MailerInfo::EMAIL_PROVIDER_RESEND => "email.bounced" }, delivered: { MailerInfo::EMAIL_PROVIDER_SENDGRID => "delivered", MailerInfo::EMAIL_PROVIDER_RESEND => "email.delivered" }, opened: { MailerInfo::EMAIL_PROVIDER_SENDGRID => "open", MailerInfo::EMAIL_PROVIDER_RESEND => "email.opened" }, clicked: { MailerInfo::EMAIL_PROVIDER_SENDGRID => "click", MailerInfo::EMAIL_PROVIDER_RESEND => "email.clicked" }, complained: { MailerInfo::EMAIL_PROVIDER_SENDGRID => "spamreport", MailerInfo::EMAIL_PROVIDER_RESEND => "email.complained" } }.freeze EVENTS.keys.each do |event_type| const_set("EVENT_#{event_type.upcase}", event_type) end TRACKED_EVENTS = { MailerInfo::EMAIL_PROVIDER_SENDGRID => EVENTS.transform_values { |v| v[MailerInfo::EMAIL_PROVIDER_SENDGRID] }, MailerInfo::EMAIL_PROVIDER_RESEND => EVENTS.transform_values { |v| v[MailerInfo::EMAIL_PROVIDER_RESEND] } }.freeze SUBSCRIPTION_INSTALLMENT_MAILER_METHOD = "subscription_installment" ABANDONED_CART_MAILER_METHOD = "abandoned_cart" CUSTOMER_MAILER = "CustomerMailer" attr_reader :mailer_method, :mailer_class, :installment_id, :click_url def click_url_as_mongo_key @_click_url_as_mongo_key ||= begin return if click_url.blank? return if unsubscribe_click? # Don't count unsubscribe clicks. if attachment_click? CreatorEmailClickEvent::VIEW_ATTACHMENTS_URL else # Encoding "." is necessary because Mongo doesn't allow periods as key names. click_url.gsub(/\./, "&#46;") end end end def for_installment_email? installment_id.present? end def for_receipt_email? mailer_class == CUSTOMER_MAILER && mailer_method.in?(TRACKED_RECEIPT_MAILER_METHODS) end def for_abandoned_cart_email? mailer_class == CUSTOMER_MAILER && mailer_method == ABANDONED_CART_MAILER_METHOD end private # Indicates whether the recipient clicked on the download attachments link def attachment_click? click_url =~ %r{#{DOMAIN}/d/[a-z0-9]{32}}o end # The regex corresponds to possible ExternalIds and SecureExternalIds # Legacy ExternalIds: base64 encoded with urlsafe parameters (- and _ instead of + and /) and may end in = or == # Secure ExternalIds: longer strings using URL-safe characters (letters, digits, hyphens, underscores) EXTERNAL_ID_PATTERN = "[\\w-]+={0,2}" private_constant :EXTERNAL_ID_PATTERN # Checks if the url is for unsubscribing or unfollowing. def unsubscribe_click? # These are three different paths that a user may click to unsubscribe. customer_path = URI::DEFAULT_PARSER.unescape( Rails.application.routes.url_helpers.unsubscribe_purchase_path(EXTERNAL_ID_PATTERN) ) imported_customer_path = URI::DEFAULT_PARSER.unescape( Rails.application.routes.url_helpers.unsubscribe_imported_customer_path(EXTERNAL_ID_PATTERN) ) follower_path = URI::DEFAULT_PARSER.unescape( Rails.application.routes.url_helpers.cancel_follow_path(EXTERNAL_ID_PATTERN) ) click_url =~ /#{DOMAIN}(#{customer_path}|#{imported_customer_path}|#{follower_path})/ end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/team_invitation.rb
app/models/team_invitation.rb
# frozen_string_literal: true class TeamInvitation < ApplicationRecord include ExternalId include TimestampStateFields has_paper_trail ACTIVE_INTERVAL_IN_DAYS = 7 ROLES = TeamMembership::ROLES .excluding(TeamMembership::ROLE_OWNER) ROLES.each do |role| scope "role_#{role}", -> { where(role:) } define_method("role_#{role}?") do attributes["role"] == role end end stripped_fields :email, transform: -> { _1.downcase } timestamp_state_fields :accepted, :deleted belongs_to :seller, class_name: "User", foreign_key: :seller_id validates :email, email_format: true with_options if: :not_deleted? do validates_uniqueness_of :email, scope: %i[seller_id deleted_at], message: "has already been invited" validate :email_cannot_belong_to_existing_member end validates :role, inclusion: { in: ROLES, allow_nil: false } def expired? expires_at < Time.current end def from_gumroad_account? seller.gumroad_account? end def matches_owner_email? email.downcase == seller.email.downcase end private def email_cannot_belong_to_existing_member return unless seller.present? return if seller.seller_memberships.not_deleted.joins(:user).where("users.email = ?", email).none? && email != seller.email errors.add :email, "is associated with an existing team member" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/colombia_bank_account.rb
app/models/colombia_bank_account.rb
# frozen_string_literal: true class ColombiaBankAccount < BankAccount include ColombiaBankAccount::AccountType BANK_ACCOUNT_TYPE = "CO" BANK_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{9,16}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number before_validation :set_default_account_type, on: :create, if: ->(bank_account) { bank_account.account_type.nil? } validate :validate_bank_code validate :validate_account_number validates :account_type, inclusion: { in: AccountType.all } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::COL.alpha2 end def currency Currency::COP end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end def set_default_account_type self.account_type = ColombiaBankAccount::AccountType::CHECKING end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bosnia_and_herzegovina_bank_account.rb
app/models/bosnia_and_herzegovina_bank_account.rb
# frozen_string_literal: true class BosniaAndHerzegovinaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "BA" BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::BIH.alpha2 end def currency Currency::BAM end def account_number_visual "BA******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/service_charge.rb
app/models/service_charge.rb
# frozen_string_literal: true class ServiceCharge < ApplicationRecord include CurrencyHelper include ActionView::Helpers::DateHelper include Mongoable include PurchaseErrorCode include DiscountCode include ExternalId include JsonData include TimestampScopes include Purchase::CardCountrySource include Rails.application.routes.url_helpers include FlagShihTzu attr_json_data_accessor :locale, default: -> { "en" } attr_json_data_accessor :card_country_source attr_json_data_accessor :chargeback_reason belongs_to :user, optional: true belongs_to :recurring_service, optional: true belongs_to :credit_card, optional: true belongs_to :merchant_account, optional: true has_one :dispute has_many :events # ServiceCharge state transitions: # # in_progress β†’ successful # ↓ # failed # # (DEPRECATED) Authorizations - these are to make sure the card can be charged prior to the free trial: # # in_progress β†’ authorization_successful # ↓ # authorization_failed # state_machine :state, initial: :in_progress do event :mark_successful do transition in_progress: :successful end event :mark_failed do transition in_progress: :failed end event :mark_authorization_successful do transition in_progress: :authorization_successful end event :mark_authorization_failed do transition in_progress: :authorization_failed end end before_save :to_mongo validates_presence_of :user validates_associated :user validates :charge_cents, numericality: true, presence: true has_flags 1 => :chargeback_reversed, 2 => :was_zip_code_check_performed, 3 => :is_authorization_charge, 4 => :is_automatic_charge, 5 => :is_charge_by_admin, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false attr_accessor :chargeable, :card_data_handling_error, :perceived_charge_cents, :charge_intent delegate :email, :name, to: :user scope :in_progress, -> { where(state: "in_progress") } scope :successful, -> { where(state: "successful") } scope :authorization_successful, -> { where(state: "authorization_successful") } scope :successful_or_authorization_successful, -> { where("state = 'successful' OR state = 'authorization_successful'") } scope :failed, -> { where(state: "failed") } scope :charge_processor_failed, -> { failed.where("service_charges.charge_processor_fingerprint IS NOT NULL AND service_charges.charge_processor_fingerprint != ''") } scope :refunded, -> { successful.where("service_charges.charge_processor_refunded = 1") } scope :not_refunded, -> { where("service_charges.charge_processor_refunded = 0") } scope :chargedback, -> { successful.where("service_charges.chargeback_date IS NOT NULL") } scope :not_chargedback, -> { where("service_charges.chargeback_date IS NULL") } scope :created_after, ->(start_at = nil) { start_at ? where("service_charges.created_at > ?", start_at) : all } scope :created_before, ->(end_at = nil) { end_at ? where("service_charges.created_at < ?", end_at) : all } def as_json(options = {}) { id: external_id, user_id: user.external_id, timestamp: "#{time_ago_in_words(created_at)} ago", created_at:, charge_cents:, formatted_charge:, refunded: refunded?, chargedback: chargedback?, card: { visual: card_visual, type: card_type, # legacy param bin: nil, expiry_month: card_expiry_month, expiry_year: card_expiry_year } } end def chargedback? chargeback_date.present? end def refunded? charge_processor_refunded end def formatted_charge MoneyFormatter.format(charge_cents, :usd, no_cents_if_whole: true, symbol: true) end def send_service_charge_receipt ServiceMailer.service_charge_receipt(id).deliver_later(queue: "critical", wait: 3.seconds) end def time_fields fields = attributes.keys.keep_if { |key| key.include?("_at") && send(key) } fields << "chargeback_date" if chargeback_date fields end def discount_amount discount = DiscountCode::DISCOUNT_CODES[discount_code.to_sym] amount = discount[:function] ? recurring_service.send(discount[:function]) : discount[:amount] if discount[:type] == :percentage old_total = charge_cents / (1 - amount / 100.0).round discount_cents = old_total - charge_cents elsif discount[:type] == :cents discount_cents = amount end MoneyFormatter.format(discount_cents, :usd, no_cents_if_whole: true, symbol: true) end def upload_invoice_pdf(pdf) timestamp = Time.current.strftime("%F") key = "#{Rails.env}/#{timestamp}/invoices/service_charges/#{external_id}-#{SecureRandom.hex}/invoice.pdf" s3_obj = Aws::S3::Resource.new.bucket(INVOICES_S3_BUCKET).object(key) s3_obj.put(body: pdf) s3_obj end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/user_compliance_info_request.rb
app/models/user_compliance_info_request.rb
# frozen_string_literal: true class UserComplianceInfoRequest < ApplicationRecord include ExternalId include JsonData include FlagShihTzu belongs_to :user, optional: true validates :user, presence: true has_flags 1 => :only_needs_field_to_be_partially_provided, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false attr_json_data_accessor :stripe_event_id attr_json_data_writer :emails_sent_at attr_json_data_accessor :sg_verification_reminder_sent_at attr_json_data_accessor :verification_error state_machine :state, initial: :requested do before_transition any => :provided, :do => lambda { |user_compliance_info_request| user_compliance_info_request.provided_at = Time.current } event :mark_provided do transition requested: :provided end end scope :requested, -> { where(state: :requested) } scope :provided, -> { where(state: :provided) } scope :only_needs_field_to_be_partially_provided, lambda { |does_only_needs_field_to_be_partially_provided = true| where( "flags & ? = ?", flag_mapping["flags"][:only_needs_field_to_be_partially_provided], does_only_needs_field_to_be_partially_provided ? flag_mapping["flags"][:only_needs_field_to_be_partially_provided] : 0 ) } def emails_sent_at email_sent_at_raw = json_data_for_attr("emails_sent_at", default: []) email_sent_at_raw.map { |email_sent_at| email_sent_at.is_a?(String) ? Time.zone.parse(email_sent_at) : email_sent_at } end def last_email_sent_at emails_sent_at.last end def record_email_sent!(email_sent_at = Time.current) self.emails_sent_at = emails_sent_at << email_sent_at save! end def self.handle_new_user_compliance_info(user_compliance_info) UserComplianceInfoFields.all_fields_on_user_compliance_info.each do |field| field_value = user_compliance_info.send(field) field_value = field_value.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")) if field_value.is_a?(Strongbox::Lock) next if field_value.blank? field_filter = UserComplianceInfoFieldProperty.property_for_field( field, UserComplianceInfoFieldProperty::FILTER, country: user_compliance_info.country_code ) field_value = field_value.scan(field_filter).join if field_filter next if field_value.blank? field_expected_length = UserComplianceInfoFieldProperty.property_for_field( field, UserComplianceInfoFieldProperty::LENGTH, country: user_compliance_info.country_code ) field_provided_in_part = field_value.length < field_expected_length if field_expected_length.present? requests = user_compliance_info.user.user_compliance_info_requests.requested.where(field_needed: field) requests = requests.only_needs_field_to_be_partially_provided if field_provided_in_part requests.find_each(&:mark_provided!) end end def self.handle_new_bank_account(bank_account) bank_account.user.user_compliance_info_requests.requested.where(field_needed: UserComplianceInfoFields::BANK_ACCOUNT).find_each(&:mark_provided!) end def verification_error_message return nil if verification_error.blank? return verification_error["message"] if verification_error["message"] case verification_error["code"] when "verification_directors_mismatch" "The provided directors on the account could not be verified. Correct any errors on the provided directors or upload a document that matches the provided information." when "verification_document_address_mismatch" "The address on the ID document doesn’t match the address provided on the account. Please verify and correct the provided address on the account, or upload a document with address that matches the account." when "verification_document_address_missing" "The uploaded document is missing the address information. Please upload another document that contains the address information." when "verification_document_corrupt" "The document verification failed as the file was corrupt. Please provide a clearly legible color document (8,000 pixels by 8,000 pixels or smaller), 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_country_not_supported" "The provided document is not an acceptable form of ID from a supported country, or is not a type of legal entity document that is expected. Please provide a new file that meets that requirement." when "verification_document_directors_mismatch" "The directors on the document did not match the directors on the account. Upload a document with matching directors or update the directors on the account." when "verification_document_dob_mismatch" "The date of birth on the ID document doesn’t match the date of birth provided on the account. Please verify and correct the provided date of birth on the account, or upload a document with date of birth that matches the account." when "verification_document_duplicate_type" "The same type of document was used twice. Two unique types of documents are required for verification. Upload two different documents." when "verification_document_expired" "The issue or expiry date is missing on the document, or the document is expired. If it’s an identity document, its expiration date must be after the date the document was submitted. If it’s an address document, the issue date must be within the last six months." when "verification_document_failed_copy" "Copies (including photos or scans) of the original document cannot be read. Please upload the original document in color (8,000 pixels by 8,000 pixels or smaller), 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_failed_greyscale" "The document verification failed as the file was in gray scale. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_failed_other" "There was a problem with verification of the document that you provided." when "verification_document_fraudulent" "The document might have been altered so it could not be verified." when "verification_document_id_number_mismatch" "The ID number on the ID document doesn’t match the ID number provided on the account. Please verify and correct the provided ID number on the account, or upload a document with ID number that matches the account." when "verification_document_id_number_missing" "The uploaded document is missing the ID number. Please upload another document that contains the ID number." when "verification_document_incomplete" "The document verification failed as it was incomplete. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_invalid" "The provided document is not an acceptable form of ID from a supported country, or is not a type of legal entity document that is expected. Please provide a new file that meets that requirement." when "verification_document_issue_or_expiry_date_missing" "The issue or expiry date is missing on the document, or the document is expired. If it’s an identity document, its expiration date must be after the date the document was submitted. If it’s an address document, the issue date must be within the last six months." when "verification_document_manipulated" "The document might have been altered so it could not be verified." when "verification_document_missing_back" "The document verification failed as the back side of the document was not provided. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_missing_front" "The document upload failed as the front side of the document was not provided. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_name_mismatch" "The name on the ID document doesn’t match the name provided on the account. Please verify and correct the provided name on the account, or upload a document with name that matches the account." when "verification_document_name_missing" "The uploaded document is missing the name. Please upload another document that contains the name." when "verification_document_not_readable" "The document verification failed as it was not readable. Please provide a valid color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_not_signed" "The document verification failed as it was not signed. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_not_uploaded" "The document verification failed due to a problem with the file itself. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_photo_mismatch" "The photo on the ID document doesn’t match the photo provided on the account. Please verify and correct the provided photo on the account, or upload a document with photo that matches the account." when "verification_document_too_large" "The document verification failed as the file was too large. Please provide a clearly legible color image (8,000 pixels by 8,000 pixels or smaller), which is 10 MB or less in size, in JPG or PNG format. Please make sure the file contains all required pages of the document and is not password protected." when "verification_document_type_not_supported" "The provided document is not an acceptable form of ID from a supported country, or is not a type of legal entity document that is expected. Please provide a new file that meets that requirement." when "verification_extraneous_directors" "We have identified extra directors that we haven’t been able to verify. Please remove any extraneous directors from the account." when "verification_failed_address_match" "The address on the document doesn’t match the address on the account. Please verify and correct the provided address on the account, or upload a document with address that matches the account." when "verification_failed_document_match" "The information on the account couldn’t be verified. Please either upload a document to confirm the account details, or update the information on your account." when "verification_failed_id_number_match" "The ID number on the document doesn’t match the ID number on the account. Please verify and correct the provided ID number on the account, or upload a document with ID number that matches the account." when "verification_failed_keyed_identity" "The identity information you entered cannot be verified. Please correct any errors or upload a document that matches the identity fields (e.g., name and date of birth) that you entered." when "verification_failed_keyed_match" "The information on the account couldn’t be verified. Please either upload a document to confirm the account details, or update the information on your account." when "verification_failed_name_match" "The name on the document doesn’t match the name on the account. Please verify and correct the provided name on the account, or upload a document with name that matches the account." when "verification_failed_other" "There was a problem with your identity verification." when "verification_failed_residential_address" "We could not verify that the person resides at the provided address. The address must be a valid physical address where the individual resides and cannot be a P.O. Box." when "verification_failed_tax_id_match" "The tax ID that you provided couldn’t be verified with the IRS. Please correct any possible errors in the company name or tax ID, or upload a document that contains those fields." when "verification_failed_tax_id_not_issued" "The tax ID that you provided couldn’t be verified with the IRS. Please correct any possible errors in the company name or tax ID, or upload a document that contains those fields." when "verification_missing_directors" "We have identified directors that haven’t been added on the account. Add any missing directors to the account." when "verification_missing_executives" "We have identified executives that haven’t been added on the account. Add any missing executives to the account." when "verification_missing_owners" "We have identified owners that haven’t been added on the account. Add any missing owners to the account." when "verification_requires_additional_memorandum_of_associations" "We have identified holding companies with significant percentage ownership. Upload a Memorandum of Association for each of the holding companies." end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/iceland_bank_account.rb
app/models/iceland_bank_account.rb
# frozen_string_literal: true class IcelandBankAccount < BankAccount BANK_ACCOUNT_TYPE = "IS" validate :validate_account_number def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::ISL.alpha2 end def currency Currency::EUR end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/cote_d_ivoire_bank_account.rb
app/models/cote_d_ivoire_bank_account.rb
# frozen_string_literal: true class CoteDIvoireBankAccount < BankAccount BANK_ACCOUNT_TYPE = "CI" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::CIV.alpha2 end def currency Currency::XOF end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/community_chat_recap_run.rb
app/models/community_chat_recap_run.rb
# frozen_string_literal: true class CommunityChatRecapRun < ApplicationRecord has_many :community_chat_recaps, dependent: :destroy validates :recap_frequency, :from_date, :to_date, presence: true validates :recap_frequency, uniqueness: { scope: [:from_date, :to_date] } enum :recap_frequency, { daily: "daily", weekly: "weekly" }, prefix: true, validate: true scope :running, -> { where(finished_at: nil) } scope :finished, -> { where.not(finished_at: nil) } scope :between, ->(from_date, to_date) { where("from_date >= ? AND to_date <= ?", from_date, to_date) } after_save_commit :trigger_weekly_recap_run after_save_commit :send_recap_notifications def finished? finished_at.present? end def check_if_finished! return if finished? recap_statuses = community_chat_recaps.pluck(:status) return if recap_statuses.include?("pending") return if (recaps_count - recap_statuses.select { |status| status.in?(%w[finished failed]) }.size) > 0 update!(finished_at: Time.current) end private def trigger_weekly_recap_run return unless recap_frequency_daily? return unless finished? return unless Date::DAYNAMES[from_date.wday] == "Saturday" TriggerCommunityChatRecapRunJob.perform_async("weekly", (from_date.to_date - 6.days).to_date.to_s) end def send_recap_notifications return unless finished? return if notified_at.present? SendCommunityChatRecapNotificationsJob.perform_async(id) update!(notified_at: Time.current) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/recommended_purchase_info.rb
app/models/recommended_purchase_info.rb
# frozen_string_literal: true class RecommendedPurchaseInfo < ApplicationRecord include FlagShihTzu belongs_to :purchase, optional: true belongs_to :recommended_link, class_name: "Link", optional: true belongs_to :recommended_by_link, class_name: "Link", optional: true validates_inclusion_of :recommender_model_name, in: RecommendedProductsService::MODELS, allow_nil: true has_flags 1 => :is_recurring_purchase, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false scope :successful_by_date, lambda { |date| joins(:purchase).where("recommended_purchase_infos.created_at > ?", date).where("purchases.purchase_state = 'successful'") } end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bulgaria_bank_account.rb
app/models/bulgaria_bank_account.rb
# frozen_string_literal: true class BulgariaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "BG" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::BGR.alpha2 end def currency Currency::EUR end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/blocked_customer_object.rb
app/models/blocked_customer_object.rb
# frozen_string_literal: true class BlockedCustomerObject < ApplicationRecord SUPPORTED_OBJECT_TYPES = { email: "email", charge_processor_fingerprint: "charge_processor_fingerprint" }.freeze has_paper_trail belongs_to :seller, class_name: "User" validates_presence_of :object_type, :object_value validates_presence_of :buyer_email, if: -> { object_type == SUPPORTED_OBJECT_TYPES[:charge_processor_fingerprint] } validates_inclusion_of :object_type, in: SUPPORTED_OBJECT_TYPES.values validates :object_value, email_format: true, if: -> { object_type == SUPPORTED_OBJECT_TYPES[:email] } validates :buyer_email, email_format: true, allow_blank: true scope :email, -> { where(object_type: SUPPORTED_OBJECT_TYPES[:email]) } scope :active, -> { where.not(blocked_at: nil) } scope :inactive, -> { where(blocked_at: nil) } def self.email_blocked?(email:, seller_id:) return false if email.blank? active.email.where(seller_id:, object_value: comparable_email(email:)).exists? end def self.block_email!(email:, seller_id:) find_or_initialize_by(seller_id:, object_type: SUPPORTED_OBJECT_TYPES[:email], object_value: email).tap do |blocked_object| return true if blocked_object.blocked_at? blocked_object.blocked_at = DateTime.current blocked_object.save! end end def self.comparable_email(email:) local_part, domain = email.downcase.split("@") local_part = local_part.split("+").first # normalize plus sub-addressing local_part = local_part.delete(".") # remove dots "#{local_part}@#{domain}" end private_class_method :comparable_email def unblock! return true if blocked_at.nil? update!(blocked_at: nil) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/serbia_bank_account.rb
app/models/serbia_bank_account.rb
# frozen_string_literal: true class SerbiaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "RS" BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /^RS([0-9]){18,20}$/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::SRB.alpha2 end def currency Currency::RSD end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sri_lanka_bank_account.rb
app/models/sri_lanka_bank_account.rb
# frozen_string_literal: true class SriLankaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "LK" BANK_CODE_FORMAT_REGEX = /^[a-z0-9A-Z]{11}$/ BRANCH_CODE_FORMAT_REGEX = /^\d{7}$/ ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{10,18}$/ private_constant :BANK_CODE_FORMAT_REGEX, :BRANCH_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_branch_code validate :validate_account_number def routing_number "#{bank_code}-#{branch_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::LKA.alpha2 end def currency Currency::LKR end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_branch_code return if BRANCH_CODE_FORMAT_REGEX.match?(branch_code) errors.add :base, "The branch code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_profile_featured_product_section.rb
app/models/seller_profile_featured_product_section.rb
# frozen_string_literal: true class SellerProfileFeaturedProductSection < SellerProfileSection end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/admin_action_call_info.rb
app/models/admin_action_call_info.rb
# frozen_string_literal: true class AdminActionCallInfo < ApplicationRecord validates_presence_of :controller_name, :action_name end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/paraguay_bank_account.rb
app/models/paraguay_bank_account.rb
# frozen_string_literal: true class ParaguayBankAccount < BankAccount BANK_ACCOUNT_TYPE = "PY" BANK_CODE_FORMAT_REGEX = /\A[0-9]{1,2}\z/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{1,16}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::PRY.alpha2 end def currency Currency::PYG end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/ghana_bank_account.rb
app/models/ghana_bank_account.rb
# frozen_string_literal: true class GhanaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "GH" BANK_CODE_FORMAT_REGEX = /\A[0-9]{6}\z/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{8,20}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number bank_code end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::GHA.alpha2 end def currency Currency::GHS end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/charge.rb
app/models/charge.rb
# frozen_string_literal: true class Charge < ApplicationRecord include ExternalId, Chargeable, Purchase::ChargeEventsHandler, Disputable, FlagShihTzu, Refundable COMBINED_CHARGE_PREFIX = "CH-" belongs_to :order belongs_to :seller, class_name: "User" belongs_to :merchant_account, optional: true belongs_to :credit_card, optional: true has_many :charge_purchases, dependent: :destroy has_many :purchases, through: :charge_purchases, dependent: :destroy has_many :refunds, through: :purchases attr_accessor :charge_intent, :setup_future_charges has_flags 1 => :receipt_sent, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false delegate :full_name, :purchaser, to: :purchase_as_chargeable delegate :tax_label_with_creator_tax_info, to: :purchase_with_tax_as_chargeable, allow_nil: true delegate :purchase_sales_tax_info, to: :purchase_with_sales_tax_info_as_chargeable, allow_nil: true delegate :purchase_taxjar_info, to: :purchase_with_taxjar_info_as_chargeable, allow_nil: true delegate :street_address, :city, :state, :state_or_from_ip_address, :zip_code, :country, to: :purchase_with_address_as_chargeable def statement_description seller.name_or_username end def reference_id_for_charge_processors COMBINED_CHARGE_PREFIX + external_id end def id_with_prefix COMBINED_CHARGE_PREFIX + id.to_s end def update_processor_fee_cents!(processor_fee_cents:) return unless processor_fee_cents.present? transaction do update!(processor_fee_cents:) charged_purchases.each do |purchase| purchase_processor_fee_cents = (processor_fee_cents * (purchase.total_transaction_cents.to_f / amount_cents)).round purchase.update!(processor_fee_cents: purchase_processor_fee_cents) end end end def upload_invoice_pdf(pdf) purchase_as_chargeable.upload_invoice_pdf(pdf) end def successful_purchases purchases.all_success_states_including_test end def shipping_cents @_shipping_cents ||= successful_purchases.sum(&:shipping_cents) end def has_invoice? successful_purchases.any?(&:has_invoice?) end def country_name purchase_as_chargeable.country_or_ip_country end def update_charge_details_from_processor!(processor_charge) return unless processor_charge.present? self.processor = processor_charge.charge_processor_id self.payment_method_fingerprint = processor_charge.card_fingerprint self.processor_transaction_id = processor_charge.id self.processor_fee_cents = processor_charge.fee self.processor_fee_currency = processor_charge.fee_currency update_processor_fee_cents!(processor_fee_cents: processor_charge.fee) save! end # Avoids creating an endpoint for the charge invoice since the invoice is the same # for all purchases that belong to the same charge def invoice_url Rails.application.routes.url_helpers.generate_invoice_by_buyer_url( purchase_as_chargeable.external_id, email: purchase_as_chargeable.email, host: UrlService.domain_with_protocol ) end def taxable? purchase_with_tax_as_chargeable.present? end def multi_item_charge? @_is_multi_item_charge ||= successful_purchases.many? end def require_shipping? purchase_with_shipping_as_chargeable.present? end def is_direct_to_australian_customer? require_shipping? && country == Compliance::Countries::AUS.common_name end def taxed_by_gumroad? purchase_with_gumroad_tax_as_chargeable.present? end def refund_and_save!(refunding_user_id) transaction do successful_purchases.each do |purchase| purchase.refund_and_save!(refunding_user_id) end end end def refund_gumroad_taxes!(refunding_user_id:, note: nil, business_vat_id: nil) transaction do successful_purchases .select { _1.gumroad_tax_cents > 0 }.each do |purchase| purchase.refund_gumroad_taxes!(refunding_user_id:, note:, business_vat_id:) end end end def refund_for_fraud_and_block_buyer!(refunding_user_id) with_lock do successful_purchases.each do |purchase| purchase.refund_for_fraud!(refunding_user_id) end block_buyer!(blocking_user_id: refunding_user_id) end end def block_buyer!(blocking_user_id: nil, comment_content: nil) purchase_as_chargeable.block_buyer!(blocking_user_id:, comment_content:) end def sync_status_with_charge_processor(mark_as_failed: false) transaction do purchases.each do |purchase| purchase.sync_status_with_charge_processor(mark_as_failed:) end end end def external_id_for_invoice purchase_as_chargeable.external_id end def external_id_numeric_for_invoice purchase_as_chargeable.external_id_numeric.to_s end def country_or_ip_country purchase_with_address_as_chargeable.country.presence || purchase_with_address_as_chargeable.ip_country end def purchases_requiring_stamping @_purchases_requiring_stamping ||= successful_purchases .select { _1.link.has_stampable_pdfs? && _1.url_redirect.present? } .reject { _1.url_redirect.is_done_pdf_stamping? } end def charged_using_stripe_connect_account? merchant_account&.is_a_stripe_connect_account? end def buyer_blocked? purchase_as_chargeable.buyer_blocked? end def receipt_email_info # Queries `email_info_charges` first to leverage the index since there is no `purchase_id` on the associated # `email_infos` record (`email_infos` has > 1b records, and relies on `purchase_id` index) EmailInfoCharge.includes(:email_info) .where(charge_id: id) .where( email_infos: { email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD, type: CustomerEmailInfo.name } ) .last&.email_info end def first_purchase_for_subscription successful_purchases.includes(:subscription).detect { _1.subscription.present? } end def self.parse_id(id) id.starts_with?(Charge::COMBINED_CHARGE_PREFIX) ? id.sub(Charge::COMBINED_CHARGE_PREFIX, "") : id end private # At least one product must be taxable for the charge to be taxable. # For that, we need to find at least one purchase that was taxable. def purchase_with_tax_as_chargeable @_purchase_with_tax_as_chargeable ||= successful_purchases.select(&:was_purchase_taxable?).first end def purchase_with_sales_tax_info_as_chargeable @_purchase_with_sales_tax_info_as_chargeable ||= \ successful_purchases.find { _1.purchase_sales_tax_info&.business_vat_id.present? } || purchase_with_tax_as_chargeable end def purchase_with_taxjar_info_as_chargeable @_purchase_with_taxjar_info_as_chargeable ||= successful_purchases.find { _1.purchase_taxjar_info.present? } end # Used to determine if the charge requires shipping. It returns a purchase associated with a physical product # At least one product must require shipping for the charge to require shipping. def purchase_with_shipping_as_chargeable @_purchase_with_shipping_as_chargeable ||= successful_purchases.select(&:require_shipping?).first end # During checkout we collect partial address information that is used for generating the invoice # If the charge doesn't require shipping, we still want to use the partial address information # to generate the invoice def purchase_with_address_as_chargeable purchase_with_shipping_as_chargeable || purchase_as_chargeable end # To be used only when the data retrieved is present on ALL purchases def purchase_as_chargeable @_purchase_as_chargeable ||= successful_purchases.first end def purchase_with_gumroad_tax_as_chargeable @_purchase_with_gumroad_tax_as_chargeable ||= successful_purchases .select { _1.gumroad_tax_cents > 0 } .first end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sendgrid_event_info.rb
app/models/sendgrid_event_info.rb
# frozen_string_literal: true class SendgridEventInfo < EmailEventInfo attr_reader \ :charge_id, :click_url, :email, :event_json, :installment_id, :mailer_args, :mailer_class_and_method, :mailer_class, :mailer_method, :purchase_id, :type, :created_at def initialize(event_json) @event_json = event_json @email = event_json["email"] @click_url = event_json["url"] @installment_id = event_json["installment_id"] @type = TRACKED_EVENTS[MailerInfo::EMAIL_PROVIDER_SENDGRID].invert[event_json["event"]] @created_at = Time.zone.at(event_json["timestamp"]) if event_json.key?("timestamp") if event_json["type"].present? && event_json["identifier"].present? initialize_from_type_and_identifier_unique_args(event_json) else initialize_from_record_level_unique_args(event_json) end end def invalid? # The event must have a type (otherwise it's not tracked), and appropriate metadata type.blank? || mailer_class_and_method.blank? || mailer_args.blank? end # Used by HandleEmailEventInfo::ForAbandonedCartEmail def workflow_ids # mailer_args is a string that looks like this: "[3783, {\"5296\"=>[153758, 163413], \"5644\"=>[163413]}]" parsed_mailer_args = JSON.parse(mailer_args.gsub("=>", ":")) rescue [] if parsed_mailer_args.size != 2 Bugsnag.notify("Abandoned cart email event has unexpected mailer_args size", mailer_args:) return [] end _cart_id, workflows_ids_with_product_ids = parsed_mailer_args workflows_ids_with_product_ids.keys end def email_provider MailerInfo::EMAIL_PROVIDER_SENDGRID end private # Old data structure that is used by post emails (via PostSendgridApi), and it was used by receipt emails until # Mar 2024. Should be kept around unless we no longer want to parse events for emails sent using the old data # structure. # Sample SendgGrid header: # { # "environment": "test", # "category": ["CustomerMailer" , "CustomerMailer.receipt"], # "unique_args": { # "identifier": "[1]", # "type": "CustomerMailer.receipt" # } # } def initialize_from_type_and_identifier_unique_args(event_json) @mailer_class_and_method = event_json["type"] @mailer_class, @mailer_method = @mailer_class_and_method.split(".", 2) @mailer_args = event_json["identifier"] @purchase_id = find_purchase_id_from_mailer_args end def find_purchase_id_from_mailer_args id = mailer_args.gsub(/\[|\]/, "").split(",").first.to_i if mailer_class_and_method == "#{CUSTOMER_MAILER}.#{PREORDER_RECEIPT_MAILER_METHOD}" Preorder.find(id).authorization_purchase.id else id end end # Sample SendGrid header: # { # "environment": "test", # "category": ["CustomerMailer" , "CustomerMailer.receipt"], # "unique_args": { # "purchase_id": 1, # "mailer_class": "CustomerMailer", # "mailer_method":"receipt" # } # } def initialize_from_record_level_unique_args(event_json) @mailer_class_and_method = "#{event_json["mailer_class"]}.#{event_json["mailer_method"]}" @mailer_class = event_json["mailer_class"] @mailer_method = event_json["mailer_method"] @mailer_args = event_json["mailer_args"] @purchase_id = event_json["purchase_id"] @charge_id = event_json["charge_id"] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bahrain_bank_account.rb
app/models/bahrain_bank_account.rb
# frozen_string_literal: true class BahrainBankAccount < BankAccount BANK_ACCOUNT_TYPE = "BH" BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::BHR.alpha2 end def currency Currency::BHD end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sales_related_products_info.rb
app/models/sales_related_products_info.rb
# frozen_string_literal: true class SalesRelatedProductsInfo < ApplicationRecord belongs_to :smaller_product, class_name: "Link" belongs_to :larger_product, class_name: "Link" validates_numericality_of :smaller_product_id, less_than: :larger_product_id scope :for_product_id, ->(product_id) { where("smaller_product_id = :product_id OR larger_product_id = :product_id", product_id:) } def self.find_or_create_info(product1_id, product2_id) if product1_id > product2_id find_or_create_by(smaller_product_id: product2_id, larger_product_id: product1_id) else find_or_create_by(smaller_product_id: product1_id, larger_product_id: product2_id) end rescue ActiveRecord::RecordNotUnique retry end def self.update_sales_counts(product_id:, related_product_ids:, increment:) return if related_product_ids.empty? raise ArgumentError, "product_id must be an integer" unless product_id.is_a?(Integer) raise ArgumentError, "related_product_ids must be an array of integers" unless related_product_ids.all? { _1.is_a?(Integer) } now_string = %("#{Time.current.to_fs(:db)}") sales_count_change = increment ? 1 : -1 # Update existing larger_ids, smaller_ids = related_product_ids.partition { _1 > product_id } existing = where(smaller_product_id: product_id, larger_product_id: larger_ids) .or(where(smaller_product_id: smaller_ids, larger_product_id: product_id)) .pluck(:id, :smaller_product_id, :larger_product_id) where(id: existing.map(&:first)) .in_batches(of: 1_000) .update_all("sales_count = sales_count + #{sales_count_change}, updated_at = #{now_string}") # Insert remaining remaining = related_product_ids - existing.map { [_2, _3] }.flatten.uniq - [product_id] return if remaining.empty? new_sales_count = increment ? 1 : 0 remaining.each_slice(100) do |remaining_slice| inserts_sql = remaining_slice.map do |related_product_id| smaller_id, larger_id = [product_id, related_product_id].sort [smaller_id, larger_id, new_sales_count, now_string, now_string].join(", ") end.map { "(#{_1})" }.join(", ") query = <<~SQL INSERT IGNORE INTO #{table_name} (smaller_product_id, larger_product_id, sales_count, created_at, updated_at) VALUES #{inserts_sql}; SQL ApplicationRecord.connection.execute(query) end end # In: an array of product ids (typically: up to 50 latest cart and/or purchased products) # Out: An ordered ActiveRelation of products def self.related_products(product_ids, limit: 10) return Link.none if product_ids.blank? raise ArgumentError, "product_ids must be an array of integers" unless product_ids.all? { _1.is_a?(Integer) } raise ArgumentError, "limit must an integer" unless limit.is_a?(Integer) counts = Hash.new { 0 } product_ids.each_slice(100) do |product_ids_slice| # prevent huge sql queries products_counts = CachedSalesRelatedProductsInfo.where(product_id: product_ids_slice).map(&:normalized_counts) products_counts.flat_map(&:to_a).each do |product_id, sales_count| counts[product_id] += sales_count # sum sales counts for the same products across relationships end end related_products_ids = counts. except(*product_ids). # remove requested products sort { { 0 => (_2[0] <=> _1[0]), 1 => 1, -1 => -1 }[_2[1] <=> _1[1]] }. # sort by sales count (desc), then by product id (desc) in case of equality first(limit). # get the top results map(&:first) # return the product ids only Link.where(id: related_products_ids).in_order_of(:id, related_products_ids) end # Used when generating cached data for a product. # In: a single product id # Out: a hash of related products and the sales counts: { product_id => sales_count, ... } def self.related_product_ids_and_sales_counts(product_id, limit: 10) raise ArgumentError, "product_id must be an integer" unless product_id.is_a?(Integer) raise ArgumentError, "limit must be an integer" unless limit.is_a?(Integer) sql = <<~SQL.squish select product_id, sales_count from (#{two_sided_related_product_ids_and_sales_counts_sql(product_id:, limit:)}) t order by sales_count desc limit #{limit} SQL connection.exec_query(sql).rows.to_h end private def self.two_sided_related_product_ids_and_sales_counts_sql(product_id:, limit:) <<~SQL (#{one_sided_related_product_ids_and_sales_counts_sql(product_id:, limit:, column: :smaller_product_id, mirror_column: :larger_product_id)}) union all (#{one_sided_related_product_ids_and_sales_counts_sql(product_id:, limit:, column: :larger_product_id, mirror_column: :smaller_product_id)}) SQL end def self.one_sided_related_product_ids_and_sales_counts_sql(product_id:, limit:, column:, mirror_column:) <<~SQL select #{mirror_column} as product_id, sales_count from #{table_name} where #{column} = #{product_id} order by sales_count desc limit #{limit} SQL end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/collaborator.rb
app/models/collaborator.rb
# frozen_string_literal: true class Collaborator < Affiliate MIN_PERCENT_COMMISSION = 1 MAX_PERCENT_COMMISSION = 50 belongs_to :seller, class_name: "User" has_one :collaborator_invitation, dependent: :destroy validates :seller_id, uniqueness: { scope: [:affiliate_user_id, :deleted_at] }, unless: :deleted? validates :affiliate_basis_points, presence: true, if: -> { apply_to_all_products? } validates :affiliate_basis_points, numericality: { greater_than_or_equal_to: MIN_PERCENT_COMMISSION * 100, less_than_or_equal_to: MAX_PERCENT_COMMISSION * 100, allow_nil: true } validate :collaborator_does_not_require_approval, if: :affiliate_user_changed? validate :eligible_for_stripe_payments scope :invitation_accepted, -> { where.missing(:collaborator_invitation) } scope :invitation_pending, -> { joins(:collaborator_invitation) } def as_json(*) { id: external_id, email: affiliate_user.email, name: affiliate_user.display_name(prefer_email_over_default_username: true), avatar_url: affiliate_user.avatar_url, apply_to_all_products:, percent_commission: affiliate_percentage, setup_incomplete: !affiliate_user.has_valid_payout_info?, dont_show_as_co_creator:, invitation_accepted: invitation_accepted?, } end def invitation_accepted? collaborator_invitation.blank? end def mark_deleted! super products.each { _1.update!(is_collab: false) } end def basis_points(product_id: nil) return affiliate_basis_points if product_id.blank? product_affiliates.find_by(link_id: product_id)&.affiliate_basis_points || affiliate_basis_points end def show_as_co_creator_for_product?(product) apply_to_all_products? ? !dont_show_as_co_creator? : !product_affiliates.find_by(link_id: product.id).dont_show_as_co_creator? end private def collaborator_does_not_require_approval if affiliate_user&.require_collab_request_approval? errors.add(:base, "You cannot add this user as a collaborator") end end def eligible_for_stripe_payments super return unless seller.present? && seller.has_brazilian_stripe_connect_account? errors.add(:base, "You cannot add a collaborator because you are using a Brazilian Stripe account.") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/transcoded_video.rb
app/models/transcoded_video.rb
# frozen_string_literal: true class TranscodedVideo < ApplicationRecord include FlagShihTzu, Deletable, CdnDeletable self.ignored_columns += [:product_file_id] has_paper_trail belongs_to :link, optional: true delegated_type :streamable, types: %w[ProductFile], optional: true validates_presence_of :original_video_key, :transcoded_video_key before_save :assign_default_last_accessed_at has_flags 1 => :is_hls, 2 => :via_grmc, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false state_machine(:state, initial: :processing) do event :mark_completed do transition processing: :completed end event :mark_error do transition processing: :error end end scope :completed, -> { where(state: "completed") } scope :processing, -> { where(state: "processing") } scope :s3, -> { } # assume they're all on S3 (needed for CdnDeletable) def mark(state) send("mark_#{state}") end def filename # filename is irrelevant for hls since we don't allow hls transcoded videos to be downloaded. is_hls? ? "" : transcoded_video_key.split("/").last end # note: when updating, last_accessed_at should be set to the same value for all the same transcoded_video_key def assign_default_last_accessed_at self.last_accessed_at ||= Time.current end def has_alive_duplicate_files? TranscodedVideo.alive.where(transcoded_video_key:).exists? end def mark_deleted! super if streamable&.is_transcoded_for_hls? && !has_alive_duplicate_files? streamable.update!(is_transcoded_for_hls: false) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/email_event.rb
app/models/email_event.rb
# frozen_string_literal: true class EmailEvent include Mongoid::Document include Mongoid::Timestamps EMAIL_DIGEST_LENGTH = 12 STALE_RECIPIENT_THRESHOLD_DAYS = 365 STALE_RECIPIENT_UNOPENED_THRESHOLD = 10 private_constant :EMAIL_DIGEST_LENGTH, :STALE_RECIPIENT_THRESHOLD_DAYS, :STALE_RECIPIENT_UNOPENED_THRESHOLD index({ email_digest: 1 }, { name: "email_digest_index" }) index({ first_unopened_email_sent_at: 1 }, { name: "first_unopened_email_sent_at_index" }) index({ marked_as_stale_at: 1 }, { name: "marked_as_stale_at_index" }) field :email_digest, type: String field :sent_emails_count, type: Integer, default: 0 field :unopened_emails_count, type: Integer, default: 0 field :open_count, type: Integer, default: 0 field :click_count, type: Integer, default: 0 field :first_unopened_email_sent_at, type: DateTime field :last_email_sent_at, type: DateTime field :last_opened_at, type: DateTime field :last_clicked_at, type: DateTime field :marked_as_stale_at, type: DateTime def self.log_send_events(emails, timestamp) return if Feature.inactive?(:log_email_events) operations = Array.wrap(emails).map do |email| { update_one: { filter: { email_digest: email_sha_digest(email) }, update: { "$inc" => { sent_emails_count: 1, unopened_emails_count: 1 }, "$set" => { last_email_sent_at: timestamp }, "$setOnInsert" => { first_unopened_email_sent_at: timestamp } }, upsert: true, } } end self.collection.bulk_write(operations, ordered: false) end def self.log_open_event(email, timestamp) return if Feature.inactive?(:log_email_events) event = self.find_by(email_digest: email_sha_digest(email)) return unless event.present? event.open_count += 1 event.unopened_emails_count = 0 event.first_unopened_email_sent_at = nil event.last_opened_at = timestamp event.save! end def self.log_click_event(email, timestamp) return if Feature.inactive?(:log_email_events) event = self.find_by(email_digest: email_sha_digest(email)) return unless event.present? event.click_count += 1 event.last_clicked_at = timestamp event.save! end def self.email_sha_digest(email) Digest::SHA1.hexdigest(email).first(EMAIL_DIGEST_LENGTH) end def self.stale_recipient?(email) event = self.find_by(email_digest: email_sha_digest(email)) return false if event.nil? return false if event.first_unopened_email_sent_at.nil? return false if event.first_unopened_email_sent_at > STALE_RECIPIENT_THRESHOLD_DAYS.days.ago return false if event.last_clicked_at.present? && event.last_clicked_at > STALE_RECIPIENT_THRESHOLD_DAYS.days.ago event.unopened_emails_count >= STALE_RECIPIENT_UNOPENED_THRESHOLD end def self.mark_as_stale(email, timestamp) event = self.find_by(email_digest: email_sha_digest(email)) return unless event.present? event.marked_as_stale_at = timestamp event.save! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_sales_tax_info.rb
app/models/purchase_sales_tax_info.rb
# frozen_string_literal: true class PurchaseSalesTaxInfo < ApplicationRecord belongs_to :purchase, optional: true end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/processor_payment_intent.rb
app/models/processor_payment_intent.rb
# frozen_string_literal: true class ProcessorPaymentIntent < ApplicationRecord belongs_to :purchase validates_uniqueness_of :purchase validates_presence_of :intent_id end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/url_redirect.rb
app/models/url_redirect.rb
# frozen_string_literal: true class UrlRedirect < ApplicationRecord include ExternalId include SignedUrlHelper include FlagShihTzu # Note: SendPostBlastEmailsJob bypasses all validations and callbacks when creating records. before_validation :set_token validates :token, uniqueness: { case_sensitive: true }, presence: true belongs_to :purchase, optional: true belongs_to :link, optional: true belongs_to :installment, optional: true belongs_to :subscription, optional: true belongs_to :preorder, optional: true belongs_to :imported_customer, optional: true has_many :stamped_pdfs has_many :alive_stamped_pdfs, -> { alive }, class_name: "StampedPdf" delegate :rental_expired?, to: :purchase, allow_nil: true has_flags 1 => :has_been_seen, 2 => :admin_generated, 3 => :is_rental, 4 => :is_done_pdf_stamping, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false TIME_TO_WATCH_RENTED_PRODUCT_AFTER_PURCHASE = 30.days TIME_TO_WATCH_RENTED_PRODUCT_AFTER_FIRST_PLAY = 72.hours FAKE_VIDEO_URL_GUID_FOR_OBFUSCATION = "ef64f2fef0d6c776a337050020423fc0" GUID_GETTER_FROM_S3_URL_REGEX = %r{attachments/(.*)/original} # Public: If one exists, returns the product that this UrlRedirect is associated to, directly or indirectly. Otherwise nil is returned. def referenced_link if purchase.present? purchase.link elsif imported_customer.present? imported_customer.link elsif link.present? link elsif installment.present? installment.link end end # Public: Returns the WithProductFiles object that has the content that this UrlRedirect is responsible for delivering. def with_product_files return installment if installment.present? && installment.has_files? return purchase.variant_attributes.order(deleted_at: :asc).first if has_purchased_variants_from_categories_with_files? || has_purchased_variants_from_categories_with_rich_content? referenced_link end def rich_content_json json = rich_content_provider&.rich_content_json commission = purchase&.commission if commission&.is_completed? json ||= [] json << ( { id: "", page_id: "", title: "Downloads", variant_id: nil, description: { type: "doc", content: commission.files.map do |file| { type: "fileEmbed", attrs: { id: file.signed_id, } } end, }, updated_at: commission.updated_at, } ) end json end def has_embedded_posts? rich_content_provider&.alive_rich_contents&.any?(&:has_posts?) || false end def entity_archive return if with_product_files.has_stampable_pdfs? product_files_archives.latest_ready_entity_archive end def folder_archive(folder_id) return if with_product_files.has_stampable_pdfs? product_files_archives.latest_ready_folder_archive(folder_id) end def alive_product_files return @cached_alive_product_files if @cached_alive_product_files @cached_alive_product_files = if installment.present? && installment.has_files? installment.product_files.alive.in_order elsif rich_content_provider.present? rich_content_provider.product_files.alive.ordered_by_ids(rich_content_provider.alive_rich_contents.flat_map(&:embedded_product_file_ids_in_order)) elsif purchase.present? && has_purchased_variants_from_categories_with_files? file_ids = purchase.variant_attributes.reduce([]) do |all_file_ids, version_option| all_file_ids + version_option.product_files.alive.pluck(:id) end.uniq ProductFile.where(id: file_ids).in_order else referenced_link.product_files.alive.in_order end @cached_alive_product_files end def product_files_archives @_cached_product_files_archives ||= (rich_content_provider.presence || with_product_files).product_files_archives end # Public: used to pass the list of downloadable files to Dropbox. def product_files_hash alive_product_files.map do |product_file| next if product_file.stream_only? { url: signed_location_for_file(product_file), filename: product_file.s3_filename } end.compact.to_json end def seller with_product_files.user end def redirect_or_s3_location if preorder.present? signed_download_url_for_s3_key_and_filename(preorder.preorder_link.s3_key, preorder.preorder_link.s3_filename) elsif alive_product_files.count == 1 signed_location_for_file(alive_product_files.first) else download_page_url end end def signed_location_for_file(product_file) return product_file.url if product_file.external_link? s3_retrievable = product_file if product_file.must_be_pdf_stamped? stamped_s3_retrievable = alive_stamped_pdfs.where(product_file_id: product_file.id).first s3_retrievable = stamped_s3_retrievable if stamped_s3_retrievable.present? end s3_key = s3_retrievable.s3_key s3_filename = s3_retrievable.s3_filename signed_download_url_for_s3_key_and_filename(s3_key, s3_filename, is_video: product_file.streamable?) end def product_file(product_file_external_id) alive_product_files.find_by_external_id(product_file_external_id) if product_file_external_id.present? end def missing_stamped_pdf?(product_file) !alive_stamped_pdfs.where(product_file_id: product_file.id).exists? end def url "#{PROTOCOL}://#{DOMAIN}/r/#{token}" end def download_page_url "#{PROTOCOL}://#{DOMAIN}/d/#{token}" end def read_url "#{PROTOCOL}://#{DOMAIN}/read/#{token}" end def stream_url "#{PROTOCOL}://#{DOMAIN}/s/#{token}" end def mark_as_seen self.has_been_seen = true save! end def mark_unseen self.has_been_seen = false save! end def smil_xml_for_product_file(product_file) smil_xml = ::Builder::XmlMarkup.new smil_xml.smil do |smil| smil.body do |body| body.switch do |switch| s3_path = product_file.s3_key switch.video(src: signed_cloudfront_url(s3_path, is_video: true)) end end end end def video_files_playlist(initial_product_file) video_files_playlist = { playlist: [], index_to_play: 0 } alive_product_files.each do |product_file| next unless product_file.streamable? video_url, guid = html5_video_url_and_guid_for_product_file(product_file) video_data = { sources: [hls_playlist_or_smil_xml_path(product_file), video_url] } video_data[:guid] = guid video_data[:title] = product_file.name_displayable video_data[:tracks] = product_file.subtitle_files_urls video_data[:external_id] = product_file.try(:external_id) video_data[:latest_media_location] = product_file.latest_media_location_for(purchase) video_data[:content_length] = product_file.content_length video_files_playlist[:playlist] << video_data video_files_playlist[:index_to_play] = video_files_playlist[:playlist].size.pred if product_file == initial_product_file end video_files_playlist end def html5_video_url_and_guid_for_product_file(product_file) video_url = signed_video_url(product_file) # We replace the GUID of the video URL with a fake guid and put the resulting URL in the DOM, along with the real GUID. # On the client-side we do the opposite replacement and generate the real URL in js and pass that to JWPlayer. # This way we won't have the signed URL for the video file in the DOM. This simply makes it somewhat harder to download the video file. guid = video_url[GUID_GETTER_FROM_S3_URL_REGEX, 1] [video_url.sub(guid, FAKE_VIDEO_URL_GUID_FOR_OBFUSCATION), guid] end def hls_playlist_or_smil_xml_path(product_file) path_method = if product_file.is_transcoded_for_hls :hls_playlist_for_product_file_path else :url_redirect_smil_for_product_file_path end Rails.application.routes.url_helpers.public_send(path_method, token, product_file.external_id) end def signed_video_url(s3_retrievable) signed_download_url_for_s3_key_and_filename(s3_retrievable.s3_key, s3_retrievable.s3_filename, is_video: true) end def product_json_data result = referenced_link.as_json(mobile: true).merge(url_redirect_external_id: external_id, url_redirect_token: token) result[:file_data] = product_file_json_data_for_mobile unless purchase.present? && purchase.subscription.present? && !purchase.subscription.alive? purchase = self.purchase if purchase result[:purchase_id] = purchase.external_id result[:purchased_at] = purchase.created_at result[:user_id] = purchase.purchaser.external_id if purchase.purchaser result[:product_updates_data] = purchase.update_json_data_for_mobile result[:is_archived] = purchase.is_archived result[:custom_delivery_url] = nil # Deprecated end result end def product_unique_permalink referenced_link.unique_permalink end def is_file_downloadable?(product_file) return false if product_file.external_link? return false if product_file.stream_only? return false if product_file.streamable? && is_rental true end def mark_rental_as_viewed! update!(rental_first_viewed_at: Time.current) if is_rental && rental_first_viewed_at.nil? end # Mobile specific methods def product_file_json_data_for_mobile alive_product_files.map do |file| mobile_product_file_json_data(file) end end def mobile_product_file_json_data(file) product_file_mobile_json_data = file.mobile_json_data if is_file_downloadable?(file) download_url = Rails.application.routes.url_helpers.api_mobile_download_product_file_url(token, file.external_id, host: UrlService.api_domain_with_protocol) download_url += "?mobile_token=#{Api::Mobile::BaseController::MOBILE_TOKEN}" product_file_mobile_json_data[:download_url] = download_url end product_file_mobile_json_data[:latest_media_location] = file.latest_media_location_for(purchase) product_file_mobile_json_data[:content_length] = file.content_length product_file_mobile_json_data[:streaming_url] = Rails.application.routes.url_helpers.api_mobile_stream_video_url(token, file.external_id, host: UrlService.api_domain_with_protocol) if file.streamable? product_file_mobile_json_data[:external_link_url] = file.url if file.external_link? product_file_mobile_json_data end def self.generate_new_token SecureRandom.hex end def enqueue_job_to_regenerate_deleted_stamped_pdfs return if purchase.blank? stampable_files = alive_product_files.pdf_stamp_enabled.pluck(:id) return if stampable_files.empty? stamped_files = alive_stamped_pdfs.pluck(:product_file_id) missing = stampable_files - stamped_files return if missing.empty? deleted = stamped_pdfs.deleted.distinct.pluck(:product_file_id) missing_because_deleted = missing & deleted return if missing_because_deleted.empty? Rails.logger.info("[url_redirect=#{id}, purchase=#{purchase_id}] Stamped PDFs for files #{missing_because_deleted.join(", ")} were deleted, enqueuing job to regenerate them") StampPdfForPurchaseJob.perform_async(purchase_id) end def update_transcoded_videos_last_accessed_at videos_ids = alive_product_files.select { _1.filegroup == "video" }.map(&:id) return if videos_ids.empty? now = Time.current videos_ids.each_slice(1_000) do |slice| TranscodedVideo.alive .product_files .where(streamable_id: slice) .update_all(last_accessed_at: now) end end def enqueue_job_to_regenerate_deleted_transcoded_videos videos_ids = alive_product_files.select { _1.filegroup == "video" }.map(&:id) return if videos_ids.empty? alive = videos_ids.each_slice(1_000).flat_map do |slice| TranscodedVideo.alive .product_files .where(streamable_id: slice) .pluck(:streamable_id) end missing = (videos_ids - alive).uniq missing_because_deleted = ProductFile.where(id: missing) .joins(:transcoded_videos) .merge(TranscodedVideo.deleted.completed) .distinct .select(&:transcodable?) missing_because_deleted.each_with_index do |product_file, i| delay = 5.minutes * i TranscodeVideoForStreamingWorker.perform_in(delay, product_file.id, product_file.class.name) end end private def set_token self.token ||= self.class.generate_new_token end def rich_content_provider return @_rich_content_provider if instance_variable_defined?(:@_rich_content_provider) @_rich_content_provider = nil entity = with_product_files return if entity.blank? || entity.is_a?(Installment) @_rich_content_provider = if should_refer_to_product_level_rich_content_of_purchased_variant?(entity) entity.link elsif entity.is_a?(Link) || (entity.is_a?(BaseVariant) && entity.deleted?) product_or_cheapest_variant_as_rich_content_provider(entity) else entity end @_rich_content_provider end def has_purchased_variants_from_categories_with_files? return false unless purchase purchase.variant_attributes.any? do |variant| variant.is_a?(Variant) && (variant.has_files? || (variant.variant_category && variant.variant_category.variants.alive.any?(&:has_files?))) end end def has_purchased_variants_from_categories_with_rich_content? return false unless purchase purchase.variant_attributes.any? { _1.is_a?(Variant) } end def should_refer_to_product_level_rich_content_of_purchased_variant?(entity) return false unless entity.is_a?(BaseVariant) entity.link&.has_same_rich_content_for_all_variants? || false end def product_or_cheapest_variant_as_rich_content_provider(entity) product = entity.is_a?(BaseVariant) ? entity.link : entity return product if product.is_physical? || product.has_same_rich_content_for_all_variants? || product.rich_content_json.present? || product.alive_variants.none? product.alive_variants.order(price_difference_cents: :asc).first end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/cart_product.rb
app/models/cart_product.rb
# frozen_string_literal: true class CartProduct < ApplicationRecord include ExternalId include Deletable URL_PARAMETERS_JSON_SCHEMA = { type: "object", additionalProperties: { type: "string" } }.freeze ACCEPTED_OFFER_DETAILS_JSON_SCHEMA = { type: "object", properties: { original_product_id: { type: ["string", "null"] }, original_variant_id: { type: ["string", "null"] }, }, additionalProperties: false, }.freeze belongs_to :cart, touch: true belongs_to :product, class_name: "Link" belongs_to :option, class_name: "BaseVariant", optional: true belongs_to :affiliate, optional: true belongs_to :accepted_offer, class_name: "Upsell", optional: true after_initialize :assign_default_values validates :price, :quantity, :referrer, presence: true validate :ensure_url_parameters_conform_to_schema validate :ensure_accepted_offer_details_conform_to_schema private def assign_default_values self.url_parameters = {} if url_parameters.nil? self.accepted_offer_details = {} if accepted_offer_details.nil? end def ensure_url_parameters_conform_to_schema JSON::Validator.fully_validate(URL_PARAMETERS_JSON_SCHEMA, url_parameters).each { errors.add(:url_parameters, _1) } end def ensure_accepted_offer_details_conform_to_schema JSON::Validator.fully_validate(ACCEPTED_OFFER_DETAILS_JSON_SCHEMA, accepted_offer_details).each { errors.add(:accepted_offer_details, _1) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bundle_product.rb
app/models/bundle_product.rb
# frozen_string_literal: true class BundleProduct < ApplicationRecord include Deletable, ExternalId has_paper_trail belongs_to :bundle, class_name: "Link" belongs_to :product, class_name: "Link" belongs_to :variant, class_name: "BaseVariant", optional: true validate :product_belongs_to_bundle_seller validate :versioned_product_has_variant validate :variant_belongs_to_product validate :product_is_not_bundle validate :product_is_not_subscription validate :product_is_not_call validate :is_not_duplicate validate :bundle_is_bundle_product validate :product_is_eligible_for_installment_plan attribute :quantity, default: 1 scope :in_order, -> { order(position: :asc) } def standalone_price_cents (product.price_cents + (variant&.price_difference_cents || 0)) * quantity end def eligible_for_installment_plans? # This method determines if a product can be included in a bundle that # offers installment plans. While it currently delegates to the product's # own eligibility check, the criteria may differ in the future. For # example, while installment plans explicitly reject "pay what you want" # pricing, but a PWYW product could still be part of a fixed-price bundle # with installment plans. product.eligible_for_installment_plans? end private def product_belongs_to_bundle_seller if bundle.user != product.user errors.add(:base, "The product must belong to the bundle's seller") end end def versioned_product_has_variant if (product.skus_enabled && product.skus.alive.not_is_default_sku.count > 1) || product.alive_variants.present? if variant.blank? errors.add(:base, "Bundle product must have variant specified for versioned product") end end end def variant_belongs_to_product if variant.present? && variant.link != product errors.add(:base, "The bundle product's variant must belong to its product") end end def product_is_not_bundle if product.is_bundle errors.add(:base, "A bundle product cannot be added to a bundle") end end def product_is_not_subscription if product.is_recurring_billing errors.add(:base, "A subscription product cannot be added to a bundle") end end def product_is_not_call if product.native_type == Link::NATIVE_TYPE_CALL errors.add(:base, "A call product cannot be added to a bundle") end end def is_not_duplicate if bundle.bundle_products.where(product_id:).where.not(id:).present? errors.add(:base, "Product is already in bundle") end end def bundle_is_bundle_product if bundle.not_is_bundle? errors.add(:base, "Bundle products can only be added to bundles") end end def product_is_eligible_for_installment_plan return if bundle.installment_plan.blank? return if eligible_for_installment_plans? errors.add(:base, "Installment plan is not available for the bundled product: #{product.name}") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/gift.rb
app/models/gift.rb
# frozen_string_literal: true class Gift < ApplicationRecord include FlagShihTzu stripped_fields :gifter_email, :giftee_email belongs_to :gifter_purchase, class_name: "Purchase", optional: true belongs_to :giftee_purchase, class_name: "Purchase", optional: true belongs_to :link, optional: true validates :giftee_email, presence: true, email_format: true validates :gifter_email, presence: true, email_format: true has_flags 1 => :is_recipient_hidden state_machine(:state, initial: :in_progress) do before_transition in_progress: :successful, do: :everything_successful? event :mark_successful do transition in_progress: :successful end event :mark_failed do transition in_progress: :failed end end scope :successful, -> { where(state: "successful") } private def everything_successful? gifter_purchase.present? && giftee_purchase.present? && gifter_purchase.successful? && giftee_purchase.gift_receiver_purchase_successful? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/installment_rule.rb
app/models/installment_rule.rb
# frozen_string_literal: true class InstallmentRule < ApplicationRecord has_paper_trail version: :paper_trail_version include Deletable belongs_to :installment, optional: true # To show the proper time period to a user, we need to store this. # To a user, they should see "1 week" instead of "7 days." HOUR = "hour" DAY = "day" WEEK = "week" MONTH = "month" ABANDONED_CART_DELAYED_DELIVERY_TIME_IN_SECONDS = 24.hours.to_i validates_presence_of :installment, :version validate :to_be_published_at_cannot_be_in_the_past validate :to_be_published_at_must_exist_for_non_workflow_posts # We increment the version when delivery date changes so the correct job is processed, not an old one. We have the version starting # at 1 even though the schema shows a default value of 0. If there is no rule to go with an installment, we pass version = 0 as a # parameter so changing version to start at 0 will disrupt current installment jobs in the queue. before_save :increment_version, if: :delivery_date_changed? # Public: Converts the delayed_delivery_time back into the number the creator entered using the time period of the rule # # Examples # delayed_delivery_time = 432000, time_period = "DAY" # displayable_time_duration # #=> 5 # delayed_delivery_time = 72000, time_period = "HOUR" # displayable_time_duration # # => 20 # # Returns an integer def displayable_time_duration case time_period when HOUR period = 1.hour when DAY period = 1.day when WEEK period = 1.week when MONTH period = 1.month end (delayed_delivery_time / period).to_i end private # Private: Increments version of InstallmentRule. This is so PublishInstallment jobs are ignored if the version of the job does not match the # most recent version of the InstallmentRule. We want to update the version every time the creator changes when it is scheduled. def increment_version self[:version] = version + 1 end def delivery_date_changed? delayed_delivery_time_changed? || to_be_published_at_changed? end def to_be_published_at_must_exist_for_non_workflow_posts return if installment.blank? return if installment.workflow.present? return if to_be_published_at.present? errors.add(:base, "Please select a date and time in the future.") end def to_be_published_at_cannot_be_in_the_past return if deleted_at_changed? return if to_be_published_at.blank? return if to_be_published_at > Time.current errors.add(:base, "Please select a date and time in the future.") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/tanzania_bank_account.rb
app/models/tanzania_bank_account.rb
# frozen_string_literal: true class TanzaniaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "TZ" BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/ ACCOUNT_NUMBER_FORMAT_REGEX = /^[a-zA-Z0-9]{10,14}$/ private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::TZA.alpha2 end def currency Currency::TZS end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/philippines_bank_account.rb
app/models/philippines_bank_account.rb
# frozen_string_literal: true class PhilippinesBankAccount < BankAccount BANK_ACCOUNT_TYPE = "PH" BANK_CODE_FORMAT_REGEX = /\A[A-Za-z0-9]{8,11}\z/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{1,17}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::PHL.alpha2 end def currency Currency::PHP end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/european_bank_account.rb
app/models/european_bank_account.rb
# frozen_string_literal: true class EuropeanBankAccount < BankAccount BANK_ACCOUNT_TYPE = "EU" # On sandbox, the test IBAN numbers are of same length for all countries # (ref: https://stripe.com/docs/connect/testing#account-numbers), # so validating this only for production. validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country ISO3166::Country[account_number_decrypted[0, 2]].alpha2 end def currency Currency::EUR end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_review.rb
app/models/product_review.rb
# frozen_string_literal: true class ProductReview < ApplicationRecord include ExternalId, Deletable PRODUCT_RATING_RANGE = (1..5) REVIEW_REMINDER_DELAY = 5.days REVIEW_REMINDER_PHYSICAL_DELAY = 90.days RestrictedOperationError = Class.new(StandardError) belongs_to :link, optional: true belongs_to :purchase, optional: true has_one :response, class_name: "ProductReviewResponse" has_many :videos, dependent: :destroy, class_name: "ProductReviewVideo" has_many :alive_videos, -> { alive }, class_name: "ProductReviewVideo" has_one :approved_video, -> { alive.approved.latest }, class_name: "ProductReviewVideo" has_one :pending_video, -> { alive.pending_review.latest }, class_name: "ProductReviewVideo" has_one :editable_video, -> { alive.editable.latest }, class_name: "ProductReviewVideo" scope :visible_on_product_page, -> { left_joins(:approved_video) .where("product_reviews.has_message = true OR product_review_videos.id IS NOT NULL") } validates_presence_of :purchase validates_presence_of :link validates_uniqueness_of :purchase_id validates_inclusion_of :rating, in: PRODUCT_RATING_RANGE, message: "Invalid product rating." validate :message_cannot_contain_adult_keywords, if: :message_changed? before_create do next if purchase.allows_review_to_be_counted? raise RestrictedOperationError.new("Creating a review for an invalid purchase is not handled") end before_update do next if !rating_changed? || purchase.allows_review_to_be_counted? raise RestrictedOperationError.new("A rating on a invalid purchase can't be changed") end before_destroy do raise RestrictedOperationError.new("Updating stats when destroying review is not handled") end after_save :update_product_review_stat after_create_commit :notify_seller private def update_product_review_stat return if rating_previous_change.nil? link.update_review_stat_via_rating_change(*rating_previous_change) end def message_cannot_contain_adult_keywords errors.add(:base, "Adult keywords are not allowed") if AdultKeywordDetector.adult?(message) end def notify_seller return if link.user.disable_reviews_email? ContactingCreatorMailer.review_submitted(id).deliver_later end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/stripe_apple_pay_domain.rb
app/models/stripe_apple_pay_domain.rb
# frozen_string_literal: true class StripeApplePayDomain < ApplicationRecord belongs_to :user, optional: true validates_presence_of :user, :domain, :stripe_id end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/subscription_plan_change.rb
app/models/subscription_plan_change.rb
# frozen_string_literal: true # Represents a user-initiated plan change to a subscription, for example to # upgrade or downgrade their tier or recurrence. Used by `RecurringChargeWorker` # worker to check if a user has a plan change that must be made at the end of # the current billing period, before initiating the next recurring charge. class SubscriptionPlanChange < ApplicationRecord has_paper_trail include Deletable include CurrencyHelper include FlagShihTzu belongs_to :subscription belongs_to :tier, class_name: "BaseVariant", foreign_key: "base_variant_id", optional: true has_flags 1 => :for_product_price_change, 2 => :applied, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false validates :recurrence, presence: true validates :tier, presence: true, if: -> { subscription&.link&.is_tiered_membership? } validates :recurrence, inclusion: { in: BasePrice::Recurrence::ALLOWED_RECURRENCES } validates :perceived_price_cents, presence: true scope :applicable_for_product_price_change_as_of, ->(date) { alive.not_applied .for_product_price_change .where("effective_on <= ?", date) } scope :currently_applicable, -> { for_price_change = SubscriptionPlanChange.alive.not_applied .applicable_for_product_price_change_as_of(Date.today) .where.not(notified_subscriber_at: nil) not_for_price_change = SubscriptionPlanChange.alive.not_applied.not_for_product_price_change subquery_sqls = [for_price_change, not_for_price_change].map(&:to_sql) from("(" + subquery_sqls.join(" UNION ") + ") AS #{table_name}") } def formatted_display_price formatted_price_in_currency_with_recurrence( perceived_price_cents, subscription.link.price_currency_type, recurrence, subscription.charge_occurrence_count ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/nigeria_bank_account.rb
app/models/nigeria_bank_account.rb
# frozen_string_literal: true class NigeriaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "NG" BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{10}$/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::NGA.alpha2 end def currency Currency::NGN end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/romania_bank_account.rb
app/models/romania_bank_account.rb
# frozen_string_literal: true class RomaniaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "RO" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::ROU.alpha2 end def currency Currency::RON end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/device.rb
app/models/device.rb
# frozen_string_literal: true class Device < ApplicationRecord DEVICE_TYPES = { ios: "ios", android: "android" } APP_TYPES = { consumer: "consumer", creator: "creator" } NOTIFICATION_SOUNDS = { sale: "chaching.wav" } belongs_to :user validates_presence_of :token validates :device_type, presence: true, inclusion: DEVICE_TYPES.values validates :app_type, presence: true, inclusion: APP_TYPES.values before_save :delete_token_if_already_linked_with_other_user private def delete_token_if_already_linked_with_other_user if token.present? Device.where(token:, device_type:).where.not(id:).destroy_all end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_refund_policy.rb
app/models/purchase_refund_policy.rb
# frozen_string_literal: true class PurchaseRefundPolicy < ApplicationRecord belongs_to :purchase has_one :link, through: :purchase has_one :product_refund_policy, through: :link stripped_fields :title, :fine_print validates :purchase, uniqueness: true validates :title, presence: true # This is the date when we switched to product-level refund policies, and started enforcing # ProductRefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS (which defines the value for policy title) # Before that, the policy title was free form, and there are still records pre-2025-04-10 that don't have a # max_refund_period_in_days set (couldn't be matched to one of the allowed values) # This validation is mostly to ensure new records have this value set. # # One way to clean up this technical debt is to set the max_refund_period_in_days to the maximum allowed value (183) # for all records pre-2025-04-10 that don't have a max_refund_period_in_days set. # Attention: some products offered more than 183 (6 months) refund policies, and any change to those policies may # require customer communication. MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON = Time.zone.parse("2025-04-10") validates :max_refund_period_in_days, presence: true, if: -> { (created_at || Time.current) > MAX_REFUND_PERIOD_IN_DAYS_INTRODUCED_ON } def different_than_product_refund_policy? return true if product_refund_policy.blank? if max_refund_period_in_days.present? max_refund_period_in_days != product_refund_policy.max_refund_period_in_days else title != product_refund_policy.title end end def determine_max_refund_period_in_days previous_value = determine_max_refund_period_in_days_from_previous_policy return previous_value if previous_value.present? return 0 if title.match?(/no refunds|final|no returns/i) exact_match = find_exact_match_by_title return exact_match if exact_match begin response = ask_ai(max_refund_period_in_days_prompt) days = Integer(response.dig("choices", 0, "message", "content")) rescue response.dig("choices", 0, "message", "content") # Return only values from ALLOWED_REFUND_PERIODS_IN_DAYS or nil for unmatched titles if RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.key?(days) days else Rails.logger.debug("Unknown refund period for policy #{id}: #{days}") nil end rescue => e Rails.logger.debug("Error determining max refund period for policy #{id}: #{e.message}") nil end end def max_refund_period_in_days_prompt prompt = <<~PROMPT You are an expert content reviewer that responds in numbers only. Your role is to determine the maximum number of days allowed for a refund policy based on the refund policy title & fine print. If the refund policy or fine print has words like "no refunds", "refunds not allowed", "no returns", "returns not allowed", "final" etc.), it's a no-refunds policy. The allowed number of days are 0 (no refunds allowed), 7, 14, 30, or 183 (6 months). Determine the number of days that match EXACTLY what the current refund policy mentions. Example 1: If the title is "30-day money back guarantee", return 30. Example 2: If from the fine print it clearly states that there are no refunds, return 0. Example 3: If the analysis determines that it is a 7-day refund policy, return 7. Example 4: If the analysis determines that it is a 2-month refund policy, return -1. Example 5: If the analysis determines that it is a 1-year refund policy, return -1. Return one of the allowed numbers only if you are 100% confident. If you are not 100% confident, return -1. The response MUST be just a number. The only allowed numbers are: -1, 0, 7, 14, 30, 183. Purchase ID: #{purchase.id} Refund policy title: #{title} PROMPT if fine_print.present? prompt += <<~FINE_PRINT <refund policy fine print> #{fine_print.truncate(300)} </refund policy fine print> FINE_PRINT end prompt end # Avoid calling AI if possible by checking the product refund policy, and previous purchase refund policies def determine_max_refund_period_in_days_from_previous_policy return product_refund_policy.max_refund_period_in_days if product_refund_policy&.title == title other_purchase_refund_policy = PurchaseRefundPolicy.joins(:purchase).where(purchases: { link_id: purchase.link_id }).where.not(id: id).where(title:).first return other_purchase_refund_policy.max_refund_period_in_days if other_purchase_refund_policy.present? nil end private def ask_ai(prompt) OpenAI::Client.new.chat( parameters: { messages: [{ role: "user", content: prompt }], model: "gpt-4o-mini", temperature: 0.0, max_tokens: 10 } ) end private def find_exact_match_by_title RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.each do |days, policy_title| return days if title.downcase.strip == policy_title.downcase.strip end nil end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/guatemala_bank_account.rb
app/models/guatemala_bank_account.rb
# frozen_string_literal: true class GuatemalaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "GT" BANK_CODE_FORMAT_REGEX = /^[A-Za-z0-9]{8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::GTM.alpha2 end def currency Currency::GTQ end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/global_affiliate.rb
app/models/global_affiliate.rb
# frozen_string_literal: true class GlobalAffiliate < Affiliate AFFILIATE_COOKIE_LIFETIME_DAYS = 7 AFFILIATE_BASIS_POINTS = 1000 validates :affiliate_user_id, uniqueness: true validates :affiliate_basis_points, presence: true before_validation :set_affiliate_basis_points, unless: :persisted? def self.cookie_lifetime AFFILIATE_COOKIE_LIFETIME_DAYS.days end def final_destination_url(product: nil) product.present? ? product.long_url : Rails.application.routes.url_helpers.discover_url(Affiliate::SHORT_QUERY_PARAM => external_id_numeric, host: UrlService.discover_domain_with_protocol) end def eligible_for_purchase_credit?(product:, **opts) eligible_for_credit? && product.recommendable? && opts[:purchaser_email] != affiliate_user.email && !product.user.disable_global_affiliate && !product.user.has_brazilian_stripe_connect_account? end private def set_affiliate_basis_points self.affiliate_basis_points = AFFILIATE_BASIS_POINTS end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/custom_field.rb
app/models/custom_field.rb
# frozen_string_literal: true class CustomField < ApplicationRecord include ExternalId, FlagShihTzu has_flags 1 => :is_post_purchase, 2 => :collect_per_product, column: "flags", flag_query_mode: :bit_operator, check_for_column: false belongs_to :seller, class_name: "User" has_many :purchase_custom_fields has_and_belongs_to_many :products, class_name: "Link", join_table: "custom_fields_products", association_foreign_key: "product_id" URI_REGEXP = /\A#{URI.regexp([%w[http https]])}\z/ TYPES = %w(text checkbox terms long_text file).freeze TYPES.each do |type| self.const_set("TYPE_#{type.upcase}", type) end alias_attribute :type, :field_type validates :field_type, inclusion: { in: TYPES } validates_presence_of :name validate :terms_valid_uri validate :type_not_boolean_if_post_purchase scope :global, -> { where(global: true) } BOOLEAN_TYPES = [TYPE_TERMS, TYPE_CHECKBOX].freeze FIELD_TYPE_TO_NODE_TYPE_MAPPING = { TYPE_TEXT => RichContent::SHORT_ANSWER_NODE_TYPE, TYPE_LONG_TEXT => RichContent::LONG_ANSWER_NODE_TYPE, TYPE_FILE => RichContent::FILE_UPLOAD_NODE_TYPE, }.freeze FILE_FIELD_NAME = "File upload" before_validation :set_default_name def as_json(*) { id: external_id, type:, name:, required:, global:, collect_per_product:, products: products.map(&:external_id) } end private def terms_valid_uri if field_type == TYPE_TERMS && !URI_REGEXP.match?(name) errors.add(:base, "Please provide a valid URL for custom field of Terms type.") end end def set_default_name self.name = FILE_FIELD_NAME if type == TYPE_FILE && name.blank? end def type_not_boolean_if_post_purchase if is_post_purchase? && BOOLEAN_TYPES.include?(field_type) errors.add(:base, "Boolean post-purchase fields are not allowed") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/norway_bank_account.rb
app/models/norway_bank_account.rb
# frozen_string_literal: true class NorwayBankAccount < BankAccount BANK_ACCOUNT_TYPE = "NO" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::NOR.alpha2 end def currency Currency::NOK end def account_number_visual "******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/utm_link_visit.rb
app/models/utm_link_visit.rb
# frozen_string_literal: true class UtmLinkVisit < ApplicationRecord has_paper_trail belongs_to :utm_link belongs_to :user, optional: true has_many :utm_link_driven_sales, dependent: :destroy has_many :purchases, through: :utm_link_driven_sales validates :ip_address, presence: true validates :browser_guid, presence: true end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/community.rb
app/models/community.rb
# frozen_string_literal: true class Community < ApplicationRecord include Deletable include ExternalId belongs_to :seller, class_name: "User" belongs_to :resource, polymorphic: true has_many :community_chat_messages, dependent: :destroy has_many :last_read_community_chat_messages, dependent: :destroy has_many :community_chat_recaps, dependent: :destroy validates :seller_id, uniqueness: { scope: [:resource_id, :resource_type, :deleted_at] } def name = resource.name def thumbnail_url resource.for_email_thumbnail_url end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/custom_domain.rb
app/models/custom_domain.rb
# frozen_string_literal: true require "ipaddr" class CustomDomain < ApplicationRecord WWW_PREFIX = "www" MAX_FAILED_VERIFICATION_ATTEMPTS_COUNT = 3 include Deletable stripped_fields :domain, transform: -> { _1.downcase } belongs_to :user, optional: true belongs_to :product, class_name: "Link", optional: true validate :user_or_product_present validate :validate_domain_uniqueness validate :validate_domain_format validate :validate_domain_is_allowed before_save :reset_ssl_certificate_issued_at, if: :domain_changed? after_commit :generate_ssl_certificate, if: ->(custom_domain) { custom_domain.previous_changes[:domain].present? } scope :certificate_absent_or_older_than, -> (duration) { where("ssl_certificate_issued_at IS NULL OR ssl_certificate_issued_at < ?", duration.ago) } scope :certificates_younger_than, -> (duration) { where("ssl_certificate_issued_at > ?", duration.ago) } scope :verified, -> { with_state(:verified) } scope :unverified, -> { with_state(:unverified) } state_machine :state, initial: :unverified do after_transition unverified: :verified, do: ->(record) { record.failed_verification_attempts_count = 0 } after_transition verified: :unverified, do: :increment_failed_verification_attempts_count_and_notify_creator event :mark_verified do transition unverified: :verified end event :mark_unverified do transition verified: :unverified end end def validate_domain_uniqueness custom_domain = CustomDomain.find_by_host(domain) return if custom_domain.nil? || custom_domain == self errors.add(:base, "The custom domain is already in use.") end def validate_domain_format # LetsEncrypt allows only valid hostnames when generating SSL certificates # Ref: https://github.com/letsencrypt/boulder/pull/1437#issuecomment-533533967 if domain.blank? || !domain.match?(/\A[a-zA-Z0-9\-.]+[^.]\z/) || !PublicSuffix.valid?(domain) || ip_address?(domain) errors.add(:base, "#{domain} is not a valid domain name.") end end def validate_domain_is_allowed forbidden_suffixes = [DOMAIN, ROOT_DOMAIN, SHORT_DOMAIN, DISCOVER_DOMAIN, API_DOMAIN, INTERNAL_GUMROAD_DOMAIN].freeze forbidden_suffixes.each do |suffix| if domain == suffix || domain.to_s.ends_with?(".#{suffix}") return errors.add(:base, "#{domain} is not a valid domain name.") end end end def verify(allow_incrementing_failed_verification_attempts_count: true) self.allow_incrementing_failed_verification_attempts_count = allow_incrementing_failed_verification_attempts_count has_valid_configuration = CustomDomainVerificationService.new(domain:).process if has_valid_configuration mark_verified if unverified? else verified? ? mark_unverified : increment_failed_verification_attempts_count_and_notify_creator end end def self.find_by_host(host) return unless PublicSuffix.valid?(host) parsed_host = PublicSuffix.parse(host) if parsed_host.trd.nil? || parsed_host.trd == WWW_PREFIX alive.find_by(domain: parsed_host.domain) || alive.find_by(domain: "#{WWW_PREFIX}.#{parsed_host.domain}") else alive.find_by(domain: host) end end def reset_ssl_certificate_issued_at! self.ssl_certificate_issued_at = nil self.save! end def set_ssl_certificate_issued_at! self.ssl_certificate_issued_at = Time.current self.save! end def generate_ssl_certificate GenerateSslCertificate.perform_in(2.seconds, id) end def has_valid_certificate?(renew_certificate_in) ssl_certificate_issued_at.present? && ssl_certificate_issued_at > renew_certificate_in.ago end def exceeding_max_failed_verification_attempts? failed_verification_attempts_count >= MAX_FAILED_VERIFICATION_ATTEMPTS_COUNT end def active? verified? && has_valid_certificate?(1.week) end private attr_accessor :allow_incrementing_failed_verification_attempts_count def reset_ssl_certificate_issued_at self.ssl_certificate_issued_at = nil end def increment_failed_verification_attempts_count_and_notify_creator return unless allow_incrementing_failed_verification_attempts_count return if exceeding_max_failed_verification_attempts? increment(:failed_verification_attempts_count) end def user_or_product_present return if user.present? || product.present? errors.add(:base, "Requires an associated user or product.") end def ip_address?(domain) IPAddr.new(domain) true rescue IPAddr::InvalidAddressError false end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sweden_bank_account.rb
app/models/sweden_bank_account.rb
# frozen_string_literal: true class SwedenBankAccount < BankAccount BANK_ACCOUNT_TYPE = "SE" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::SWE.alpha2 end def currency Currency::SEK end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/resend_event_info.rb
app/models/resend_event_info.rb
# frozen_string_literal: true class ResendEventInfo < EmailEventInfo attr_reader \ :charge_id, :click_url, :email, :event_json, :installment_id, :mailer_class, :mailer_method, :mailer_args, :purchase_id, :workflow_ids, :type, :created_at # Sample payload # event_json = HashWithIndifferentAccess.new({ # "created_at": "2025-01-02T00:14:12.391Z", # "data": { # "created_at": "2025-01-02 00:14:11.140106+00", # "email_id": "7409b6f1-56f1-4ba5-89f0-4364a08b246e", # "from": "\"Razvan\" <noreply@staging.customers.gumroad.com>", # "headers": [ # { # "name": "X-Gum-Environment", # "value": "v1:T4Atudv1nP58+gprjqKMJA==:fGNbbVO69Zrw7kSnULg2mw==" # }, # { # "name": "X-Gum-Mailer-Class", # "value": "v1:4/KqqxSld7KZg35TizeOzg==:roev9VWcJg5De5uJ95tWbQ==" # }, # { # "name": "X-Gum-Mailer-Method", # "value": "v1:27cEW99BqALnRhqJcqq4yg==:JnxrbX321BGYsKX8wAANFg==" # }, # { # "name": "X-Gum-Mailer-Args", # "value": "v1:pqH9QUfHKV1VUURMgRzN6Q==:sDje7QqsyOWz9kH542EpEA==" # }, # { # "name": "X-Gum-Category", # "value": "v1:O85BjjvFY9LSq0ECcPnh0g==:7qblpHdeZxUdjTDM0XoSW/I3UIeKt8Cv41jTWssgmAcABmCfjtukxHl7RimCCSnD" # }, # { # "name": "X-Gum-Charge-ID", # "value": "v1:sI/i9tSEYbiXU3kcb7iF+Q==:5f1Ls/SJFFUF+6L6VZc7CQ==" # }, # { # "name": "X-Gum-Email-Provider", # "value": "resend" # }, # { # "name": "Reply-To", # "value": "gumroad@marescu.net" # } # ], # "subject": "You bought Prod with license!", # "to": [ # "gumroad+cust4@marescu.net" # ] # }, # "type": "email.delivered" # }) def self.from_event_json(event_json) new(event_json) end def initialize(event_json) @event_json = event_json @email = event_json["data"]["to"].first @click_url = event_json["data"].dig("click", "link") @mailer_class = parse_header_value(:mailer_class) @mailer_method = parse_header_value(:mailer_method) @mailer_args = parse_header_value(:mailer_args) @purchase_id = parse_header_value(:purchase_id) @charge_id = parse_header_value(:charge_id) @workflow_ids = parse_workflow_ids @type = TRACKED_EVENTS[MailerInfo::EMAIL_PROVIDER_RESEND].invert[event_json["type"]] @created_at = Time.zone.parse(event_json["data"]["created_at"]) @installment_id = parse_header_value(:post_id) end def invalid? type.blank? || mailer_class.blank? || mailer_method.blank? end def mailer_class_and_method "#{mailer_class}.#{mailer_method}" end def email_provider MailerInfo::EMAIL_PROVIDER_RESEND end private def parse_header_value(header_name) MailerInfo.parse_resend_webhook_header(event_json["data"]["headers"], header_name) end def parse_workflow_ids value = parse_header_value(:workflow_ids) return [] if value.blank? JSON.parse(value.to_s) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/dominican_republic_bank_account.rb
app/models/dominican_republic_bank_account.rb
# frozen_string_literal: true class DominicanRepublicBankAccount < BankAccount BANK_ACCOUNT_TYPE = "DO" BANK_CODE_FORMAT_REGEX = /^\d{1,3}$/ ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,28}$/ private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number validates :bank_code, presence: true validates :account_number, presence: true def routing_number branch_code.present? ? "#{bank_code}-#{branch_code}" : "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::DOM.alpha2 end def currency Currency::DOP end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/sent_post_email.rb
app/models/sent_post_email.rb
# frozen_string_literal: true class SentPostEmail < ApplicationRecord belongs_to :post, class_name: "Installment", optional: true before_validation :downcase_email validates_presence_of :email def downcase_email return if email.blank? self.email = email.downcase end def self.missing_emails(post:, emails:) emails - where(post:, email: emails).pluck(:email) end def self.ensure_uniqueness(post:, email:) return if email.blank? create!(post:, email:) rescue ActiveRecord::RecordNotUnique # noop else yield end # Returns array of emails that were just inserted. # Assumes all emails are present?. def self.insert_all_emails(post:, emails:) return [] if emails.empty? insert_all!(emails.map { { post_id: post.id, email: _1 } }) emails rescue ActiveRecord::RecordNotUnique insert_all_emails(post:, emails: missing_emails(post:, emails:)) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/peru_bank_account.rb
app/models/peru_bank_account.rb
# frozen_string_literal: true class PeruBankAccount < BankAccount BANK_ACCOUNT_TYPE = "PE" ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{20}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX validate :validate_account_number def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::PER.alpha2 end def currency Currency::PEN end def account_number_visual "******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/trinidad_and_tobago_bank_account.rb
app/models/trinidad_and_tobago_bank_account.rb
# frozen_string_literal: true class TrinidadAndTobagoBankAccount < BankAccount BANK_ACCOUNT_TYPE = "TT" BANK_CODE_FORMAT_REGEX = /\A[0-9]{3}\z/ private_constant :BANK_CODE_FORMAT_REGEX BRANCH_CODE_FORMAT_REGEX = /\A[0-9]{5}\z/ private_constant :BRANCH_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /\A[0-9]{1,17}\z/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_branch_code validate :validate_account_number def routing_number "#{bank_code}#{branch_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::TTO.alpha2 end def currency Currency::TTD end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_branch_code return if BRANCH_CODE_FORMAT_REGEX.match?(branch_code) errors.add :base, "The branch code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/base_variants_purchase.rb
app/models/base_variants_purchase.rb
# frozen_string_literal: true # This table is used as a HABTM join table between BaseVariant and Purchase. # This model exists to allow us to query for variant ids directly from purchase ids. # It must not be used directly for creating/deleting records. class BaseVariantsPurchase < ApplicationRecord end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/seller_refund_policy.rb
app/models/seller_refund_policy.rb
# frozen_string_literal: true class SellerRefundPolicy < RefundPolicy validates :seller, presence: true, uniqueness: { conditions: -> { where(product_id: nil) } } end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/kazakhstan_bank_account.rb
app/models/kazakhstan_bank_account.rb
# frozen_string_literal: true class KazakhstanBankAccount < BankAccount BANK_ACCOUNT_TYPE = "KZ" BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}\z/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::KAZ.alpha2 end def currency Currency::KZT end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/refund_policy.rb
app/models/refund_policy.rb
# frozen_string_literal: true class RefundPolicy < ApplicationRecord include ExternalId has_paper_trail ALLOWED_REFUND_PERIODS_IN_DAYS = { 0 => "No refunds allowed", 7 => "7-day money back guarantee", 14 => "14-day money back guarantee", 30 => "30-day money back guarantee", 183 => "6-month money back guarantee", }.freeze DEFAULT_REFUND_PERIOD_IN_DAYS = 30 attribute :max_refund_period_in_days, :integer, default: RefundPolicy::DEFAULT_REFUND_PERIOD_IN_DAYS belongs_to :seller, class_name: "User" stripped_fields :title, :fine_print, transform: -> { ActionController::Base.helpers.strip_tags(_1) } validates_presence_of :seller validates :fine_print, length: { maximum: 3_000 } validates :max_refund_period_in_days, inclusion: { in: ALLOWED_REFUND_PERIODS_IN_DAYS.keys } def title ALLOWED_REFUND_PERIODS_IN_DAYS[max_refund_period_in_days] end def as_json(*) { fine_print:, id: external_id, title:, } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/niger_bank_account.rb
app/models/niger_bank_account.rb
# frozen_string_literal: true class NigerBankAccount < BankAccount BANK_ACCOUNT_TYPE = "NE" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::NER.alpha2 end def currency Currency::XOF end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_integration.rb
app/models/product_integration.rb
# frozen_string_literal: true class ProductIntegration < ApplicationRecord include Deletable belongs_to :product, class_name: "Link", optional: true belongs_to :integration, optional: true validates_presence_of :product_id, :integration_id validates_uniqueness_of :integration_id, scope: %i[product_id deleted_at], unless: :deleted? end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/affiliate_request.rb
app/models/affiliate_request.rb
# frozen_string_literal: true class AffiliateRequest < ApplicationRecord include ExternalId ACTION_APPROVE = "approve" ACTION_IGNORE = "ignore" belongs_to :seller, class_name: "User", optional: true validates :seller, :name, :email, :promotion_text, presence: true validates :name, length: { maximum: User::MAX_LENGTH_NAME, too_long: "Your name is too long. Please try again with a shorter one." } validates :email, email_format: true validate :duplicate_request_validation, on: :create validate :requester_is_not_seller, on: :create after_commit :notify_requester_and_seller_of_submitted_request, on: :create scope :approved, -> { with_state(:approved) } scope :unattended, -> { with_state(:created) } scope :unattended_or_approved_but_awaiting_requester_to_sign_up, -> { joins("LEFT OUTER JOIN users ON users.email = affiliate_requests.email").where(users: { id: nil }).approved.or(unattended) } state_machine :state, initial: :created do after_transition created: :approved, do: ->(request) { request.state_transitioned_at = DateTime.current } after_transition created: :approved, do: :make_requester_an_affiliate! after_transition any => :ignored, do: ->(request) { request.state_transitioned_at = DateTime.current } after_transition any => :ignored, do: :notify_requester_of_ignored_request event :approve do transition created: :approved end event :ignore do transition any => :ignored, if: :allow_to_ignore? end end def can_perform_action?(action) return can_approve? if action == ACTION_APPROVE return can_ignore? if action == ACTION_IGNORE true end def as_json(options = {}) pundit_user = options[:pundit_user] { id: external_id, name:, email:, promotion: promotion_text, date: created_at.in_time_zone(seller.timezone).iso8601, state:, can_update: pundit_user ? Pundit.policy!(pundit_user, self).update? : false } end def to_param external_id end def make_requester_an_affiliate! return unless approved? requester = User.find_by(email:) if requester.nil? AffiliateRequestMailer.notify_unregistered_requester_of_request_approval(id) .deliver_later(queue: "default", wait: 3.seconds) return end affiliate = seller.direct_affiliates.alive.find_by(affiliate_user_id: requester.id) affiliate ||= seller.direct_affiliates.new enabled_self_service_affiliate_products = seller.self_service_affiliate_products.enabled if affiliate.persisted? enabled_self_service_affiliate_products = enabled_self_service_affiliate_products.where.not(product_id: affiliate.product_affiliates.pluck(:link_id)) end added_product_ids = enabled_self_service_affiliate_products.each_with_object([]) do |self_service_affiliate_product, product_ids| next unless self_service_affiliate_product.product.alive? if affiliate.new_record? affiliate.prevent_sending_invitation_email = true affiliate.affiliate_user = requester affiliate.apply_to_all_products = false affiliate.affiliate_basis_points = Affiliate::BasisPointsValidations::MIN_AFFILIATE_BASIS_POINTS affiliate.send_posts = true end affiliate.product_affiliates.build( link_id: self_service_affiliate_product.product_id, destination_url: self_service_affiliate_product.destination_url, affiliate_basis_points: self_service_affiliate_product.affiliate_basis_points || affiliate.affiliate_basis_points ) affiliate.save! affiliate.schedule_workflow_jobs product_ids << self_service_affiliate_product.product_id end if added_product_ids.any? AffiliateRequestMailer.notify_requester_of_request_approval(id) .deliver_later(queue: "default", wait: 3.seconds) end end private def duplicate_request_validation # It's fine if a requester submits a new request in case their previous # request was ignored return unless AffiliateRequest.where(seller_id:, email:, state: %i[created approved]) .exists? errors.add(:base, "You have already requested to become an affiliate of this creator.") end def requester_is_not_seller return unless seller_id return if email != seller.email errors.add(:base, "You cannot request to become an affiliate of yourself.") end def notify_requester_and_seller_of_submitted_request AffiliateRequestMailer.notify_requester_of_request_submission(id) .deliver_later(queue: "default") AffiliateRequestMailer.notify_seller_of_new_request(id) .deliver_later(queue: "default") end def notify_requester_of_ignored_request AffiliateRequestMailer.notify_requester_of_ignored_request(id) .deliver_later(queue: "default") end def allow_to_ignore? return false if ignored? # Allow creator to ignore an already approved request if the requester # hasn't signed up yet return false if approved? && User.exists?(email:) true end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/kuwait_bank_account.rb
app/models/kuwait_bank_account.rb
# frozen_string_literal: true class KuwaitBankAccount < BankAccount BANK_ACCOUNT_TYPE = "KW" BANK_CODE_FORMAT_REGEX = /^[a-zA-Z0-9]{8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::KWT.alpha2 end def currency Currency::KWD end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/card_bank_account.rb
app/models/card_bank_account.rb
# frozen_string_literal: true class CardBankAccount < BankAccount BANK_ACCOUNT_TYPE = "CARD" belongs_to :credit_card, optional: true validates :credit_card, presence: true validate :validate_credit_card_is_funded_by_debit validate :validate_credit_card_is_issued_by_a_united_states_issuer # Only on create because we already have invalid data in the DB. # TODO: Clean up data and apply the validation on all actions when possible. validate :validate_credit_card_is_not_fraudy, on: :create def bank_account_type BANK_ACCOUNT_TYPE end def routing_number credit_card.card_type.capitalize end def account_number_visual credit_card.visual end def account_number credit_card.visual end def account_number_last_four ChargeableVisual.get_card_last4(account_number) end def account_holder_full_name credit_card.visual end def country Compliance::Countries::USA.alpha2 end def currency Currency::USD end private def validate_credit_card_is_not_fraudy errors.add :base, "Your payout card must be a US debit card." if credit_card.card_type == "visa" && %w[5860 0559].include?(account_number_last_four) end def validate_credit_card_is_funded_by_debit errors.add :base, "Your payout card must be a US debit card." unless credit_card.funding_type == ChargeableFundingType::DEBIT end def validate_credit_card_is_issued_by_a_united_states_issuer errors.add :base, "Your payout card must be a US debit card." unless credit_card.card_country == Compliance::Countries::USA.alpha2 end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/installment_event.rb
app/models/installment_event.rb
# frozen_string_literal: true class InstallmentEvent < ApplicationRecord belongs_to :event, optional: true belongs_to :installment, optional: true after_commit :update_installment_events_cache_count, on: [:create, :destroy] private def update_installment_events_cache_count UpdateInstallmentEventsCountCacheWorker.perform_in(2.seconds, installment_id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/jordan_bank_account.rb
app/models/jordan_bank_account.rb
# frozen_string_literal: true class JordanBankAccount < BankAccount BANK_ACCOUNT_TYPE = "JO" BANK_CODE_FORMAT_REGEX = /^([0-9a-zA-Z]){8,11}$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::JOR.alpha2 end def currency Currency::JOD end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/call.rb
app/models/call.rb
# frozen_string_literal: true class Call < ApplicationRecord include ExternalId belongs_to :purchase delegate :link, to: :purchase attr_readonly :start_time, :end_time normalizes :start_time, :end_time, with: -> { _1.change(sec: 0) } validates_presence_of :start_time, :end_time validate :start_time_is_before_end_time validate :purchase_product_is_call validate :selected_time_is_available, on: :create, unless: :selected_time_availability_already_validated? scope :occupies_availability, -> { joins(:purchase).merge(Purchase.counts_towards_inventory.not_fully_refunded) } scope :upcoming, -> { where(end_time: Time.current..) } scope :ordered_chronologically, -> { order(start_time: :asc, end_time: :asc) } scope :starts_on_date, ->(start_time, timezone) { where(start_time: start_time.in_time_zone(timezone).all_day) } scope :overlaps_with, ->(start_time, end_time) { where("start_time < ? AND end_time > ?", end_time, start_time) } after_create_commit :schedule_reminder_emails after_create_commit :send_google_calendar_invites def formatted_time_range start_time = self.start_time.in_time_zone(link.user.timezone) end_time = self.end_time.in_time_zone(link.user.timezone) "#{start_time.strftime("%I:%M %p")} - #{end_time.strftime("%I:%M %p")} #{start_time.strftime("%Z")}" end def formatted_date_range start_time = self.start_time.in_time_zone(link.user.timezone) end_time = self.end_time.in_time_zone(link.user.timezone) formatted_start_date = start_time.strftime("%A, %B #{start_time.day.ordinalize}, %Y") if start_time.to_date == end_time.to_date formatted_start_date else formatted_end_date = end_time.strftime("%A, %B #{end_time.day.ordinalize}, %Y") "#{formatted_start_date} - #{formatted_end_date}" end end def eligible_for_reminder? return false if purchase.is_gift_sender_purchase? return true if purchase.in_progress? purchase.successful_and_not_reversed?(include_gift: true) end private def start_time_is_before_end_time return if start_time.blank? || end_time.blank? if start_time >= end_time errors.add(:base, "Start time must be before end time.") end end def purchase_product_is_call if link.native_type != Link::NATIVE_TYPE_CALL errors.add(:base, "Purchased product must be a call") end end def selected_time_is_available return if start_time.blank? || end_time.blank? return if link.call_limitation_info&.allows?(start_time) && start_time_and_end_time_available? errors.add(:base, "Selected time is no longer available") end def start_time_and_end_time_available? link.sold_calls.occupies_availability.overlaps_with(start_time, end_time).empty? && link.call_availabilities.containing(start_time, end_time).exists? end def selected_time_availability_already_validated? purchase.is_gift_receiver_purchase? end def schedule_reminder_emails return unless eligible_for_reminder? reminder_time = start_time - 1.day return if reminder_time.past? ContactingCreatorMailer.upcoming_call_reminder(id).deliver_later(wait_until: reminder_time) CustomerMailer.upcoming_call_reminder(id).deliver_later(wait_until: reminder_time) end def send_google_calendar_invites if link.has_integration?(Integration.type_for(Integration::GOOGLE_CALENDAR)) GoogleCalendarInviteJob.perform_async(id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/backtax_agreement.rb
app/models/backtax_agreement.rb
# frozen_string_literal: true class BacktaxAgreement < ApplicationRecord include FlagShihTzu belongs_to :user has_one :credit has_many :backtax_collections has_flags 1 => :collected, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false module Jurisdictions AUSTRALIA = "AUSTRALIA" ALL = [AUSTRALIA].freeze end validates :jurisdiction, inclusion: { in: Jurisdictions::ALL } validates_presence_of :signature end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/morocco_bank_account.rb
app/models/morocco_bank_account.rb
# frozen_string_literal: true class MoroccoBankAccount < BankAccount BANK_ACCOUNT_TYPE = "MA" BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/ private_constant :BANK_CODE_FORMAT_REGEX ACCOUNT_NUMBER_FORMAT_REGEX = /^MA([0-9]){20,26}$/ private_constant :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number, if: -> { Rails.env.production? } def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::MAR.alpha2 end def currency Currency::MAD end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/affiliate_credit.rb
app/models/affiliate_credit.rb
# frozen_string_literal: true class AffiliateCredit < ApplicationRecord include Purchase::Searchable::AffiliateCreditCallbacks belongs_to :affiliate_user, class_name: "User" belongs_to :seller, class_name: "User" belongs_to :purchase belongs_to :link, optional: true belongs_to :affiliate, optional: true belongs_to :oauth_application, optional: true belongs_to :affiliate_credit_success_balance, class_name: "Balance", optional: true belongs_to :affiliate_credit_chargeback_balance, class_name: "Balance", optional: true belongs_to :affiliate_credit_refund_balance, class_name: "Balance", optional: true has_many :affiliate_partial_refunds validates :basis_points, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100_00 } validate :affiliate_or_oauth_application_present scope :paid, -> { not_refunded_or_chargebacked.where("affiliate_credit_success_balance_id IS NOT NULL") } scope :not_refunded_or_chargebacked, -> { where("affiliate_credit_refund_balance_id IS NULL AND " \ "affiliate_credit_chargeback_balance_id IS NULL")} def self.create!(purchase:, affiliate:, affiliate_amount_cents:, affiliate_fee_cents:, affiliate_balance:) affiliate_credit = new affiliate_credit.affiliate = affiliate affiliate_credit.amount_cents = affiliate_amount_cents affiliate_credit.fee_cents = affiliate_fee_cents affiliate_credit.basis_points = affiliate.basis_points(product_id: purchase.link_id) affiliate_credit.seller = purchase.seller affiliate_credit.affiliate_credit_success_balance = affiliate_balance affiliate_credit.affiliate_user = affiliate.affiliate_user affiliate_credit.purchase = purchase affiliate_credit.link = purchase.link affiliate_credit.save! affiliate_credit end def amount_partially_refunded_cents affiliate_partial_refunds.sum(:amount_cents) end def fee_partially_refunded_cents affiliate_partial_refunds.sum(:fee_cents) end private def affiliate_or_oauth_application_present return if affiliate.present? || oauth_application.present? errors.add(:base, "Either affiliate or oauth_application should be set on AffiliateCredit") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_file.rb
app/models/product_file.rb
# frozen_string_literal: true class ProductFile < ApplicationRecord include S3Retrievable, WithFileProperties, ExternalId, SignedUrlHelper, JsonData, SendableToKindle, Deletable, CdnDeletable, FlagShihTzu, CdnUrlHelper, Streamable SUPPORTED_THUMBNAIL_IMAGE_CONTENT_TYPES = /jpeg|gif|png|jpg/i MAXIMUM_THUMBNAIL_FILE_SIZE = 5.megabytes has_paper_trail belongs_to :link, optional: true belongs_to :folder, class_name: "ProductFolder", optional: true belongs_to :installment, optional: true has_many :stamped_pdfs has_many :alive_stamped_pdfs, -> { alive }, class_name: "StampedPdf" has_many :subtitle_files has_many :alive_subtitle_files, -> { alive }, class_name: "SubtitleFile" has_many :media_locations has_one :dropbox_file has_and_belongs_to_many :base_variants has_and_belongs_to_many :product_files_archives has_one_attached :thumbnail normalizes :isbn, with: ->(value) do next if value.blank? value.strip.upcase.gsub(/[\sβ€“β€”βˆ’]/, "-") end normalizes :filetype, with: proc(&:downcase) before_validation :set_filegroup after_commit :schedule_file_analyze, on: :create after_commit :stamp_existing_pdfs_if_needed, on: :update after_create :reset_moderated_by_iffy_flag has_flags 1 => :is_transcoded_for_hls, 2 => :is_linked_to_existing_file, 3 => :analyze_completed, 4 => :stream_only, 5 => :pdf_stamp_enabled, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false validates_presence_of :url validates :isbn, isbn: true, allow_nil: true, if: :supports_isbn? validates :isbn, absence: { unless: :supports_isbn? } validate :valid_url?, on: :create validate :belongs_to_product_or_installment, on: :save validate :thumbnail_is_vaild after_save :invalidate_product_cache after_commit :schedule_rename_in_storage, on: :update, if: :saved_change_to_display_name? attr_json_data_accessor :epub_section_info has_s3_fields :url scope :in_order, -> { order(position: :asc) } scope :ordered_by_ids, ->(ids) { reorder([Arel.sql("FIELD(product_files.id, ?)"), ids]) } scope :pdf, -> { where(filetype: "pdf") } scope :not_external_link, -> { where.not(filetype: "link") } scope :archivable, -> { not_external_link.not_stream_only } def has_alive_duplicate_files? ProductFile.alive.where(url:).exists? end def has_cdn_url? url&.starts_with?(S3_BASE_URL) end def has_valid_external_link? url =~ /\A#{URI::DEFAULT_PARSER.make_regexp}\z/ && URI.parse(url).host.present? end def valid_url? if external_link? && !has_valid_external_link? errors.add(:base, "#{url} is not a valid URL.") elsif !external_link? && !has_cdn_url? errors.add(:base, "Please provide a valid file URL.") end end def as_json(options = {}) return super(options) if options.delete(:original) url_for_thumbnail = thumbnail_url { # TODO (product_edit_react) remove duplicate attribute file_name: name_displayable, display_name: name_displayable, description:, extension: display_extension, file_size: size, pagelength: (epub? ? nil : pagelength), duration:, is_pdf: pdf?, pdf_stamp_enabled: pdf_stamp_enabled?, is_streamable: streamable?, stream_only: stream_only?, is_transcoding_in_progress: options[:existing_product_file] ? false : transcoding_in_progress?, id: external_id, attached_product_name: link.try(:name), subtitle_files: alive_subtitle_files.map do |file| { url: file.url, file_name: file.s3_display_name, extension: file.s3_display_extension, language: file.language, file_size: file.size, size: file.size_displayable, signed_url: signed_download_url_for_s3_key_and_filename(file.s3_key, file.s3_filename, is_video: true), status: { type: "saved" }, } end, url:, isbn:, thumbnail: url_for_thumbnail.present? ? { url: url_for_thumbnail, signed_id: thumbnail.signed_id, status: { type: "saved" } } : nil, status: { type: "saved" }, } end delegate :user, to: :with_product_files_owner def with_product_files_owner link || installment end def must_be_pdf_stamped? pdf? && pdf_stamp_enabled? end def epub? filetype == "epub" end def pdf? filetype == "pdf" end def mobi? filetype == "mobi" end def supports_isbn? epub? || pdf? || mobi? end def streamable? filegroup == "video" end def listenable? filegroup == "audio" end def external_link? filetype == "link" end def readable? pdf? end def stream_only? streamable? && stream_only end def archivable? !external_link? && !stream_only? end def consumable? streamable? || listenable? || readable? end def can_send_to_kindle? return false if !pdf? && !epub? return false if size.nil? size < Link::MAX_ALLOWED_FILE_SIZE_FOR_SEND_TO_KINDLE end def transcoding_failed ContactingCreatorMailer.video_transcode_failed(id).deliver_later end def save_subtitle_files!(files) subtitle_files.alive.each do |file| found = files.extract! { _1[:url] == file.url }.first if found file.language = found[:language] else file.mark_deleted end file.save! end files.each { subtitle_files.create!(_1) } end def delete_all_subtitle_files! subtitle_files.alive.each do |file| file.mark_deleted file.save! end end def delete! mark_deleted! delete_all_subtitle_files! end def display_extension external_link? ? "URL" : s3_display_extension end def rename_in_storage return if display_name == s3_display_name extension = s3_extension name_with_extension = display_name.ends_with?(extension) ? display_name : "#{display_name}#{extension}" new_key = MultipartTransfer.transfer_to_s3(self.s3_object.presigned_url(:get, expires_in: SignedUrlHelper::SIGNED_S3_URL_VALID_FOR_MAXIMUM.to_i).to_s, destination_filename: name_with_extension, existing_s3_object: self.s3_object) self.url = URI::DEFAULT_PARSER.unescape("#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/#{new_key}") save! end def name_displayable return display_name if display_name.present? return url if external_link? s3_display_name end def subtitle_files_urls subtitle_files.alive.map do |file| { file: signed_download_url_for_s3_key_and_filename(file.s3_key, file.s3_filename, is_video: true), label: file.language, kind: "captions" } end end def subtitle_files_for_mobile subtitle_files.alive.map do |file| { url: signed_download_url_for_s3_key_and_filename(file.s3_key, file.s3_filename, is_video: true), language: file.language } end end def mobile_json_data { name: s3_filename, size:, filetype:, filegroup:, id: external_id, created_at:, name_displayable:, description:, pagelength: (epub? ? nil : pagelength), duration:, } end def read_consumption_markers markers = Array.new(pagelength, "") if pdf? (1..pagelength).each do |page_number| # markers is 0-based; page_number is 1-based: markers[page_number - 1] = "Page #{page_number}" end elsif epub? markers = epub_section_info.values.map { |epub_section_info_hash| epub_section_info_hash["section_name"] } end markers end def schedule_file_analyze AnalyzeFileWorker.perform_in(5.seconds, id, self.class.name) unless external_link? end def queue_for_transcoding? streamable? && analyze_completed? end def latest_media_location_for(purchase) return nil if link.nil? || installment.present? || purchase.nil? latest_media_location = media_locations.where(purchase_id: purchase.id).order("consumed_at").last latest_media_location.as_json end def content_length (listenable? || streamable?) ? duration : pagelength end def external_folder_id ObfuscateIds.encrypt(folder_id) if folder&.alive? end def thumbnail_url return unless streamable? return unless thumbnail.attached? cached_variant_url = Rails.cache.fetch("attachment_product_file_thumbnail_#{thumbnail.id}_variant_url") { thumbnail_variant.url } cdn_url_for(cached_variant_url) rescue => e Rails.logger.warn("ProductFile#thumbnail_url error (#{id}): #{e.class} => #{e.message}") cdn_url_for(thumbnail.url) end def thumbnail_variant return unless thumbnail.attached? return unless thumbnail.image? && thumbnail.content_type.match?(SUPPORTED_THUMBNAIL_IMAGE_CONTENT_TYPES) thumbnail.variant(resize_to_limit: [1280, 720]).processed end def cannot_be_stamped? # The column allows nil values stampable_pdf == false end private def schedule_rename_in_storage return if external_link? # a slight delay to allow the new `display_name` to propagate to replica DBs RenameProductFileWorker.perform_in(5.seconds, id) end def belongs_to_product_or_installment return if (link.present? && installment.nil?) || (link.nil? && installment.present?) errors.add(:base, "A file needs to either belong to a product or an installment") end def set_filegroup if filetype == "link" self.filegroup = "link" return end extension = s3_extension&.delete(".") determine_and_set_filegroup(extension) if extension.present? end def invalidate_product_cache link.invalidate_cache if link.present? end def thumbnail_is_vaild return unless thumbnail.attached? unless thumbnail.image? && thumbnail.content_type.match?(SUPPORTED_THUMBNAIL_IMAGE_CONTENT_TYPES) errors.add(:base, "Please upload a thumbnail in JPG, PNG, or GIF format.") return end if thumbnail.byte_size > MAXIMUM_THUMBNAIL_FILE_SIZE errors.add(:base, "Could not process your thumbnail, please upload an image with size smaller than 5 MB.") end end def reset_moderated_by_iffy_flag return unless filegroup == "image" link&.update_attribute(:moderated_by_iffy, false) end def stamp_existing_pdfs_if_needed return if link.nil? return unless saved_change_to_pdf_stamp_enabled? && pdf_stamp_enabled? link.sales.successful_gift_or_nongift.not_is_gift_sender_purchase.not_recurring_charge.includes(:url_redirect).find_each(order: :desc) do |purchase| next if purchase.url_redirect.blank? StampPdfForPurchaseJob.perform_async(purchase.id) end end def video_file_analysis_completed if installment&.published? transcode_video(self) elsif link&.alive? if link.auto_transcode_videos? transcode_video(self) else link.enable_transcode_videos_on_purchase! 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/uruguay_bank_account.rb
app/models/uruguay_bank_account.rb
# frozen_string_literal: true class UruguayBankAccount < BankAccount BANK_ACCOUNT_TYPE = "UY" BANK_CODE_FORMAT_REGEX = /^\d{3}$/ ACCOUNT_NUMBER_FORMAT_REGEX = /^\d{1,12}$/ private_constant :BANK_CODE_FORMAT_REGEX, :ACCOUNT_NUMBER_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::URY.alpha2 end def currency Currency::UYU end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if ACCOUNT_NUMBER_FORMAT_REGEX.match?(account_number_decrypted) errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/taxonomy_stat.rb
app/models/taxonomy_stat.rb
# frozen_string_literal: true class TaxonomyStat < ApplicationRecord belongs_to :taxonomy end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/product_refund_policy.rb
app/models/product_refund_policy.rb
# frozen_string_literal: true class ProductRefundPolicy < RefundPolicy belongs_to :product, class_name: "Link" validates :product, presence: true, uniqueness: true validate :product_must_belong_to_seller scope :for_visible_and_not_archived_products, -> { joins(:product).merge(Link.visible_and_not_archived) } def as_json(*) { fine_print:, id: external_id, max_refund_period_in_days:, product_name: product.name, title:, } end def published_and_no_refunds? product.published? && no_refunds? end def no_refunds? return true if title.match?(/no refunds|final|no returns/i) response = ask_ai(no_refunds_prompt) value = JSON.parse(response.dig("choices", 0, "message", "content"))["no_refunds"] Rails.logger.debug("AI determined refund policy #{id} is no-refunds: #{value}") value rescue => e Rails.logger.debug("Error determining if refund policy #{id} is no-refunds: #{e.message}") false end def determine_max_refund_period_in_days return 0 if title.match?(/no refunds|final|no returns/i) begin response = ask_ai(max_refund_period_in_days_prompt) days = Integer(response.dig("choices", 0, "message", "content")) rescue response.dig("choices", 0, "message", "content") # Return only values from ALLOWED_REFUND_PERIODS_IN_DAYS or default to 30 if RefundPolicy::ALLOWED_REFUND_PERIODS_IN_DAYS.key?(days) days else Rails.logger.debug("Unknown refund period for policy #{id}: #{days}") RefundPolicy::DEFAULT_REFUND_PERIOD_IN_DAYS end rescue => e Rails.logger.debug("Error determining max refund period for policy #{id}: #{e.message}") RefundPolicy::DEFAULT_REFUND_PERIOD_IN_DAYS end end def max_refund_period_in_days_prompt prompt = <<~PROMPT You are an expert content reviewer that responds in numbers only. Your role is to determine the maximum number of days allowed for a refund policy based on the refund policy title. If the refund policy or fine print has words like "no refunds", "refunds not allowed", "no returns", "returns not allowed", "final" etc.), it's a no-refunds policy The allowed number of days are 0 (no refunds allowed), 7, 14, 30, or 183 (6 months). Use the number that most closely matches, but not above the maximum allowed. Example 1: If the title is "30-day money back guarantee", return 30. Example 2: If from the fine print it clearly states that there are no refunds, return 0. Example 3: If the analysis determines that it is a 3-day refund policy, return 3. Example 4: If the analysis determines that it is a 2-month refund policy, return 30. Example 5: If the analysis determines that it is a 1-year refund policy, return 183. Return one of the allowed numbers only if you are 100% confident. If you are not 100% confident, return -1. The response MUST be just a number. The only allowed numbers are: -1, 0, 7, 14, 30, 183. Product name: #{product.name} Product type: #{product.native_type} Refund policy title: #{title} PROMPT if fine_print.present? prompt += <<~FINE_PRINT <refund policy fine print> #{fine_print.truncate(300)} </refund policy fine print> FINE_PRINT end prompt end private def no_refunds_prompt prompt = <<~PROMPT Analyze this refund policy and return {"no_refunds": true} if you are 100% confident (has words like "no refunds", "refunds not allowed", "no returns", "returns not allowed", "final" etc.) it's a no-refunds policy, otherwise {"no_refunds": false}. Product name: #{product.name} Product type: #{product.native_type} Refund policy title: #{title} PROMPT if fine_print.present? prompt += <<~FINE_PRINT <refund policy fine print> #{fine_print.truncate(300)} </refund policy fine print> FINE_PRINT end prompt end def product_must_belong_to_seller return if seller.blank? || product.blank? return if seller == product.user errors.add(:product, :invalid) end def ask_ai(prompt) OpenAI::Client.new.chat( parameters: { messages: [{ role: "user", content: prompt }], model: "gpt-4o-mini", temperature: 0.0, max_tokens: 10 } ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/shipment.rb
app/models/shipment.rb
# frozen_string_literal: true class Shipment < ApplicationRecord belongs_to :purchase, optional: true CARRIER_TRACKING_URL_MAPPING = { "USPS" => "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=", "UPS" => "http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&InquiryNumber1=", "FedEx" => "http://www.fedex.com/Tracking?language=english&cntry_code=us&tracknumbers=", "DHL" => "http://www.dhl.com/content/g0/en/express/tracking.shtml?brand=DHL&AWB=", "DHL Global Mail" => "http://webtrack.dhlglobalmail.com/?trackingnumber=", "OnTrac" => "http://www.ontrac.com/trackres.asp?tracking_number=", "Canada Post" => "https://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?LOCALE=en&trackingNumber=" }.freeze validates :purchase, presence: true # The purchase's updated_at should reflect changes to its shipment. after_update :touch_purchase state_machine(:ship_state, initial: :not_shipped) do after_transition not_shipped: :shipped, do: :marked_as_shipped! after_transition not_shipped: :shipped, do: :notify_buyer_of_shipment event :mark_shipped do transition not_shipped: :shipped end end def shipped? shipped_at.present? end def calculated_tracking_url return tracking_url if tracking_url.present? return nil if tracking_number.nil? || carrier.nil? return nil unless CARRIER_TRACKING_URL_MAPPING.key?(carrier) CARRIER_TRACKING_URL_MAPPING[carrier] + tracking_number end private def marked_as_shipped! update!(shipped_at: Time.current) end def notify_buyer_of_shipment SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer", "order_shipped", id) do CustomerLowPriorityMailer.order_shipped(id).deliver_later(queue: "low") end end def touch_purchase purchase.touch end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/purchase_preview.rb
app/models/purchase_preview.rb
# frozen_string_literal: true class PurchasePreview include ActiveModel::Model attr_accessor :link, :seller, :created_at, :quantity, :custom_fields, :formatted_total_display_price_per_unit, :shipping_cents, :displayed_price_currency_type, :url_redirect, :displayed_price_cents, :support_email, :charged_amount_cents, :external_id_for_invoice, :unbundled_purchases, :successful_purchases, :orderable validates :link, presence: true validates :seller, presence: true validates :created_at, presence: true validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 } validates :formatted_total_display_price_per_unit, presence: true validates :shipping_cents, presence: true validates :displayed_price_currency_type, presence: true validates :url_redirect, presence: true validates :displayed_price_cents, presence: true validates :charged_amount_cents, presence: true validates :external_id_for_invoice, presence: true validates :unbundled_purchases, presence: true validates :successful_purchases, presence: true validates :orderable, presence: true validate :validate_custom_fields # The receipt template uses a lot of fields of `purchase` # in different pieces of business logic that are not relevant to our preview need. # For them it's fine to return `nil` instead of trying to add fields # to mock all those irrelevant pieces of business logic. # # Meanwhile the fields that are needed for previews are defined in `attr_accessor` # and we have validations for them. def method_missing(name) nil end private def validate_custom_fields errors.add(:custom_fields, "must be an array") unless custom_fields.is_a?(Array) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/bundle_product_purchase.rb
app/models/bundle_product_purchase.rb
# frozen_string_literal: true class BundleProductPurchase < ApplicationRecord belongs_to :bundle_purchase, class_name: "Purchase", foreign_key: :bundle_purchase_id belongs_to :product_purchase, class_name: "Purchase", foreign_key: :product_purchase_id validate :purchases_must_have_same_seller validate :product_purchase_cannot_be_bundle_purchase private def purchases_must_have_same_seller if bundle_purchase.seller != product_purchase.seller errors.add(:base, "Seller must be the same for bundle and product purchases") end end def product_purchase_cannot_be_bundle_purchase if product_purchase.link.is_bundle? errors.add(:base, "Product purchase cannot be a bundle purchase") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/denmark_bank_account.rb
app/models/denmark_bank_account.rb
# frozen_string_literal: true class DenmarkBankAccount < BankAccount BANK_ACCOUNT_TYPE = "DK" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::DNK.alpha2 end def currency Currency::DKK end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/collaborator_invitation.rb
app/models/collaborator_invitation.rb
# frozen_string_literal: true class CollaboratorInvitation < ApplicationRecord include ExternalId belongs_to :collaborator def accept! destroy! AffiliateMailer.collaborator_invitation_accepted(collaborator_id).deliver_later end def decline! collaborator.mark_deleted! AffiliateMailer.collaborator_invitation_declined(collaborator_id).deliver_later end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/community_notification_setting.rb
app/models/community_notification_setting.rb
# frozen_string_literal: true class CommunityNotificationSetting < ApplicationRecord belongs_to :user belongs_to :seller, class_name: "User" validates :user_id, uniqueness: { scope: :seller_id } enum :recap_frequency, { daily: "daily", weekly: "weekly" }, prefix: true, validate: { allow_nil: true } end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/costa_rica_bank_account.rb
app/models/costa_rica_bank_account.rb
# frozen_string_literal: true class CostaRicaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "CR" validate :validate_account_number, if: -> { Rails.env.production? } def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::CRI.alpha2 end def currency Currency::CRC end def account_number_visual "#{country}******#{account_number_last_four}" end def to_hash { account_number: account_number_visual, bank_account_type: } end private def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/user.rb
app/models/user.rb
# frozen_string_literal: true class User < ApplicationRecord devise :database_authenticatable, :registerable, :confirmable, :omniauthable, :recoverable, :rememberable, :trackable, :pwned_password has_paper_trail has_one_time_password include Flipper::Identifier, FlagShihTzu, CurrencyHelper, Mongoable, JsonData, Deletable, MoneyBalance, DeviseInternal, PayoutSchedule, SocialFacebook, SocialTwitter, SocialGoogle, SocialApple, SocialGoogleMobile, StripeConnect, Stats, PaymentStats, FeatureStatus, Risk, Compliance, Validations, Taxation, PingNotification, AsyncDeviseNotification, Posts, AffiliatedProducts, Followers, LowBalanceFraudCheck, MailerLevel, DirectAffiliates, AsJson, Tier, Recommendations, Team, AustralianBacktaxes, WithCdnUrl, TwoFactorAuthentication, Versionable, Comments, VipCreator, SignedUrlHelper, Purchases, SecureExternalId, AttributeBlockable, PayoutInfo stripped_fields :name, :facebook_meta_tag, :google_analytics_id, :username, :email, :support_email # Minimum tags count to show tags section on user profile page MIN_TAGS_TO_SHOW_TAGS = 2 # Max price (in USΒ’) for an unverified creator MAX_PRICE_USD_CENTS_UNLESS_VERIFIED = 500_000 # Max length for facebook_meta_tag MAX_LENGTH_FACEBOOK_META_TAG = 100 MAX_LENGTH_NAME = 100 INVALID_NAME_FOR_EMAIL_DELIVERY_REGEX = /:/ MIN_AU_BACKTAX_OWED_CENTS_FOR_CONTACT = 100_00 MIN_AGE_FOR_SERVICE_PRODUCTS = 30.days MIN_SALES_CENTS_VALUE_FOR_AI_PRODUCT_GENERATION = 10_000 has_many :affiliate_credits, foreign_key: "affiliate_user_id" has_many :affiliate_partial_refunds, foreign_key: "affiliate_user_id" has_many :affiliate_requests, foreign_key: :seller_id has_many :self_service_affiliate_products, foreign_key: :seller_id has_many :links has_many :products, class_name: "Link" has_many :dropbox_files has_many :subscriptions has_many :oauth_applications, class_name: "OauthApplication", as: :owner has_many :resource_subscriptions has_many :devices belongs_to :credit_card, optional: true # Associate with CustomDomain.alive objects has_one :custom_domain, -> { alive } has_many :orders, foreign_key: :purchaser_id has_many :purchases, foreign_key: :purchaser_id has_many :purchased_products, -> { distinct }, through: :purchases, class_name: "Link", source: :link has_many :sales, class_name: "Purchase", foreign_key: :seller_id has_many :preorders_bought, class_name: "Preorder", foreign_key: :purchaser_id has_many :preorders_sold, class_name: "Preorder", foreign_key: :seller_id has_many :payments has_many :balances has_many :balance_transactions has_many :credits has_many :credits_given, class_name: "Credit", foreign_key: :crediting_user_id has_many :bank_accounts has_many :installments, foreign_key: :seller_id has_many :comments, as: :commentable has_many :imported_customers, foreign_key: :importing_user_id has_many :invites, foreign_key: :sender_id has_many :offer_codes has_many :user_compliance_infos has_many :user_compliance_info_requests has_many :user_tax_forms has_many :workflows, foreign_key: :seller_id has_many :merchant_accounts has_many :shipping_destinations has_many :tos_agreements has_many :product_files, through: :links has_many :third_party_analytics has_many :zip_tax_rates has_many :service_charges has_many :recurring_services has_many :direct_affiliate_accounts, foreign_key: :affiliate_user_id, class_name: DirectAffiliate.name has_many :affiliate_accounts, foreign_key: :affiliate_user_id, class_name: Affiliate.name has_many :affiliate_sales, through: :affiliate_accounts, source: :purchases has_many :affiliated_products, -> { distinct }, through: :affiliate_accounts, source: :products has_many :affiliated_creators, -> { distinct }, through: :affiliated_products, source: :user, class_name: User.name has_many :collaborators, foreign_key: :seller_id has_many :incoming_collaborators, foreign_key: :affiliate_user_id, class_name: Collaborator.name has_many :accepted_alive_collaborations, -> { invitation_accepted.alive }, foreign_key: :affiliate_user_id, class_name: Collaborator.name has_many :collaborating_products, through: :accepted_alive_collaborations, source: :products has_one :large_seller, dependent: :destroy has_one :yearly_stat, dependent: :destroy has_many :stripe_apple_pay_domains has_one :global_affiliate, -> { alive }, foreign_key: :affiliate_user_id, autosave: true has_many :upsells, foreign_key: :seller_id has_many :available_cross_sells, -> { cross_sell.alive.available_to_customers }, foreign_key: :seller_id, class_name: "Upsell" has_many :blocked_customer_objects, foreign_key: :seller_id has_one :seller_profile, foreign_key: :seller_id has_many :seller_profile_sections, foreign_key: :seller_id has_many :seller_profile_products_sections, foreign_key: :seller_id has_many :seller_profile_posts_sections, foreign_key: :seller_id has_many :seller_profile_rich_text_sections, foreign_key: :seller_id has_many :seller_profile_subscribe_sections, foreign_key: :seller_id has_many :seller_profile_featured_product_sections, foreign_key: :seller_id has_many :seller_profile_wishlists_sections, foreign_key: :seller_id has_many :backtax_agreements has_many :custom_fields, foreign_key: :seller_id has_many :product_refund_policies, -> { where.not(product: nil) }, foreign_key: :seller_id has_many :audience_members, foreign_key: :seller_id has_many :alive_bank_accounts, -> { alive }, class_name: "BankAccount" has_many :wishlists has_many :alive_wishlist_follows, -> { alive }, class_name: "WishlistFollower", foreign_key: :follower_user_id has_many :alive_following_wishlists, through: :alive_wishlist_follows, source: :wishlist has_many :carts has_one :alive_cart, -> { alive }, class_name: "Cart" has_many :product_reviews, through: :purchases has_one :refund_policy, -> { where(product_id: nil) }, foreign_key: "seller_id", class_name: "SellerRefundPolicy", dependent: :destroy has_many :utm_links, dependent: :destroy, foreign_key: :seller_id has_many :seller_communities, class_name: "Community", foreign_key: :seller_id, dependent: :destroy has_many :community_chat_messages, dependent: :destroy has_many :last_read_community_chat_messages, dependent: :destroy has_many :community_notification_settings, dependent: :destroy has_many :seller_community_chat_recaps, class_name: "CommunityChatRecap", foreign_key: :seller_id, dependent: :destroy has_one_attached :avatar attr_accessor :avatar_changed before_save :set_avatar_changed after_commit :reset_avatar_changed scope :by_email, ->(email) { where(email:) } scope :compliant, -> { where(user_risk_state: "compliant") } scope :payment_reminder_risk_state, -> { where("user_risk_state in (?)", PAYMENT_REMINDER_RISK_STATES) } scope :not_suspended, -> { without_user_risk_state(:suspended_for_fraud, :suspended_for_tos_violation) } scope :created_between, ->(range) { where(created_at: range) if range } scope :holding_balance_more_than, lambda { |cents| joins(:balances).merge(Balance.unpaid).group("balances.user_id").having("SUM(balances.amount_cents) > ?", cents) } scope :holding_balance, -> { holding_balance_more_than(0) } scope :holding_non_zero_balance, lambda { joins(:balances).merge(Balance.unpaid).group("balances.user_id").having("SUM(balances.amount_cents) != 0") } scope :admin_search, ->(query) { query = query.to_s.strip if EmailFormatValidator.valid?(query) where(email: query) else where(external_id: query).or(where("email LIKE ?", "%#{query}%")).or(where("name LIKE ?", "%#{query}%")) end } attribute :recommendation_type, default: User::RecommendationType::OWN_PRODUCTS attr_accessor :login, :skip_enabling_two_factor_authentication attr_json_data_accessor :background_opacity_percent, default: 100 attr_json_data_accessor :payout_date_of_last_payment_failure_email attr_json_data_accessor :last_ping_failure_notification_at attr_json_data_accessor :au_backtax_sales_cents, default: 0 attr_json_data_accessor :au_backtax_owed_cents, default: 0 attr_json_data_accessor :gumroad_day_timezone attr_json_data_accessor :payout_threshold_cents, default: -> { minimum_payout_threshold_cents } attr_json_data_accessor :payout_frequency, default: User::PayoutSchedule::WEEKLY attr_json_data_accessor :custom_fee_per_thousand attr_json_data_accessor :payouts_paused_by attr_blockable :email attr_blockable :form_email, object_type: :email attr_blockable :email_domain attr_blockable :form_email_domain, object_type: :email_domain attr_blockable :account_created_ip, object_type: :ip_address validates :username, uniqueness: { case_sensitive: true }, length: { minimum: 3, maximum: 20 }, exclusion: { in: DENYLIST }, # Username format ensures - # 1. Username contains only lower case letters and numbers. # 2. Username contains at least one letter. format: { with: /\A[a-z0-9]*[a-z][a-z0-9]*\z/, message: "has to contain at least one letter and may only contain lower case letters and numbers." }, allow_nil: true, if: :username_changed? # validate only when seller changes their username validates :name, length: { maximum: MAX_LENGTH_NAME, too_long: "Your name is too long. Please try again with a shorter one." }, format: { without: INVALID_NAME_FOR_EMAIL_DELIVERY_REGEX, message: "cannot contain colons (:) as it causes email delivery problems. Please remove any colons from your name and try again.", if: :name_changed? } validates :facebook_meta_tag, length: { maximum: MAX_LENGTH_FACEBOOK_META_TAG } validates :purchasing_power_parity_limit, allow_nil: true, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 100 } validates_presence_of :email, if: :email_required? validate :email_almost_unique validates :email, email_format: true, allow_blank: true, if: :email_changed? validates :kindle_email, format: { with: KINDLE_EMAIL_REGEX }, allow_blank: true, if: :kindle_email_changed? validates :support_email, email_format: true, allow_blank: true, if: :support_email_changed? validates :support_email, not_reserved_email_domain: true, allow_blank: true, if: :support_email_changed?, unless: :is_team_member? validate :google_analytics_id_valid validate :avatar_is_valid validate :payout_frequency_is_valid validates_presence_of :password, if: :password_required? validates_confirmation_of :password, if: :password_required? validates_length_of :password, within: 4...128, allow_blank: true validates :timezone, inclusion: { in: ActiveSupport::TimeZone::MAPPING.keys << nil, message: "%{value} is not a known time zone." } validates :recommendation_type, inclusion: { in: User::RecommendationType::TYPES } validates :currency_type, inclusion: { in: CURRENCY_CHOICES.keys, message: "%{value} is not a supported currency." } validates :custom_fee_per_thousand, allow_nil: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 } validate :json_data, :json_data_must_be_hash validate :account_created_email_domain_is_not_blocked, on: :create validate :account_created_ip_is_not_blocked, on: :create validate :facebook_meta_tag_is_valid validates :payment_address, email_format: true, allow_blank: true before_save :append_http before_save :save_external_id before_create :init_default_notification_settings before_create :enable_two_factor_authentication before_create :enable_tipping before_create :enable_discover_boost before_create :set_refund_fee_notice_shown before_create :set_refund_policy_enabled after_create :create_global_affiliate! after_create :create_refund_policy! after_create_commit :enqueue_generate_username_job has_flags 1 => :announcement_notification_enabled, 2 => :skip_free_sale_analytics, 3 => :purchasing_power_parity_enabled, 4 => :opt_out_simplified_pricing, 5 => :display_offer_code_field, 6 => :disable_reviews_after_year, 7 => :refund_fee_notice_shown, 8 => :refunds_disabled, 9 => :two_factor_authentication_enabled, 10 => :buyer_signup, 11 => :enforce_session_timestamping, 12 => :disable_third_party_analytics, 13 => :enable_verify_domain_third_party_services, 14 => :purchasing_power_parity_payment_verification_disabled, 15 => :bears_affiliate_fee, 16 => :enable_payment_email, 17 => :has_seen_discover, 18 => :should_paypal_payout_be_split, 19 => :pre_signup_affiliate_request_processed, 20 => :payouts_paused_internally, 21 => :disable_comments_email, 22 => :has_dismissed_upgrade_banner, 23 => :opted_into_upgrading_during_signup, 24 => :disable_reviews_email, 25 => :check_merchant_account_is_linked, 26 => :collect_eu_vat, 27 => :is_eu_vat_exclusive, 28 => :is_team_member, 29 => :DEPRECATED_has_payout_privilege, 30 => :DEPRECATED_has_risk_privilege, 31 => :disable_paypal_sales, 32 => :all_adult_products, 33 => :enable_free_downloads_email, 34 => :enable_recurring_subscription_charge_email, 35 => :enable_payment_push_notification, 36 => :enable_recurring_subscription_charge_push_notification, 37 => :enable_free_downloads_push_notification, 38 => :million_dollar_announcement_sent, 39 => :disable_global_affiliate, 40 => :require_collab_request_approval, 41 => :payouts_paused_by_user, 42 => :opted_out_of_review_reminders, 43 => :tipping_enabled, 44 => :show_nsfw_products, 45 => :discover_boost_enabled, 46 => :refund_policy_enabled, # DO NOT use directly, use User#account_level_refund_policy_enabled? instead 47 => :can_connect_stripe, 48 => :upcoming_refund_policy_change_email_sent, 49 => :can_create_physical_products, 50 => :paypal_payout_fee_waived, 51 => :dismissed_create_products_with_ai_promo_alert, 52 => :disable_affiliate_requests, :column => "flags", :flag_query_mode => :bit_operator, check_for_column: false LINK_PROPERTIES = %w[username twitter_handle bio name google_analytics_id flags facebook_pixel_id skip_free_sale_analytics disable_third_party_analytics].freeze after_update :clear_products_cache, if: -> (user) { (User::LINK_PROPERTIES & user.saved_changes.keys).present? || (%w[font background_color highlight_color] & user.seller_profile&.saved_changes&.keys).present? } after_save :create_updated_stripe_apple_pay_domain, if: ->(user) { user.saved_change_to_username? } after_save :delete_old_stripe_apple_pay_domain, if: ->(user) { user.saved_change_to_username? } after_save :trigger_iffy_ingest after_update :update_audience_members_affiliates after_update :update_product_search_index! after_commit :move_purchases_to_new_email, on: :update, if: :email_previously_changed? after_commit :make_affiliate_of_the_matching_approved_affiliate_requests, on: [:create, :update], if: ->(user) { user.confirmed_at_previously_changed? && user.confirmed? } after_commit :generate_subscribe_preview, on: [:create, :update], if: :should_subscribe_preview_be_regenerated? after_create :insert_null_chargeback_state # risk state machine # # not_reviewed β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ compliant ↔ ↔ ↔ ↔ β†•οΈŽ # ↓ ↓ ↑ β†•οΈŽ # ↓ ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ↑ β†•οΈŽ # ↓ ↑ β†•οΈŽ # ↓ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ ↑ β†’ β†’ β†’ β†’ β†’ ↕ # ↓ ↑ ↑ β†•οΈŽ # ↓→ flagged_for_fraud β†’ suspended_for_fraud ↔ ↑ ↔ ↔ ↔ ↔ on_probation # ↓ ↓↑ ↑ β†•οΈŽ # ↓→ flagged_for_tos β†’ suspended_for_tos ↔ ↑ ↔ ↔ ↔ ↔ ↔ ↔ ↔ ↔ # ↓ ↓ ↓ ↑ # ↓ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ β†’ ↑ β†’ β†’ β†’ β†’ β†’ β†’ # state_machine(:user_risk_state, initial: :not_reviewed) do before_transition any => %i[flagged_for_fraud flagged_for_tos_violation suspended_for_fraud suspended_for_tos_violation], :do => :not_verified? after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :invalidate_active_sessions! after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :disable_links_and_tell_chat after_transition any => %i[on_probation compliant flagged_for_tos_violation flagged_for_fraud suspended_for_tos_violation suspended_for_fraud], :do => :add_user_comment after_transition any => [:flagged_for_tos_violation], :do => :add_product_comment after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :suspend_sellers_other_accounts after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :block_seller_ip! after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :delete_custom_domain! after_transition any => %i[suspended_for_fraud suspended_for_tos_violation], :do => :log_suspension_time_to_mongo after_transition any => :compliant, :do => :enable_refunds! after_transition %i[suspended_for_fraud suspended_for_tos_violation] => %i[compliant on_probation], :do => :enable_links_and_tell_chat after_transition %i[suspended_for_fraud suspended_for_tos_violation not_reviewed] => %i[compliant on_probation], :do => :unblock_seller_ip! after_transition %i[suspended_for_fraud suspended_for_tos_violation] => :compliant, do: :enable_sellers_other_accounts after_transition %i[suspended_for_fraud suspended_for_tos_violation] => %i[compliant on_probation], :do => :create_updated_stripe_apple_pay_domain event :mark_compliant do transition all => :compliant end event :flag_for_tos_violation do transition %i[not_reviewed compliant flagged_for_fraud] => :flagged_for_tos_violation end event :flag_for_fraud do transition %i[not_reviewed compliant flagged_for_tos_violation] => :flagged_for_fraud end event :suspend_for_fraud do transition %i[on_probation flagged_for_fraud] => :suspended_for_fraud end event :suspend_for_tos_violation do transition %i[on_probation flagged_for_tos_violation] => :suspended_for_tos_violation end event :put_on_probation do transition all => :on_probation end end state_machine(:tier_state, initial: :tier_0) do state :tier_0, value: TIER_0 state :tier_1, value: TIER_1 state :tier_2, value: TIER_2 state :tier_3, value: TIER_3 state :tier_4, value: TIER_4 before_transition any => any, do: -> (user, transition) do new_tier = transition.args.first return unless new_tier raise ArgumentError, "first transition argument must be a valid tier" unless User::TIER_RANGES.has_value?(new_tier) raise ArgumentError, "invalid transition argument: new tier can't be the same as old tier" if new_tier == transition.from raise ArgumentError, "invalid transition argument: upgrading to lower tier is not allowed" if new_tier < transition.from end after_transition any => any, do: ->(user, transition) do new_tier = transition.args.first || transition.to user.update!(tier_state: new_tier) user.log_tier_transition(from_tier: transition.from, to_tier: new_tier) end event :upgrade_tier do transition tier_0: %i[tier_1 tier_2 tier_3 tier_4] transition tier_1: %i[tier_2 tier_3 tier_4] transition tier_2: %i[tier_3 tier_4] transition tier_3: %i[tier_4] end end has_one_attached :subscribe_preview has_many_attached :annual_reports def financial_annual_report_url_for(year: Time.current.year) return unless annual_reports.attached? blob_url = annual_reports.joins("LEFT JOIN active_storage_blobs ON active_storage_blobs.id = active_storage_attachments.blob_id") .find_by("JSON_CONTAINS(active_storage_blobs.metadata, :year, '$.year')", year:)&.blob&.url cdn_url_for(blob_url) if blob_url end def subscribe_preview_url cdn_url_for(subscribe_preview.url) if subscribe_preview.attached? rescue => e Rails.logger.warn("User#subscribe_preview_url error (#{id}): #{e.class} => #{e.message}") end def resized_avatar_url(size:) return ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png") unless avatar.attached? cdn_url_for(avatar.variant(resize_to_limit: [size, size]).processed.url) end def avatar_url return ActionController::Base.helpers.asset_url("gumroad-default-avatar-5.png") unless avatar.attached? cached_variant_url = Rails.cache.fetch("attachment_#{avatar.id}_variant_url") { avatar_variant.url } cdn_url_for(cached_variant_url) rescue => e Rails.logger.warn("User#avatar_url error (#{id}): #{e.class} => #{e.message}") avatar.url end def avatar_variant return unless avatar.attached? avatar.variant(resize_to_limit: [128, 128]).processed end def username read_attribute(:username).presence || external_id end def display_name(prefer_email_over_default_username: false) return name if name.present? return form_email || username.presence if prefer_email_over_default_username && username == external_id username.presence || form_email end def display_name_or_email display_name(prefer_email_over_default_username: true) end def support_or_form_email support_email.presence || form_email end def has_valid_payout_info? PayoutProcessorType.all.any? { PayoutProcessorType.get(_1).has_valid_payout_info?(self) } end def stripe_and_paypal_merchant_accounts_exist? merchant_account(StripeChargeProcessor.charge_processor_id) && paypal_connect_account end def stripe_or_paypal_merchant_accounts_exist? merchant_account(StripeChargeProcessor.charge_processor_id) || paypal_connect_account end def stripe_connect_account merchant_accounts.alive.charge_processor_alive.stripe.find { |ma| ma.is_a_stripe_connect_account? } end def paypal_connect_account merchant_account(PaypalChargeProcessor.charge_processor_id) end def stripe_account merchant_accounts.alive.charge_processor_alive.stripe.find { |ma| !ma.is_a_stripe_connect_account? } end def merchant_account(charge_processor_id) if charge_processor_id == StripeChargeProcessor.charge_processor_id if has_stripe_account_connected? stripe_connect_account else merchant_accounts.alive.charge_processor_alive.stripe .find { |ma| ma.can_accept_charges? && !ma.is_a_stripe_connect_account? } end else merchant_accounts.alive.charge_processor_alive.where(charge_processor_id:).find(&:can_accept_charges?) end end def merchant_account_currency(charge_processor_id) merchant_account = merchant_account(charge_processor_id) currency = merchant_account.try(:currency) || ChargeProcessor::DEFAULT_CURRENCY_CODE currency.upcase end # Public: Get the maximum product price for a user. # This is the maximum price that a user can receive in payment for a product. # The function returns nil if there is no maximum. # Returns: # β€’ nil for verified users # β€’ User::MAX_PRICE_USD_CENTS_UNLESS_VERIFIED for all other users def max_product_price return nil if verified MAX_PRICE_USD_CENTS_UNLESS_VERIFIED end def min_ppp_factor return 0 unless purchasing_power_parity_limit? 1 - purchasing_power_parity_limit / 100.0 end def purchasing_power_parity_excluded_product_external_ids products.purchasing_power_parity_disabled.map(&:external_id) end def update_purchasing_power_parity_excluded_products!(external_ids) products.purchasing_power_parity_disabled.or(products.by_external_ids(external_ids)).each do |product| should_disable = external_ids.include?(product.external_id) product.update!(purchasing_power_parity_disabled: should_disable) unless should_disable && product.purchasing_power_parity_disabled? end end def product_level_support_emails return unless product_level_support_emails_enabled? products .where.not(support_email: nil) .pluck(:support_email, :id) .group_by { |support_email, _| support_email } .map do |email, pairs| { email:, product_ids: pairs.map { |_, id| Link.to_external_id(id) } } end end def update_product_level_support_emails!(entries) Product::BulkUpdateSupportEmailService.new(self, entries).perform end def save_external_id return if external_id.present? found = false until found random = rand(9_999_999_999_999) if User.find_by_external_id(random.to_s).nil? self.external_id = random.to_s found = true end end end def self.serialize_from_session(key, _salt) # logged in user calls this to get users from sessions. redefined # so as to use the cache single_key = key.is_a?(Array) ? key.first : key find_by(id: single_key) end def admin_page_url Rails.application.routes.url_helpers.admin_user_url(self, protocol: PROTOCOL, host: DOMAIN) end def profile_url(custom_domain_url: nil, recommended_by: nil) uri = URI(custom_domain_url || subdomain_with_protocol) uri.query = { recommended_by: }.to_query if recommended_by.present? uri.to_s end alias_method :business_profile_url, :profile_url def credit_card_info(creator) return CreditCard.test_card_info if self == creator return credit_card.as_json if credit_card CreditCard.new_card_info end def user_info(creator) { email: form_email, full_name: name, profile_picture_url: avatar_url, shipping_information: { street_address:, zip_code:, state:, country:, city: }, card: credit_card_info(creator), admin: is_team_member? } end def name_or_username name.presence || username end def valid_password?(password) super(password) rescue BCrypt::Errors::InvalidHash logger.info "Account with sha256 password: #{inspect}" false end def is_buyer? !links.exists? && purchases.successful.exists? end def is_affiliate? DirectAffiliate.exists?(affiliate_user_id: id) end def account_active? alive? && !suspended? end def is_name_invalid_for_email_delivery? name.present? && name.match?(INVALID_NAME_FOR_EMAIL_DELIVERY_REGEX) end def deactivate! validate_account_closure_balances! ActiveRecord::Base.transaction do update!( deleted_at: Time.current, username: nil, credit_card_id: nil, payouts_paused_internally: true, ) links.each(&:delete!) installments.alive.each(&:mark_deleted!) user_compliance_infos.alive.each(&:mark_deleted!) bank_accounts.alive.each(&:mark_deleted!) cancel_active_subscriptions! invalidate_active_sessions! if custom_domain&.persisted? && !custom_domain.deleted? custom_domain.mark_deleted! end true rescue false end end def reactivate! self.deleted_at = nil save! end def mark_as_invited(referral_id) referral_user = User.find_by_external_id(referral_id) return unless referral_user invite = Invite.where(sender_id: referral_user.id).where(receiver_email: email).last invite = Invite.create(sender_id: referral_user.id, receiver_email: email, receiver_id: id) if invite.nil? invite.update!(receiver_id: id) invite.mark_signed_up end def email_domain to_email_domain(email) end def form_email unconfirmed_email.presence || email.presence end def form_email_domain to_email_domain(form_email) end def currency_symbol symbol_for(currency_type) end def self.find_for_database_authentication(warden_conditions) conditions = warden_conditions.dup login = conditions.delete(:login) where(conditions).where([ "email = :value OR username = :value", { value: login.strip.downcase } ]).first end def self.find_by_hostname(hostname) Subdomain.find_seller_by_hostname(hostname) || CustomDomain.find_by_host(hostname)&.user end def seller_profile super || build_seller_profile end def time_fields attributes.keys.keep_if { |key| key.include?("_at") && send(key) } end def clear_products_cache array_of_product_ids = links.ids.map { |product_id| [product_id] } InvalidateProductCacheWorker.perform_bulk(array_of_product_ids) end def generate_subscribe_preview raise "User must be persisted to generate a subscribe preview" unless persisted? GenerateSubscribePreviewJob.perform_async(id) end def insert_null_chargeback_state Mongoer.async_write("user_risk_state", { "user_id" => id.to_s, "chargeback_state" => nil }) end def minimum_payout_amount_cents [payout_threshold_cents, minimum_payout_threshold_cents].max end def minimum_payout_threshold_cents country_code = alive_user_compliance_info&.legal_entity_country_code country = Country.new(country_code) if country_code.present? [Payouts::MIN_AMOUNT_CENTS, country&.min_cross_border_payout_amount_usd_cents].compact.max end def active_bank_account bank_accounts.alive.first end def active_ach_account bank_accounts.alive.where("type = ?", AchAccount.name).first end def dismissed_audience_callout? Event.where(event_name: "audience_callout_dismissal", user_id: id).exists? end def has_workflows? workflows.alive.present? end # Public: Return the alive product files for the user # # product_id_to_exclude - Each product file belongs to a product, sometimes we do not want to display # product files of a certain product (if the user is on the edit page of that product). By passing this id we will # ignore product files for that product. def alive_product_files_excluding_product(product_id_to_exclude: nil) result_set = product_files.alive.merge(Link.alive) if product_id_to_exclude excluded_product = links.find_by(id: product_id_to_exclude) excluded_product_file_urls = excluded_product.alive_product_files.map(&:url) result_set = result_set.where.not(link_id: excluded_product.id) result_set = result_set.where.not(url: excluded_product_file_urls) if excluded_product_file_urls.present? end # Remove duplicate product files by url result_set.group(:url).includes(:subtitle_files, link: :user) end # Returns the user's product files by prioritizing the product files of # the given product over the the product files of the user's other products # that have the same `url` attribute. # This is sometimes needed (for an example, in the dynamic product content # editor), where we need a product's product files to be preferred over the # product files of other products among the duplicates having the same `url` # attribute. def alive_product_files_preferred_for_product(product) result_set = ProductFile.includes(:subtitle_files, link: :user).group(:url) product_file_urls = product.alive_product_files.pluck(:url) all_user_product_files = product_files.alive.merge(Link.alive) return result_set.merge(all_user_product_files) if product_file_urls.empty? product_files_not_belonging_to_product_query = all_user_product_files
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/saudi_arabia_bank_account.rb
app/models/saudi_arabia_bank_account.rb
# frozen_string_literal: true class SaudiArabiaBankAccount < BankAccount BANK_ACCOUNT_TYPE = "SA" BANK_CODE_FORMAT_REGEX = /^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$/ private_constant :BANK_CODE_FORMAT_REGEX alias_attribute :bank_code, :bank_number validate :validate_bank_code validate :validate_account_number def routing_number "#{bank_code}" end def bank_account_type BANK_ACCOUNT_TYPE end def country Compliance::Countries::SAU.alpha2 end def currency Currency::SAR end def account_number_visual "******#{account_number_last_four}" end def to_hash { routing_number:, account_number: account_number_visual, bank_account_type: } end private def validate_bank_code return if BANK_CODE_FORMAT_REGEX.match?(bank_code) errors.add :base, "The bank code is invalid." end def validate_account_number return if Ibandit::IBAN.new(account_number_decrypted).valid? errors.add :base, "The account number is invalid." end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/models/concerns/stripped_fields.rb
app/models/concerns/stripped_fields.rb
# frozen_string_literal: true # Strips whitespace from start and end, and optionally: # * converts blanks to nil # * removes duplicate spaces # * makes changes to the value # # Example: # # include StrippedFields # stripped_fields :code, nilify_blanks: false # stripped_fields :email, transform: -> { _1.downcase } # module StrippedFields extend ActiveSupport::Concern class_methods do def stripped_fields(*fields, remove_duplicate_spaces: true, transform: nil, nilify_blanks: true, **options) before_validation(options) do |object| fields.each do |field| StrippedFields::StrippedField.before_validation( object, field, remove_duplicate_spaces:, transform:, nilify_blanks: ) end end end end module StrippedField extend self def before_validation(object, field, remove_duplicate_spaces:, transform:, nilify_blanks:) value = object.read_attribute(field) value = strip(value) value = remove_duplicate_spaces(value, enabled: remove_duplicate_spaces) value = transform(value, transform:) value = nilify_blanks(value, enabled: nilify_blanks) object.send("#{field}=", value) end private def strip(value) value.to_s.strip || "" end def remove_duplicate_spaces(value, enabled:) value = value.squeeze(" ") if enabled value end def transform(value, transform:) value = transform.call(value) if transform.present? && value.present? value end def nilify_blanks(value, enabled:) value = nil if enabled && value.blank? value 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/two_factor_authentication.rb
app/models/concerns/two_factor_authentication.rb
# frozen_string_literal: true module TwoFactorAuthentication extend ActiveSupport::Concern DEFAULT_AUTH_TOKEN = "000000" TOKEN_VALIDITY = 10.minutes TWO_FACTOR_AUTH_EXPIRY = 2.months TWO_FACTOR_COOKIE_NAME_PREFIX = "_gumroad_two_factor_" class_methods do def find_by_encrypted_external_id(external_id) decrypted_external_id = ObfuscateIds.decrypt(external_id) find_by_external_id(decrypted_external_id) end end def encrypted_external_id ObfuscateIds.encrypt(external_id) end def two_factor_authentication_cookie_key # We set a unique cookie for each user in the browser to remember 2FA status for # multiple accounts from the same browser. # # The unique string we use in cookie name shouldn't be guessable. If we use user.external_id, # a scammer might be able to get that from public pages of that user. Here, we encrypt the external_id # using a cipher key known only to us which makes it unguessable. encrypted_id_sha = Digest::SHA256.hexdigest(encrypted_external_id)[0..12] "#{TWO_FACTOR_COOKIE_NAME_PREFIX}#{encrypted_id_sha}" end def send_authentication_token! TwoFactorAuthenticationMailer.authentication_token(id).deliver_later(queue: "critical") end def add_two_factor_authenticated_ip!(remote_ip) two_factor_auth_redis_namespace.set(two_factor_auth_ip_redis_key(remote_ip), true, ex: TWO_FACTOR_AUTH_EXPIRY.to_i) end def token_authenticated?(authentication_token) return true if authenticate_otp(authentication_token, drift: TOKEN_VALIDITY).present? # Allow 000000 as valid authentication token in all non-production environments !Rails.env.production? && authentication_token == DEFAULT_AUTH_TOKEN end def has_logged_in_from_ip_before?(remote_ip) two_factor_auth_redis_namespace.get(two_factor_auth_ip_redis_key(remote_ip)).present? end def two_factor_auth_redis_namespace @two_factor_auth_redis_namespace ||= Redis::Namespace.new(:two_factor_auth_redis_namespace, redis: $redis) end private def two_factor_auth_ip_redis_key(remote_ip) "auth_ip_#{id}_#{remote_ip}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false