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/sidekiq/delete_old_versions_records_worker.rb
app/sidekiq/delete_old_versions_records_worker.rb
# frozen_string_literal: true class DeleteOldVersionsRecordsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low MAX_ALLOWED_ROWS = 100_000_000 DELETION_BATCH_SIZE = 100 # Counting rows is not free, so we're relying on the fact that ids are consecutive instead. def perform max_id = PaperTrail::Version.maximum(:id) return if max_id.nil? minimum_id_to_keep = max_id - MAX_ALLOWED_ROWS loop do ReplicaLagWatcher.watch rows = PaperTrail::Version.where("id <= ?", minimum_id_to_keep).limit(DELETION_BATCH_SIZE) break if rows.delete_all.zero? end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_missing_purchase_events_worker.rb
app/sidekiq/create_missing_purchase_events_worker.rb
# frozen_string_literal: true class CreateMissingPurchaseEventsWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low def perform(date = Date.yesterday) purchases = Purchase.successful.left_joins(:events). where("purchases.created_at >= ? and purchases.created_at < ?", date, date.tomorrow). where("purchases.preorder_id is null and events.id is null") analytics_days_to_regenerate = Set.new purchases.find_each do |purchase| Event.create!( event_name: "purchase", created_at: purchase.created_at, user_id: purchase.purchaser_id, link_id: purchase.link_id, purchase_id: purchase.id, ip_address: purchase.ip_address, referrer: purchase.referrer, referrer_domain: Referrer.extract_domain(purchase.referrer), price_cents: purchase.price_cents, card_type: purchase.card_type, card_visual: purchase.card_visual, purchase_state: purchase.purchase_state, billing_zip: purchase.zip_code, ip_country: purchase.ip_country, ip_state: purchase.ip_state, browser_guid: purchase.browser_guid, manufactured: true, ) analytics_days_to_regenerate << [purchase.seller_id, purchase.created_at.in_time_zone(purchase.seller.timezone).to_date.to_s] end analytics_days_to_regenerate.each do |(seller_id, date_string)| RegenerateCreatorAnalyticsCacheWorker.perform_async(seller_id, date_string) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/payout_users_worker.rb
app/sidekiq/payout_users_worker.rb
# frozen_string_literal: true class PayoutUsersWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :default, lock: :until_executed def perform(date_string, processor_type, user_ids, payout_type = Payouts::PAYOUT_TYPE_STANDARD) PayoutUsersService.new(date_string:, processor_type:, user_ids:, payout_type:).process end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/renew_facebook_access_tokens_worker.rb
app/sidekiq/renew_facebook_access_tokens_worker.rb
# frozen_string_literal: true class RenewFacebookAccessTokensWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :critical def perform users = User.where("updated_at > ? AND facebook_access_token IS NOT NULL", Date.today - 30) users.find_each do |user| user.renew_facebook_access_token user.save end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/block_suspended_account_ip_worker.rb
app/sidekiq/block_suspended_account_ip_worker.rb
# frozen_string_literal: true class BlockSuspendedAccountIpWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_id) user = User.find(user_id) return if user.last_sign_in_ip.blank? return if User.where( "(current_sign_in_ip = :ip OR last_sign_in_ip = :ip OR account_created_ip = :ip) and user_risk_state = :risk_state", { ip: user.last_sign_in_ip, risk_state: "compliant" } ).exists? BlockedObject.block!( BLOCKED_OBJECT_TYPES[:ip_address], user.last_sign_in_ip, nil, expires_in: BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/purge_old_deleted_asset_previews_worker.rb
app/sidekiq/purge_old_deleted_asset_previews_worker.rb
# frozen_string_literal: true class PurgeOldDeletedAssetPreviewsWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low DELETION_BATCH_SIZE = 100 def perform(to: 1.month.ago) loop do asset_previews = AssetPreview.deleted.where("deleted_at < ?", to).limit(DELETION_BATCH_SIZE).load break if asset_previews.empty? ReplicaLagWatcher.watch asset_previews.each(&:destroy!) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_large_sellers_analytics_cache_worker.rb
app/sidekiq/generate_large_sellers_analytics_cache_worker.rb
# frozen_string_literal: true class GenerateLargeSellersAnalyticsCacheWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low, lock: :until_executed def perform User.joins(:large_seller).find_each do |user| CreatorAnalytics::CachingProxy.new(user).generate_cache rescue => e Bugsnag.notify(e) do |report| report.add_tab(:user_info, id: user.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/schedule_membership_price_updates_job.rb
app/sidekiq/schedule_membership_price_updates_job.rb
# frozen_string_literal: true class ScheduleMembershipPriceUpdatesJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(tier_id) tier = Variant.find(tier_id) return unless tier.apply_price_changes_to_existing_memberships? product = tier.link return unless product.is_tiered_membership? product.subscriptions.includes(original_purchase: :variant_attributes).find_each do |subscription| next if subscription.charges_completed? || subscription.deactivated? next unless subscription.for_tier?(tier) effective_on = subscription.end_time_of_subscription effective_on += subscription.period until effective_on >= tier.subscription_price_change_effective_date original_purchase = subscription.original_purchase plan_change = subscription.latest_plan_change selected_tier = plan_change.present? ? plan_change.tier : subscription.tier next if selected_tier.id != tier_id selected_recurrence = plan_change.present? ? plan_change.recurrence : subscription.recurrence existing_price = plan_change.present? ? plan_change.perceived_price_cents : original_purchase.displayed_price_cents new_price = nil if plan_change.present? ActiveRecord::Base.transaction do new_product_price = subscription.link.prices.is_buy.alive.find_by(recurrence: plan_change.recurrence) || subscription.link.prices.is_buy.find_by(recurrence: plan_change.recurrence) # use live price if exists, else deleted price begin subscription.update_current_plan!( new_variants: [plan_change.tier], new_price: new_product_price, new_quantity: plan_change.quantity, is_applying_plan_change: true, skip_preparing_for_charge: true, ) rescue Subscription::UpdateFailed => e Rails.logger.info("ScheduleMembershipPriceUpdatesJob failed for #{subscription.id}: #{e.class} (#{e.message})") raise ActiveRecord::Rollback end new_price = subscription.reload.original_purchase.displayed_price_cents raise ActiveRecord::Rollback end else ActiveRecord::Base.transaction do original_purchase.set_price_and_rate new_price = original_purchase.displayed_price_cents raise ActiveRecord::Rollback end end if new_price.nil? || new_price <= 0 || existing_price == new_price reason = if new_price.nil? "nil price" elsif new_price <= 0 "zero or negative price (#{new_price})" else "price has not changed" end Bugsnag.notify("Not adding a plan change for membership price change - subscription_id: #{subscription.id} - reason: #{reason}") next end Rails.logger.info("Adding a plan change for membership price change - subscription_id: #{subscription.id}, tier_id: #{tier_id}, effective_on: #{effective_on}") new_plan_change = subscription.subscription_plan_changes.create!(tier: selected_tier, recurrence: selected_recurrence, perceived_price_cents: new_price, for_product_price_change: true, effective_on:) subscription.subscription_plan_changes.for_product_price_change.alive.where.not(id: new_plan_change.id).each(&:mark_deleted!) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_stripe_currency_balances_report_job.rb
app/sidekiq/send_stripe_currency_balances_report_job.rb
# frozen_string_literal: true class SendStripeCurrencyBalancesReportJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace def perform return unless Rails.env.production? balances_csv = StripeCurrencyBalancesReport.stripe_currency_balances_report AccountingMailer.stripe_currency_balances_report(balances_csv).deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_bundles_marketing_email_job.rb
app/sidekiq/send_bundles_marketing_email_job.rb
# frozen_string_literal: true class SendBundlesMarketingEmailJob MINIMUM_PRODUCTS_PER_BUNDLE = 2 LAST_YEAR = 1.year.ago.year def perform User.not_suspended .where(deleted_at: nil) .joins(:payments) .merge(Payment.completed.where(created_at: 1.year.ago..)) .select("users.id, users.currency_type") .distinct .find_in_batches do |group| ReplicaLagWatcher.watch group.each do |user| user_id = user.id currency_type = user.currency_type options = { user_id:, sort: ProductSortKey::FEATURED, is_alive_on_profile: true, is_subscription: false, is_bundle: false, } best_selling_products = Link.search(Link.search_options(options.merge({ sort: ProductSortKey::HOT_AND_NEW }))) .records.records .filter { _1.price_currency_type == currency_type } .take(5) everything_products = Link.search(Link.search_options(options)) .records.records .filter { _1.price_currency_type == currency_type } year_products = everything_products.filter { _1.created_at.year == LAST_YEAR } bundles = [] bundles << bundle_props(Product::BundlesMarketing::BEST_SELLING_BUNDLE, best_selling_products) if best_selling_products.size >= MINIMUM_PRODUCTS_PER_BUNDLE bundles << bundle_props(Product::BundlesMarketing::EVERYTHING_BUNDLE, everything_products) if everything_products.size >= MINIMUM_PRODUCTS_PER_BUNDLE bundles << bundle_props(Product::BundlesMarketing::YEAR_BUNDLE, year_products) if year_products.size >= MINIMUM_PRODUCTS_PER_BUNDLE CreatorMailer.bundles_marketing(seller_id: user_id, bundles:).deliver_later if bundles.any? end end end private DISCOUNT_FACTOR = 0.8 def bundle_props(type, products) price = products.sum(&:display_price_cents) { type:, price:, discounted_price: price * DISCOUNT_FACTOR, products: products.map { { id: _1.external_id, name: _1.name, url: _1.long_url } } } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/end_subscription_worker.rb
app/sidekiq/end_subscription_worker.rb
# frozen_string_literal: true class EndSubscriptionWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) return if subscription.is_test_subscription? return unless subscription.alive?(include_pending_cancellation: false) return unless subscription.charges_completed? subscription.end_subscription! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/cache_unreviewed_users_data_worker.rb
app/sidekiq/cache_unreviewed_users_data_worker.rb
# frozen_string_literal: true class CacheUnreviewedUsersDataWorker include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform Admin::UnreviewedUsersService.cache_users_data! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/set_subscription_as_deactivated_worker.rb
app/sidekiq/set_subscription_as_deactivated_worker.rb
# frozen_string_literal: true class SetSubscriptionAsDeactivatedWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default, lock: :until_executed def perform(subscription_id) subscription = Subscription.find(subscription_id) return if subscription.alive? subscription.deactivate! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/block_email_domains_worker.rb
app/sidekiq/block_email_domains_worker.rb
# frozen_string_literal: true class BlockEmailDomainsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(author_id, email_domains) email_domains.each do |email_domain| BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], email_domain, author_id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/google_calendar_invite_job.rb
app/sidekiq/google_calendar_invite_job.rb
# frozen_string_literal: true class GoogleCalendarInviteJob include Sidekiq::Job def perform(call_id) call = Call.find(call_id) return if call.google_calendar_event_id.present? link = call.link buyer = call.purchase.purchaser&.email || call.purchase.email google_calendar_integration = link.get_integration(Integration.type_for(Integration::GOOGLE_CALENDAR)) return unless google_calendar_integration gcal_api = GoogleCalendarApi.new event = { summary: "Call with #{buyer}", description: "Scheduled call for #{link.name}", start: { dateTime: call.start_time.iso8601, }, end: { dateTime: call.end_time.iso8601, }, attendees: [ { email: buyer } ], reminders: { useDefault: true } } response = insert_or_refresh_and_insert_event(gcal_api, google_calendar_integration, event) if response.success? call.update(google_calendar_event_id: response.parsed_response["id"]) else Rails.logger.error "Failed to insert Google Calendar event: #{response.parsed_response}" end end private def insert_or_refresh_and_insert_event(gcal_api, integration, event) response = insert_event(gcal_api, integration, event) return response if response.success? if response.code == 401 new_access_token = refresh_token(gcal_api, integration) return insert_event(gcal_api, integration, event, new_access_token) if new_access_token end response end def insert_event(gcal_api, integration, event, access_token = nil) access_token ||= integration.access_token response = gcal_api.insert_event(integration.calendar_id, event, access_token:) response end def refresh_token(gcal_api, integration) refresh_response = gcal_api.refresh_token(integration.refresh_token) if refresh_response.success? new_access_token = refresh_response.parsed_response["access_token"] integration.update(access_token: new_access_token) new_access_token else Rails.logger.error "Failed to refresh Google Calendar token: #{refresh_response.parsed_response}" nil end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/annual_payout_export_worker.rb
app/sidekiq/annual_payout_export_worker.rb
# frozen_string_literal: true class AnnualPayoutExportWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low def perform(user_id, year, send_email = false) user = User.find user_id payout_data = nil WithMaxExecutionTime.timeout_queries(seconds: 1.hour) do payout_data = Exports::Payouts::Annual.new(user:, year:).perform end if payout_data && payout_data[:csv_file] && payout_data[:total_amount] > 0 csv_file = payout_data[:csv_file] if user.financial_annual_report_url_for(year:).nil? user.annual_reports.attach( io: csv_file, filename: "Financial summary for #{year}.csv", content_type: "text/csv", metadata: { year: } ) end if send_email ContactingCreatorMailer.annual_payout_summary(user_id, year, payout_data[:total_amount]).deliver_now end end ensure if defined?(csv_file) && csv_file.respond_to?(:unlink) # https://ruby-doc.org/stdlib-2.7.0/libdoc/tempfile/rdoc/Tempfile.html#class-Tempfile-label-Explicit+close csv_file.close csv_file.unlink end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/seller_updates_worker.rb
app/sidekiq/seller_updates_worker.rb
# frozen_string_literal: true class SellerUpdatesWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed def perform User.by_sales_revenue(days_ago: 7.days.ago, limit: nil) do |user| SellerUpdateWorker.perform_async(user.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/calculate_sale_numbers_worker.rb
app/sidekiq/calculate_sale_numbers_worker.rb
# frozen_string_literal: true class CalculateSaleNumbersWorker include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform calculate_stats_for_all_purchases end private def calculate_stats_for_all_purchases aggregations_body = { total_made: { sum: { field: "price_cents" } }, number_of_creators: { cardinality: { field: "seller_id", precision_threshold: 40_000 } # 40k is the max threshold # When the actual cardinality is more than 40k expect a 0-2% error rate. # This would matter when updating values in real time. We should make sure that we don't store a value # less than what's already stored. } } search_options = { price_greater_than: 0, state: "successful", size: 0, exclude_unreversed_chargedback: true, exclude_refunded: true, exclude_bundle_product_purchases: true, aggs: aggregations_body } purchase_search = PurchaseSearchService.new(search_options) aggregations = purchase_search.process.aggregations total_made_in_usd = aggregations.total_made.value.to_i / 100 number_of_creators = aggregations.number_of_creators.value $redis.set(RedisKey.total_made, total_made_in_usd) $redis.set(RedisKey.number_of_creators, number_of_creators) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/stamp_pdf_for_purchase_job.rb
app/sidekiq/stamp_pdf_for_purchase_job.rb
# frozen_string_literal: true # Stamps PDF(s) for a purchase class StampPdfForPurchaseJob include Sidekiq::Job sidekiq_options queue: :default, retry: 5, lock: :until_executed def perform(purchase_id, notify_buyer = false) purchase = Purchase.find(purchase_id) PdfStampingService.stamp_for_purchase!(purchase) if notify_buyer CustomerMailer.files_ready_for_download(purchase_id).deliver_later(queue: "critical") # Invalidate the cache after sending the email notification Rails.cache.delete(PdfStampingService.cache_key_for_purchase(purchase_id)) end rescue PdfStampingService::Error => e Rails.logger.error("[#{self.class.name}.#{__method__}] Failed stamping for purchase #{purchase.id}: #{e.message}") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_stripe_autodebit_for_negative_balance.rb
app/sidekiq/handle_stripe_autodebit_for_negative_balance.rb
# frozen_string_literal: true class HandleStripeAutodebitForNegativeBalance include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(stripe_event_id, stripe_connect_account_id, stripe_payout_id) @stripe_connect_account_id = stripe_connect_account_id @stripe_payout_id = stripe_payout_id if debit_success? StripePayoutProcessor.handle_stripe_negative_balance_debit_event(stripe_connect_account_id, stripe_payout_id) elsif debit_failed? # The debit payout that was once reported as `paid`, has now transitioned to `failed`. # We waited for it to either complete its balance transaction, or to fail. It failed, so nothing for us to do. else raise "Timed out waiting for payout to become finalized (to transition to `failed` state or its balance transaction "\ "to transition to `available` state). Stripe event ID: #{stripe_event_id}." end end private attr_reader :stripe_payout_id, :stripe_connect_account_id def debit_success? balance_transaction_completed? && (payout["status"] == "paid") end def balance_transaction_completed? payout["balance_transaction"]["status"] == "available" end def debit_failed? payout["status"] == "failed" end def payout @_payout ||= Stripe::Payout.retrieve( { id: stripe_payout_id, expand: %w[balance_transaction] }, { stripe_account: stripe_connect_account_id } ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_sns_transcoder_event_worker.rb
app/sidekiq/handle_sns_transcoder_event_worker.rb
# frozen_string_literal: true class HandleSnsTranscoderEventWorker include Sidekiq::Job include TranscodeEventHandler sidekiq_options retry: 5, queue: :default def perform(params) if params["Type"] == "Notification" message = JSON.parse(params["Message"]) job_id = message["jobId"] state = message["state"] handle_transcoding_job_notification(job_id, state) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/analyze_file_worker.rb
app/sidekiq/analyze_file_worker.rb
# frozen_string_literal: true class AnalyzeFileWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low, lock: :until_executed def perform(id, analyzable_klass_name = ProductFile.name) return if Rails.env.test? analyzable_klass_name.constantize.find(id).analyze rescue Aws::S3::Errors::NotFound => e Rails.logger.info("AnalyzeFileWorker failed: Could not analyze #{analyzable_klass_name} #{id} (#{e.class}: #{e.message})") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/calculate_payout_numbers_worker.rb
app/sidekiq/calculate_payout_numbers_worker.rb
# frozen_string_literal: true class CalculatePayoutNumbersWorker include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform now = Time.now.in_time_zone("America/Los_Angeles") beginning_of_last_week = now.prev_week end_of_last_week = beginning_of_last_week.end_of_week search_result = PurchaseSearchService.new( price_greater_than: 0, state: "successful", size: 0, exclude_unreversed_chargedback: true, exclude_refunded: true, exclude_bundle_product_purchases: true, created_on_or_after: beginning_of_last_week, created_on_or_before: end_of_last_week, aggs: { total_made: { sum: { field: "price_cents" } } } ).process total_made_in_usd = search_result.aggregations.total_made.value / 100.to_d $redis.set(RedisKey.prev_week_payout_usd, total_made_in_usd.to_i) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_charge_receipt_job.rb
app/sidekiq/send_charge_receipt_job.rb
# frozen_string_literal: true # Job used to send the initial receipt email after checkout for a given charge. # If there are PDFs that need to be stamped, the caller must enqueue this job using the "default" queue # class SendChargeReceiptJob include Sidekiq::Job sidekiq_options queue: :critical, retry: 5, lock: :until_executed def perform(charge_id) charge = Charge.find(charge_id) return if charge.receipt_sent? charge.purchases_requiring_stamping.each do |purchase| PdfStampingService.stamp_for_purchase!(purchase) end charge.with_lock do CustomerMailer.receipt(nil, charge.id).deliver_now charge.update!(receipt_sent: true) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_community_chat_recap_notifications_job.rb
app/sidekiq/send_community_chat_recap_notifications_job.rb
# frozen_string_literal: true class SendCommunityChatRecapNotificationsJob include Sidekiq::Job sidekiq_options queue: :low, lock: :until_executed def perform(community_chat_recap_run_id) recap_run = CommunityChatRecapRun.find(community_chat_recap_run_id) return unless recap_run.finished? community_recap_ids_by_community = recap_run .community_chat_recaps .status_finished .pluck(:id, :community_id) .each_with_object({}) do |(id, community_id), hash| hash[community_id] ||= [] hash[community_id] << id end return if community_recap_ids_by_community.empty? notification_settings_by_user = CommunityNotificationSetting .where(recap_frequency: recap_run.recap_frequency) .order(:user_id) .includes(:user) .group_by(&:user_id) return if notification_settings_by_user.empty? community_ids_by_seller = Community .alive .where(seller_id: notification_settings_by_user.values.flatten.map(&:seller_id).uniq) .pluck(:id, :seller_id) .each_with_object({}) do |(id, seller_id), hash| hash[seller_id] ||= [] hash[seller_id] << id end return if community_ids_by_seller.empty? notification_settings_by_user.each do |user_id, settings| next if settings.empty? accessible_community_ids = settings.first.user.accessible_communities_ids settings.each do |setting| seller_community_ids = (community_ids_by_seller[setting.seller_id] || []) & accessible_community_ids next if seller_community_ids.empty? seller_community_recap_ids = seller_community_ids.map { community_recap_ids_by_community[_1] }.flatten.compact next if seller_community_recap_ids.empty? Rails.logger.info("Sending recap notification to user #{user_id} for seller #{setting.seller_id} for recaps: #{seller_community_recap_ids}") CommunityChatRecapMailer.community_chat_recap_notification( user_id, setting.seller_id, seller_community_recap_ids ).deliver_later end end rescue => e Rails.logger.error("Error sending community recap notifications: #{e.full_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/sidekiq/delete_old_sent_email_info_records_job.rb
app/sidekiq/delete_old_sent_email_info_records_job.rb
# frozen_string_literal: true class DeleteOldSentEmailInfoRecordsJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low VALID_DURATION = 1.year DELETION_BATCH_SIZE = 100 def perform return unless SentEmailInfo.exists? loop do ReplicaLagWatcher.watch rows = SentEmailInfo.where("created_at < ?", VALID_DURATION.ago).limit(DELETION_BATCH_SIZE) break if rows.delete_all.zero? end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/reissue_ssl_certificate_for_updated_custom_domains.rb
app/sidekiq/reissue_ssl_certificate_for_updated_custom_domains.rb
# frozen_string_literal: true class ReissueSslCertificateForUpdatedCustomDomains include Sidekiq::Job sidekiq_options retry: 0, queue: :low def perform CustomDomain.alive.where.not(ssl_certificate_issued_at: nil).find_each do |custom_domain| verification_service = CustomDomainVerificationService.new(domain: custom_domain.domain) unless verification_service.has_valid_ssl_certificates? custom_domain.reset_ssl_certificate_issued_at! custom_domain.generate_ssl_certificate end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/expire_stamped_pdfs_job.rb
app/sidekiq/expire_stamped_pdfs_job.rb
# frozen_string_literal: true class ExpireStampedPdfsJob include Sidekiq::Job sidekiq_options queue: :low, retry: 5 RECENTNESS_LIMIT = 3.months BATCH_SIZE = 100 def perform loop do ReplicaLagWatcher.watch records = StampedPdf.alive.includes(:url_redirect, :product_file).where(created_at: .. RECENTNESS_LIMIT.ago).limit(BATCH_SIZE).load break if records.empty? records.each(&:mark_deleted!) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_vat_report_job.rb
app/sidekiq/create_vat_report_job.rb
# frozen_string_literal: true class CreateVatReportJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace DEFAULT_VAT_RATE_TYPE = "Standard" REDUCED_VAT_RATE_TYPE = "Reduced" def perform(quarter, year) raise ArgumentError, "Invalid quarter" unless quarter.in?(1..4) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) s3_report_key = "sales-tax/vat-quarterly/vat-report-Q#{quarter}-#{year}-#{SecureRandom.hex(4)}.csv" row_headers = ["Member State of Consumption", "VAT rate type", "VAT rate in Member State", "Total value of supplies excluding VAT (USD)", "Total value of supplies excluding VAT (Estimated, USD)", "VAT amount due (USD)", "Total value of supplies excluding VAT (GBP)", "Total value of supplies excluding VAT (Estimated, GBP)", "VAT amount due (GBP)"] begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) ZipTaxRate.where(state: nil, user_id: nil).each do |zip_tax_rate| next unless zip_tax_rate.combined_rate > 0 total_excluding_vat_cents = 0 total_vat_cents = 0 total_excluding_vat_cents_estimated = 0 total_excluding_vat_cents_in_gbp = 0 total_vat_cents_in_gbp = 0 total_excluding_vat_cents_estimated_in_gbp = 0 start_date_of_quarter = Date.new(year, (1 + 3 * (quarter - 1)).to_i).beginning_of_month end_date_of_quarter = Date.new(year, (3 + 3 * (quarter - 1)).to_i).end_of_month (start_date_of_quarter..end_date_of_quarter).each do |date| conversion_rate = gbp_to_usd_rate_for_date(date) vat_purchases_on_date = zip_tax_rate.purchases .where("purchase_state != 'failed'") .where("stripe_transaction_id IS NOT NULL") .not_chargedback .where(created_at: date.beginning_of_day..date.end_of_day) vat_chargeback_won_purchases_on_date = zip_tax_rate.purchases .where("purchase_state != 'failed'") .chargedback .where("flags & :bit = :bit", bit: Purchase.flag_mapping["flags"][:chargeback_reversed]) .where(created_at: date.beginning_of_day..date.end_of_day) vat_refunds_on_date = zip_tax_rate.purchases .where("purchase_state != 'failed'") .joins(:refunds) .where(created_at: date.beginning_of_day..date.end_of_day) total_purchase_excluding_vat_amount_cents = vat_purchases_on_date.sum(:price_cents) total_purchase_vat_cents = vat_purchases_on_date.sum(:gumroad_tax_cents) total_purchase_excluding_vat_amount_cents += vat_chargeback_won_purchases_on_date.sum(:price_cents) total_purchase_vat_cents += vat_chargeback_won_purchases_on_date.sum(:gumroad_tax_cents) total_refund_excluding_vat_amount_cents = nil total_refund_vat_cents = nil timeout_seconds = ($redis.get(RedisKey.create_vat_report_job_max_execution_time_seconds) || 1.hour).to_i WithMaxExecutionTime.timeout_queries(seconds: timeout_seconds) do total_refund_excluding_vat_amount_cents = vat_refunds_on_date.sum("refunds.amount_cents") total_refund_vat_cents = vat_refunds_on_date.sum("refunds.gumroad_tax_cents") end total_excluding_vat_cents += total_purchase_excluding_vat_amount_cents - total_refund_excluding_vat_amount_cents total_excluding_vat_cents_estimated += (total_purchase_vat_cents - total_refund_vat_cents) / zip_tax_rate.combined_rate total_vat_cents += total_purchase_vat_cents - total_refund_vat_cents total_excluding_vat_cents_in_gbp += (total_purchase_excluding_vat_amount_cents - total_refund_excluding_vat_amount_cents) / conversion_rate total_excluding_vat_cents_estimated_in_gbp += ((total_purchase_vat_cents - total_refund_vat_cents) / zip_tax_rate.combined_rate) / conversion_rate total_vat_cents_in_gbp += (total_purchase_vat_cents - total_refund_vat_cents) / conversion_rate end temp_file.write([ISO3166::Country[zip_tax_rate.country].common_name, zip_tax_rate.is_epublication_rate ? REDUCED_VAT_RATE_TYPE : DEFAULT_VAT_RATE_TYPE, zip_tax_rate.combined_rate * 100, Money.new(total_excluding_vat_cents, :usd).format(no_cents_if_whole: false, symbol: false), Money.new(total_excluding_vat_cents_estimated, :usd).format(no_cents_if_whole: false, symbol: false), Money.new(total_vat_cents, :usd).format(no_cents_if_whole: false, symbol: false), Money.new(total_excluding_vat_cents_in_gbp, :usd).format(no_cents_if_whole: false, symbol: false), Money.new(total_excluding_vat_cents_estimated_in_gbp, :usd).format(no_cents_if_whole: false, symbol: false), Money.new(total_vat_cents_in_gbp, :usd).format(no_cents_if_whole: false, symbol: false)].to_csv) temp_file.flush end temp_file.rewind s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s AccountingMailer.vat_report(quarter, year, s3_signed_url).deliver_now SlackMessageWorker.perform_async("payments", "VAT Reporting", "Q#{quarter} #{year} VAT report is ready - #{s3_signed_url}", "green") ensure temp_file.close end end private def gbp_to_usd_rate_for_date(date) formatted_date = date.strftime("%Y-%m-%d") api_url = "#{OPEN_EXCHANGE_RATES_API_BASE_URL}/historical/#{formatted_date}.json?app_id=#{OPEN_EXCHANGE_RATE_KEY}&base=GBP" JSON.parse(URI.open(api_url).read)["rates"]["USD"] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_to_elasticsearch_worker.rb
app/sidekiq/send_to_elasticsearch_worker.rb
# frozen_string_literal: true class SendToElasticsearchWorker include Sidekiq::Job sidekiq_options retry: 10, queue: :default def perform(link_id, action, attributes_to_update = []) return if (product = Link.find_by(id: link_id)).nil? ProductIndexingService.perform( product:, action:, attributes_to_update: ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/perform_daily_instant_payouts_worker.rb
app/sidekiq/perform_daily_instant_payouts_worker.rb
# frozen_string_literal: true class PerformDailyInstantPayoutsWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :critical, lock: :until_executed def perform payout_period_end_date = Date.yesterday Rails.logger.info("AUTOMATED DAILY INSTANT PAYOUTS: #{payout_period_end_date} (Started)") Payouts.create_instant_payouts_for_balances_up_to_date(payout_period_end_date) Rails.logger.info("AUTOMATED DAILY INSTANT PAYOUTS: #{payout_period_end_date} (Finished)") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_deferred_refunds_report_worker.rb
app/sidekiq/send_deferred_refunds_report_worker.rb
# frozen_string_literal: true class SendDeferredRefundsReportWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace def perform return unless Rails.env.production? last_month = Time.current.last_month AccountingMailer.deferred_refunds_report(last_month.month, last_month.year).deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_sns_mediaconvert_event_worker.rb
app/sidekiq/handle_sns_mediaconvert_event_worker.rb
# frozen_string_literal: true class HandleSnsMediaconvertEventWorker include Sidekiq::Job include TranscodeEventHandler sidekiq_options retry: 5, queue: :default ERROR_STATUS = "ERROR" def perform(notification) return unless notification["Type"] == "Notification" message = JSON.parse(notification["Message"])["detail"] job_id = message["jobId"] transcoded_video = TranscodedVideo.find_by(job_id:) return if transcoded_video.nil? if message["status"] == ERROR_STATUS # Transcode in ETS ets_transcoder = TranscodeVideoForStreamingWorker::ETS TranscodeVideoForStreamingWorker.perform_in( 5.seconds, transcoded_video.streamable_id, transcoded_video.streamable_type, ets_transcoder ) transcoded_video.destroy! else handle_transcoding_job_notification(job_id, transcoded_state(message), transcoded_video_key(message)) end end private def transcoded_video_key(message) message["outputGroupDetails"] .first["playlistFilePaths"] .first .delete_prefix("s3://#{S3_BUCKET}/") # Strip protocol and bucket name from the file path end def transcoded_state(message) message["status"] == "COMPLETE" ? "COMPLETED" : message["status"] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_ssl_certificate.rb
app/sidekiq/generate_ssl_certificate.rb
# frozen_string_literal: true class GenerateSslCertificate include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(id) if SslCertificates::Generate.supported_environment? custom_domain = CustomDomain.find(id) return if custom_domain.deleted? # The domain was deleted after this job was enqueued SslCertificates::Generate.new(custom_domain).process end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/regenerate_sales_related_products_infos_job.rb
app/sidekiq/regenerate_sales_related_products_infos_job.rb
# frozen_string_literal: true # WARNING: This job can be very slow, and add a lot of rows to the DB. # It is only meant for rare cases, for example: improving quality of recommendations for a VIP creator's product. # It should NOT be run for more than a few of products at time. class RegenerateSalesRelatedProductsInfosJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(product_id, email_limit = 5_000, relationships_limit = 1_000, insert_batch_size = 10) product = Link.find(product_id) emails = Purchase .distinct .successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback .where(link_id: product_id) .where.not(email: nil) .limit(email_limit) .order(id: :desc) .pluck(:email) customer_counts = Purchase .successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback .where(email: emails) .where.not(link_id: product_id) .select(:link_id, "COUNT(DISTINCT(email)) as customer_count") .group(:link_id) .order(customer_count: :desc) .limit(relationships_limit) .to_a SalesRelatedProductsInfo.for_product_id(product.id).in_batches.delete_all now_string = %("#{Time.current.to_fs(:db)}") inserts = customer_counts.map do |record| smaller_id, larger_id = [product_id, record.link_id].sort [smaller_id, larger_id, record.customer_count, now_string, now_string].join(", ") end.map { "(#{_1})" } # Small slices to avoid deadlocks. inserts.each_slice(insert_batch_size) do |inserts_slice| inserts_sql_slice = inserts_slice.join(", ") query = <<~SQL INSERT IGNORE INTO #{SalesRelatedProductsInfo.table_name} (smaller_product_id, larger_product_id, sales_count, created_at, updated_at) VALUES #{inserts_sql_slice}; SQL ApplicationRecord.connection.execute(query) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_tax_rates_job.rb
app/sidekiq/update_tax_rates_job.rb
# frozen_string_literal: true class UpdateTaxRatesJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform summary_rates = client.summary_rates summary_rates.select { |summary_rate| Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.include?(summary_rate.country_code) || tax_jar_country_codes_map[summary_rate.country_code].present? }.each do |summary_rate| next unless summary_rate.average_rate.rate > 0 country_code = tax_jar_country_codes_map[summary_rate.country_code] || summary_rate.country_code zip_tax_rate = ZipTaxRate.not_is_epublication_rate.alive.where(country: country_code).first if zip_tax_rate if zip_tax_rate.combined_rate != summary_rate.average_rate.rate SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "VAT rate has changed for #{country_code} from #{zip_tax_rate.combined_rate} to #{summary_rate.average_rate.rate}", "green") zip_tax_rate.combined_rate = summary_rate.average_rate.rate zip_tax_rate.save! end else SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "Creating missing tax rate for #{country_code} with rate of #{summary_rate.average_rate.rate}", "green") zip_tax_rate = ZipTaxRate.not_is_epublication_rate.find_or_create_by(country: country_code) zip_tax_rate.update(combined_rate: summary_rate.average_rate.rate) # Make sure the tax rate was not in deleted state instead zip_tax_rate.mark_undeleted! end end summary_rates.select { |summary_rate| summary_rate.country_code == Compliance::Countries::USA.alpha2 }.each do |summary_rate| state = summary_rate.region_code next unless Compliance::Countries.taxable_state?(state) next unless summary_rate.average_rate.rate > 0 zip_tax_rate = ZipTaxRate.alive .where(country: Compliance::Countries::USA.alpha2, state:, zip_code: nil) .not_is_epublication_rate .first is_seller_responsible = !Compliance::Countries.taxable_state?(state) if zip_tax_rate if zip_tax_rate.combined_rate != summary_rate.average_rate.rate || is_seller_responsible != zip_tax_rate.is_seller_responsible SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "US Sales Tax rate for state #{state} has changed. Rate was #{zip_tax_rate.combined_rate}, now it's #{summary_rate.average_rate.rate}. is_seller_responsible was #{zip_tax_rate.is_seller_responsible}, now it's #{is_seller_responsible}", "green") zip_tax_rate.combined_rate = summary_rate.average_rate.rate zip_tax_rate.is_seller_responsible = is_seller_responsible zip_tax_rate.save! end else SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "Creating US Sales Tax rate for state #{state} with rate of #{summary_rate.average_rate.rate} and is_seller_responsible #{is_seller_responsible}", "green") ZipTaxRate.create!( country: "US", state:, zip_code: nil, combined_rate: summary_rate.average_rate.rate, is_seller_responsible: ) end end summary_rates.select { |summary_rate| summary_rate.country_code == Compliance::Countries::CAN.alpha2 }.each do |summary_rate| province = summary_rate.region_code next unless Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map(&:first).include?(province) zip_tax_rate = ZipTaxRate.alive .where(country: Compliance::Countries::CAN.alpha2, state: province) .not_is_epublication_rate .first if zip_tax_rate if zip_tax_rate.combined_rate != summary_rate.average_rate.rate SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "Canada Sales Tax rate for province #{province} has changed. Rate was #{zip_tax_rate.combined_rate}, now it's #{summary_rate.average_rate.rate}.", "green") zip_tax_rate.combined_rate = summary_rate.average_rate.rate zip_tax_rate.save! end else SlackMessageWorker.perform_async("payments", "VAT Rate Updater", "Creating Canada Sales Tax rate for province #{province} with rate of #{summary_rate.average_rate.rate}", "green") ZipTaxRate.create!( country: "CA", state: province, zip_code: nil, combined_rate: summary_rate.average_rate.rate ) end end end private def client @client ||= Taxjar::Client.new(api_key: TAXJAR_API_KEY, headers: { "x-api-version" => "2022-01-24" }, api_url: TAXJAR_ENDPOINT) end # TaxJar uses different county codes instead of sticking to ISO-3166-1 def tax_jar_country_codes_map { "EL" => "GR", "UK" => "GB" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_sendgrid_event_job.rb
app/sidekiq/handle_sendgrid_event_job.rb
# frozen_string_literal: true class HandleSendgridEventJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(params) events = params["_json"] events = [events] unless events.is_a?(Array) # Handling potential SendGrid weirdness where sometimes it might not give us an array. events.each do |event| sendgrid_event_info = SendgridEventInfo.new(event) next if sendgrid_event_info.invalid? HandleEmailEventInfo.perform(sendgrid_event_info) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_new_user_compliance_info_worker.rb
app/sidekiq/handle_new_user_compliance_info_worker.rb
# frozen_string_literal: true class HandleNewUserComplianceInfoWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_compliance_info_id) user_compliance_info = UserComplianceInfo.find(user_compliance_info_id) StripeMerchantAccountManager.handle_new_user_compliance_info(user_compliance_info) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/recurring_charge_reminder_worker.rb
app/sidekiq/recurring_charge_reminder_worker.rb
# frozen_string_literal: true class RecurringChargeReminderWorker include Sidekiq::Job sidekiq_options retry: 3, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) return if !subscription.alive?(include_pending_cancellation: false) || subscription.in_free_trial? || subscription.charges_completed? || !subscription.send_renewal_reminders? CustomerLowPriorityMailer.subscription_renewal_reminder(subscription_id).deliver_later(queue: "low") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_us_state_monthly_sales_reports_job.rb
app/sidekiq/create_us_state_monthly_sales_reports_job.rb
# frozen_string_literal: true # Usage example for the month of August 2022 in the state of Washington: # # CreateUsStateMonthlySalesReportsJob.perform_async("WA", 8, 2022) class CreateUsStateMonthlySalesReportsJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed attr_reader :taxjar_api def perform(subdivision_code, month, year) subdivision = Compliance::Countries::USA.subdivisions[subdivision_code].tap { |value| raise ArgumentError, "Invalid subdivision code" unless value } raise ArgumentError, "Invalid month" unless month.in?(1..12) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) @taxjar_api = TaxjarApi.new row_headers = [ "Purchase External ID", "Purchase Date", "Member State of Consumption", "Total Transaction", "Price", "Tax Collected by Gumroad", "Combined Tax Rate", "Calculated Tax Amount", "Jurisdiction State", "Jurisdiction County", "Jurisdiction City", "State Tax Rate", "County Tax Rate", "City Tax Rate", "Amount not collected by Gumroad", "Gumroad Product Type", "TaxJar Product Tax Code", ] purchase_ids = Purchase.successful .not_fully_refunded .not_chargedback_or_chargedback_reversed .where.not(stripe_transaction_id: nil) .where("purchases.created_at BETWEEN ? AND ?", Date.new(year, month).beginning_of_month.beginning_of_day, Date.new(year, month).end_of_month.end_of_day) .where("(country = 'United States') OR ((country IS NULL OR country = 'United States') AND ip_country = 'United States')") .where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids]) .pluck(:id, :zip_code, :ip_address) .filter_map do |purchase_attributes| zip_code = purchase_attributes.second ip_address = purchase_attributes.last if zip_code.present? if subdivision.code == UsZipCodes.identify_state_code(zip_code) purchase_attributes.first end elsif subdivision.code == GeoIp.lookup(ip_address)&.region_name purchase_attributes.first end end begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) purchase_ids.each do |id| purchase = Purchase.find(id) zip_code = purchase.zip_code if purchase.zip_code.present? && subdivision.code == UsZipCodes.identify_state_code(purchase.zip_code) unless zip_code geo_ip = GeoIp.lookup(purchase.ip_address) zip_code = geo_ip&.postal_code if subdivision.code == geo_ip&.region_name end # Discard the sale if we can't determine an in-subdivision zip code. # TaxJar needs zip code for destination calculations. next unless zip_code price_cents = purchase.price_cents_net_of_refunds gumroad_tax_cents = purchase.gumroad_tax_cents_net_of_refunds total_transaction_cents = purchase.total_cents_net_of_refunds if purchase.purchase_taxjar_info.present? && (!gumroad_tax_cents.zero? || (gumroad_tax_cents.zero? && purchase.price_cents.zero?)) taxjar_info = purchase.purchase_taxjar_info combined_tax_rate = taxjar_info.combined_tax_rate state_tax_rate = taxjar_info.state_tax_rate county_tax_rate = taxjar_info.county_tax_rate city_tax_rate = taxjar_info.city_tax_rate tax_amount_cents = gumroad_tax_cents jurisdiction_state = taxjar_info.jurisdiction_state jurisdiction_county = taxjar_info.jurisdiction_county jurisdiction_city = taxjar_info.jurisdiction_city amount_not_collected_by_gumroad = 0 else taxjar_response_json = fetch_taxjar_info(purchase:, subdivision:, zip_code:, price_cents:) next if taxjar_response_json.nil? combined_tax_rate = taxjar_response_json["rate"] state_tax_rate = taxjar_response_json["breakdown"]["state_tax_rate"] county_tax_rate = taxjar_response_json["breakdown"]["county_tax_rate"] city_tax_rate = taxjar_response_json["breakdown"]["city_tax_rate"] tax_amount_cents = (taxjar_response_json["amount_to_collect"] * 100.0).round jurisdiction_state = taxjar_response_json["jurisdictions"]["state"] jurisdiction_county = taxjar_response_json["jurisdictions"]["county"] jurisdiction_city = taxjar_response_json["jurisdictions"]["city"] amount_not_collected_by_gumroad = tax_amount_cents - gumroad_tax_cents end temp_file.write([ purchase.external_id, purchase.created_at.strftime("%m/%d/%Y"), subdivision.name, Money.new(total_transaction_cents).format(no_cents_if_whole: false, symbol: false), Money.new(price_cents).format(no_cents_if_whole: false, symbol: false), Money.new(gumroad_tax_cents).format(no_cents_if_whole: false, symbol: false), combined_tax_rate, Money.new(tax_amount_cents).format(no_cents_if_whole: false, symbol: false), jurisdiction_state, jurisdiction_county, jurisdiction_city, state_tax_rate, county_tax_rate, city_tax_rate, Money.new(amount_not_collected_by_gumroad).format(no_cents_if_whole: false, symbol: false), purchase.link.native_type, Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type], ].to_csv) price_dollars = price_cents / 100.0 unit_price_dollars = price_dollars / purchase.quantity shipping_dollars = purchase.shipping_cents / 100.0 amount_dollars = price_dollars + shipping_dollars sales_tax_dollars = gumroad_tax_cents / 100.0 destination = { country: Compliance::Countries::USA.alpha2, state: subdivision.code, zip: zip_code } begin taxjar_api.create_order_transaction(transaction_id: purchase.external_id, transaction_date: purchase.created_at.iso8601, destination:, quantity: purchase.quantity, product_tax_code: Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type], amount_dollars:, shipping_dollars:, sales_tax_dollars:, unit_price_dollars:) rescue Taxjar::Error::UnprocessableEntity => e Rails.logger.info("CreateUSStateSalesReportsJob: Purchase with external ID #{purchase.external_id} was already created as a TaxJar transaction. #{e.class}: #{e.message}") rescue Taxjar::Error::BadRequest => e Bugsnag.notify(e) Rails.logger.info("CreateUSStateSalesReportsJob: Failed to create TaxJar transaction for purchase with external ID #{purchase.external_id}. #{e.class}: #{e.message}") end temp_file.flush end temp_file.rewind s3_filename = "#{subdivision.name.downcase.tr(" ", "-")}-sales-tax-report-#{year}-#{month}-#{SecureRandom.hex(4)}.csv" s3_report_key = "sales-tax/#{subdivision.name.downcase.tr(" ", "-")}/#{s3_filename}" s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s SlackMessageWorker.perform_async("payments", "US Sales Tax Reporting", "#{subdivision.name} reports for #{year}-#{month} are ready:\nGumroad format: #{s3_signed_url}", "green") ensure temp_file.close end end private def fetch_taxjar_info(purchase:, subdivision:, zip_code:, price_cents:) origin = { country: GumroadAddress::COUNTRY.alpha2, state: GumroadAddress::STATE, zip: GumroadAddress::ZIP } destination = { country: Compliance::Countries::USA.alpha2, state: subdivision.code, zip: zip_code } nexus_address = { country: Compliance::Countries::USA.alpha2, state: subdivision.code } product_tax_code = Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type] quantity = purchase.quantity unit_price_dollars = price_cents / 100.0 / quantity shipping_dollars = purchase.shipping_cents / 100.0 begin taxjar_api.calculate_tax_for_order(origin:, destination:, nexus_address:, quantity:, product_tax_code:, unit_price_dollars:, shipping_dollars:) rescue Taxjar::Error::NotFound, Taxjar::Error::BadRequest # NoOp end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/force_finish_long_running_community_chat_recap_runs_job.rb
app/sidekiq/force_finish_long_running_community_chat_recap_runs_job.rb
# frozen_string_literal: true class ForceFinishLongRunningCommunityChatRecapRunsJob include Sidekiq::Job MAX_RUNNING_TIME_IN_HOURS = 6 def perform CommunityChatRecapRun.running.where("created_at < ?", MAX_RUNNING_TIME_IN_HOURS.hours.ago).find_each do |recap_run| recap_run.community_chat_recaps.status_pending.find_each do |recap| recap.update!(status: "failed", error_message: "Recap run cancelled because it took longer than #{MAX_RUNNING_TIME_IN_HOURS} hours to complete") end recap_run.update!(finished_at: DateTime.current) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/cancel_subscriptions_for_product_worker.rb
app/sidekiq/cancel_subscriptions_for_product_worker.rb
# frozen_string_literal: true class CancelSubscriptionsForProductWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_id) product = Link.find(product_id) return unless product.deleted? # user undid product deletion product.subscriptions.active.each(&:cancel_effective_immediately!) ContactingCreatorMailer.subscription_product_deleted(product_id).deliver_later(queue: "critical") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/post_to_ping_endpoints_worker.rb
app/sidekiq/post_to_ping_endpoints_worker.rb
# frozen_string_literal: true class PostToPingEndpointsWorker include Sidekiq::Job sidekiq_options retry: 20, queue: :critical def perform(purchase_id, url_parameters, resource_name = ResourceSubscription::SALE_RESOURCE_NAME, subscription_id = nil, additional_params = {}) ActiveRecord::Base.connection.stick_to_primary! if subscription_id.present? subscription = Subscription.find(subscription_id) return if resource_name == ResourceSubscription::SUBSCRIPTION_ENDED_RESOURCE_NAME && subscription.deactivated_at.blank? return if resource_name == ResourceSubscription::SUBSCRIPTION_RESTARTED_RESOURCE_NAME && subscription.termination_date.present? user = subscription.link.user ping_params = subscription.payload_for_ping_notification(resource_name:, additional_params:) else purchase = Purchase.find(purchase_id) user = purchase.seller ping_params = purchase.payload_for_ping_notification(url_parameters:, resource_name:) end post_urls = user.urls_for_ping_notification(resource_name) return if post_urls.empty? post_urls.each do |post_url, content_type| next unless ResourceSubscription.valid_post_url?(post_url) PostToIndividualPingEndpointWorker.perform_async(post_url, ping_params.deep_stringify_keys, content_type, user.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/order_review_reminder_job.rb
app/sidekiq/order_review_reminder_job.rb
# frozen_string_literal: true class OrderReviewReminderJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(order_id) order = Order.find(order_id) eligible_purchases = order.purchases.select(&:eligible_for_review_reminder?) return if eligible_purchases.empty? SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer", "order_review_reminder", order_id) do if eligible_purchases.count > 1 CustomerLowPriorityMailer.order_review_reminder(order_id) .deliver_later(queue: :low) else CustomerLowPriorityMailer.purchase_review_reminder(eligible_purchases.first.id) .deliver_later(queue: :low) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_wishlist_updated_emails_job.rb
app/sidekiq/send_wishlist_updated_emails_job.rb
# frozen_string_literal: true class SendWishlistUpdatedEmailsJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low, lock: :until_executed def perform(wishlist_id, wishlist_product_ids) wishlist = Wishlist.find(wishlist_id) wishlist_products = wishlist.wishlist_products.alive.where(id: wishlist_product_ids) return if wishlist_products.empty? last_product_added_at = wishlist_products.maximum(:created_at) return if wishlist.wishlist_products_for_email.where("created_at > ?", last_product_added_at).exists? wishlist.wishlist_followers.find_each do |wishlist_follower| SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer", "wishlist_updated", wishlist_follower.id, wishlist_product_ids) do new_products = wishlist_products.select { _1.created_at > wishlist_follower.created_at } if new_products.any? CustomerLowPriorityMailer.wishlist_updated(wishlist_follower.id, new_products.size).deliver_later(queue: "low") end end end wishlist.update!(followers_last_contacted_at: last_product_added_at) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/transcode_video_for_streaming_worker.rb
app/sidekiq/transcode_video_for_streaming_worker.rb
# frozen_string_literal: true class TranscodeVideoForStreamingWorker include Sidekiq::Job include Rails.application.routes.url_helpers sidekiq_options retry: 13, queue: :default # Enforced by AWS Elastic Transcoder MAX_OUTPUT_KEY_PREFIX_BYTESIZE = 255 MEDIACONVERT = "mediaconvert" GRMC = "grmc" GRMC_ENDPOINT = "https://production-mediaconverter.gumroad.net/convert" ETS = "ets" ETS_PLAYLIST_FILENAME = "index.m3u8" MEDIACONVERT_OUTPUT_FILENAME = "index" def perform(id, klass_name = ProductFile.name, transcoder = GRMC, allowed_when_processing = false) ActiveRecord::Base.connection.stick_to_primary! Rails.logger.info "TranscodeVideoForStreamingWorker: performing for id=#{id}, klass_name=#{klass_name}, transcoder=#{transcoder}" if klass_name == Link.name Rails.logger.warn "TranscodeVideoForStreamingWorker called for Link ID #{id}. We don't transcode Links anymore." return end streamable = klass_name.constantize.find(id) return if streamable.deleted? return unless streamable.attempt_to_transcode?(allowed_when_processing:) streamable.transcoded_videos.alive.processing.find_each(&:mark_error) if allowed_when_processing if streamable.transcodable? create_hls_transcode_job(streamable, streamable.s3_key, streamable.height, transcoder) else Rails.logger.warn "ProductFile with ID #{id} is not transcodable" streamable.transcoding_failed end end def create_hls_transcode_job(streamable, original_video_key, input_video_height, transcoder) if mediaconvert_transcodable?(transcoder) create_hls_mediaconvert_transcode_job(streamable, original_video_key, input_video_height, transcoder) else create_hls_ets_transcode_job(streamable, original_video_key, input_video_height) end end def create_hls_ets_transcode_job(streamable, original_video_key, input_video_height) input = { key: original_video_key, frame_rate: "auto", resolution: "auto", aspect_ratio: "auto", interlaced: "auto", container: "auto" } # Every video gets transcoded to 480p regardless of its height. HD Videos get transcoded to at most one more preset depending on their resolution: preset_keys = ["hls_480p"] if input_video_height >= 1080 preset_keys << "hls_1080p" elsif input_video_height >= 720 preset_keys << "hls_720p" end outputs = [] preset_keys.each do |preset_key| hls_preset_id = HLS_PRESETS[preset_key] outputs << { key: "#{preset_key}_", thumbnail_pattern: "", rotate: "auto", preset_id: hls_preset_id, segment_duration: "10" } end playlists = [ { name: "index", format: "HLSv3", output_keys: outputs.map { |output| output[:key] } } ] extension = File.extname(original_video_key) relative_hls_path = "/hls/" # Fails to transcode if the 'output_key_prefix' length exceeds 255. video_key_without_extension = original_video_key.sub(/#{extension}\z/, "") .truncate_bytes(MAX_OUTPUT_KEY_PREFIX_BYTESIZE - relative_hls_path.length, omission: nil) output_key_prefix = "#{video_key_without_extension}#{relative_hls_path}" response = Aws::ElasticTranscoder::Client.new.create_job(pipeline_id: HLS_PIPELINE_ID, input:, outputs:, output_key_prefix:, playlists:) job = response.data[:job] job_id = job[:id] TranscodedVideo.create!( streamable:, original_video_key:, transcoded_video_key: "#{output_key_prefix}#{ETS_PLAYLIST_FILENAME}", job_id:, is_hls: true ) end def create_hls_mediaconvert_transcode_job(streamable, original_video_key, input_video_height, transcoder) # Every video gets transcoded to 480p regardless of its height. HD Videos get transcoded to at most one more preset depending on their resolution: presets = ["hls_480p"] if input_video_height >= 1080 presets << "hls_1080p" elsif input_video_height >= 720 presets << "hls_720p" end outputs = [] presets.each do |preset| outputs << { preset:, name_modifier: preset.delete_prefix("hls") } end output_key_prefix = build_output_key_prefix(original_video_key) transcoded_video = TranscodedVideo.create!( streamable:, original_video_key:, transcoded_video_key: output_key_prefix, is_hls: true ) completed_transcode = TranscodedVideo.alive.completed.where(original_video_key:).last if completed_transcode.present? # If the video was already successfully transcoded, there is no need to try to actually transcode it again. transcoded_video.update!( transcoded_video_key: completed_transcode.transcoded_video_key, state: "completed" ) return end if TranscodedVideo.alive.processing.where(original_video_key:).where.not(id: transcoded_video.id).exists? # If the video currently being transcoded by another TranscodedVideo record, there is no need to do anything: # when its transcoding is done, all TranscodedVideo records referring to the same S3 key (including this `transcoded_video`) # will be marked as completed / error (see TranscodeEventHandler and HandleGrmcCallbackJob). return end if transcoder == GRMC begin uri = URI.parse(GRMC_ENDPOINT) request = Net::HTTP::Post.new(uri) request.basic_auth(GlobalConfig.get("GRMC_API_KEY"), "") request.content_type = "application/json" request.body = { # TODO(kyle): Verify that it's safe to use global ID here. id: streamable.id.to_s, s3_video_uri: "s3://#{S3_BUCKET}/#{original_video_key}", s3_hls_dir_uri: "s3://#{S3_BUCKET}/#{output_key_prefix}", presets:, callback_url: api_internal_grmc_webhook_url(host: API_DOMAIN) }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end if response.code == "200" transcoded_video.update!( job_id: JSON.parse(response.body)["job_id"], via_grmc: true ) # In case GRMC silently fails to convert video (without calling the callback_url), we want to automatically retry with AWS MediaConvert after a large enough delay TranscodeVideoForStreamingWorker.perform_in(24.hours, streamable.id, streamable.class.name, MEDIACONVERT, true) return elsif response.code == "429" Rails.logger.warn("GRMC is busy (#{streamable.class.name} ID #{streamable.id})") else Rails.logger.warn("Failed request to GRMC (#{streamable.class.name} ID #{streamable.id}): #{response.code} => #{response.body}") end rescue => e Rails.logger.warn("Failed attempt to request GRMC: #{e.class} => #{e.message}") end end client = Aws::MediaConvert::Client.new(endpoint: MEDIACONVERT_ENDPOINT) response = client.create_job(build_mediaconvert_job(original_video_key, output_key_prefix, outputs)) job = response.job transcoded_video.update!(job_id: job.id) end private def mediaconvert_transcodable?(transcoder) transcoder.in?([MEDIACONVERT, GRMC]) end def build_output_key_prefix(original_video_key) extension = File.extname(original_video_key) relative_hls_path = "/hls/" video_key_without_extension = original_video_key.delete_suffix(extension) "#{video_key_without_extension}#{relative_hls_path}" end def build_mediaconvert_job(original_video_key, output_key_prefix, outputs) { queue: MEDIACONVERT_QUEUE, role: MEDIACONVERT_ROLE, settings: { output_groups: [ { name: "Apple HLS", output_group_settings: { type: "HLS_GROUP_SETTINGS", hls_group_settings: { segment_length: 10, min_segment_length: 0, destination: "s3://#{S3_BUCKET}/#{output_key_prefix}#{MEDIACONVERT_OUTPUT_FILENAME}", destination_settings: { s3_settings: { access_control: { canned_acl: "PUBLIC_READ" } } } } }, outputs: } ], inputs: [ { audio_selectors: { "Audio Selector 1": { default_selection: "DEFAULT" } }, video_selector: { rotate: "AUTO" }, file_input: "s3://#{S3_BUCKET}/#{original_video_key}" } ] }, acceleration_settings: { mode: "DISABLED" } } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/perform_payouts_up_to_delay_days_ago_worker.rb
app/sidekiq/perform_payouts_up_to_delay_days_ago_worker.rb
# frozen_string_literal: true class PerformPayoutsUpToDelayDaysAgoWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :critical, lock: :until_executed def perform(payout_processor_type, bank_account_types = nil) payout_period_end_date = User::PayoutSchedule.next_scheduled_payout_end_date Rails.logger.info("AUTOMATED PAYOUTS: #{payout_period_end_date}, #{payout_processor_type}, #{bank_account_types} (Started)") if bank_account_types Payouts.create_payments_for_balances_up_to_date_for_bank_account_types(payout_period_end_date, payout_processor_type, bank_account_types) else Payouts.create_payments_for_balances_up_to_date(payout_period_end_date, payout_processor_type) end Rails.logger.info("AUTOMATED PAYOUTS: #{payout_period_end_date}, #{payout_processor_type} #{bank_account_types} (Finished)") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/large_sellers_update_user_balance_stats_cache_worker.rb
app/sidekiq/large_sellers_update_user_balance_stats_cache_worker.rb
# frozen_string_literal: true class LargeSellersUpdateUserBalanceStatsCacheWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low def perform user_ids = UserBalanceStatsService.cacheable_users.pluck(:id).map { |el| [el] } Sidekiq::Client.push_bulk( "class" => UpdateUserBalanceStatsCacheWorker, "args" => user_ids, ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/fail_abandoned_purchase_worker.rb
app/sidekiq/fail_abandoned_purchase_worker.rb
# frozen_string_literal: true class FailAbandonedPurchaseWorker include Sidekiq::Job, StripeErrorHandler sidekiq_options retry: 5, queue: :default attr_reader :purchase def perform(purchase_id) @purchase = Purchase.find(purchase_id) return unless purchase.in_progress? # Guard against the job executing too early if purchase.created_at + ChargeProcessor::TIME_TO_COMPLETE_SCA > Time.current FailAbandonedPurchaseWorker.perform_at(purchase.created_at + ChargeProcessor::TIME_TO_COMPLETE_SCA, purchase_id) return end with_stripe_error_handler do merchant_account = purchase.merchant_account return if merchant_account&.is_a_stripe_connect_account? && merchant_account.charge_processor_merchant_id.blank? if purchase.processor_payment_intent_id.present? payment_intent = if merchant_account&.is_a_stripe_connect_account? Stripe::PaymentIntent.retrieve(purchase.processor_payment_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else Stripe::PaymentIntent.retrieve(purchase.processor_payment_intent_id) end cancel_charge_intent unless payment_intent.status == StripeIntentStatus::PROCESSING elsif purchase.processor_setup_intent_id.present? setup_intent = if merchant_account&.is_a_stripe_connect_account? Stripe::SetupIntent.retrieve(purchase.processor_setup_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else Stripe::SetupIntent.retrieve(purchase.processor_setup_intent_id) end cancel_setup_intent unless setup_intent.status == StripeIntentStatus::PROCESSING else raise "Expected purchase #{purchase.id} to have either a processor_payment_intent_id or processor_setup_intent_id present" end end end private def cancel_charge_intent purchase.cancel_charge_intent! rescue ChargeProcessorError charge_intent = ChargeProcessor.get_charge_intent(purchase.merchant_account, purchase.processor_payment_intent_id) # Ignore the error if: # - charge intent succeeded (user completed SCA in the meanwhile) # - charge intent has been cancelled (by a parallel purchase) # In both these cases the purchase will transition to a successful or failed state. # # Raise all other (unexpected) errors. raise unless charge_intent&.succeeded? || charge_intent&.canceled? end def cancel_setup_intent purchase.cancel_setup_intent! rescue ChargeProcessorError setup_intent = ChargeProcessor.get_setup_intent(purchase.merchant_account, purchase.processor_setup_intent_id) # Ignore the error if: # - setup intent succeeded (user completed SCA in the meanwhile) # - setup intent has been cancelled (by a parallel purchase) # In both these cases the purchase will transition to a successful or failed state. # # Raise all other (unexpected) errors. raise unless setup_intent&.succeeded? || setup_intent&.canceled? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/fight_dispute_job.rb
app/sidekiq/fight_dispute_job.rb
# frozen_string_literal: true class FightDisputeJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default, lock: :until_executed def perform(dispute_id) dispute = Dispute.find(dispute_id) dispute_evidence = dispute.dispute_evidence return if dispute_evidence.resolved? return if dispute_evidence.not_seller_submitted? && dispute_evidence.hours_left_to_submit_evidence.positive? dispute.disputable.fight_chargeback dispute_evidence.update_as_resolved!(resolution: DisputeEvidence::RESOLUTION_SUBMITTED) rescue ChargeProcessorInvalidRequestError => e if rejected?(e.message) dispute_evidence.update_as_resolved!( resolution: DisputeEvidence::RESOLUTION_REJECTED, error_message: e.message ) else raise e end end private def rejected?(message) message.include?("This dispute is already closed") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/export_payout_data.rb
app/sidekiq/export_payout_data.rb
# frozen_string_literal: true class ExportPayoutData include Sidekiq::Job sidekiq_options retry: 5, queue: :low def initialize @tempfiles_to_cleanup = [] end def perform(payment_ids, recipient_user_id) payment_ids = Array.wrap(payment_ids) payouts = generate_payouts(payment_ids) return if payouts.empty? return unless all_from_same_seller?(payouts) filename, extension, tempfile = if payouts.size == 1 payout = payouts.first ["#{payout[:filename]}.#{payout[:extension]}", payout[:extension], payout[:tempfile]] else ["Payouts.zip", "zip", create_zip_archive(payouts)] end ContactingCreatorMailer.payout_data(filename, extension, tempfile, recipient_user_id).deliver_now ensure cleanup_tempfiles end private def create_tempfile(*args, **kwargs) Tempfile.new(*args, **kwargs).tap do |tempfile| @tempfiles_to_cleanup << tempfile end end def cleanup_tempfiles @tempfiles_to_cleanup.each do |tempfile| tempfile.close tempfile.unlink end end def create_zip_archive(payouts) zip_file = create_tempfile(["payouts", ".zip"]) Zip::File.open(zip_file.path, Zip::File::CREATE) do |zip| filename_registry = FilenameRegistry.new payouts.each do |payout| unique_filename = filename_registry.generate_unique_name(payout[:filename], payout[:extension]) zip.add(unique_filename, payout[:tempfile].path) end end # Reopen the file as it was written to in a separate stream. zip_file.open zip_file.rewind zip_file end def generate_payouts(payment_ids) payouts = [] Payment.where(id: payment_ids).find_each do |payment| tempfile = create_tempfile(["payout", ".csv"]) content = Exports::Payouts::Csv.new(payment_id: payment.id).perform tempfile.write(content) tempfile.rewind payouts << { tempfile:, filename: "Payout of #{payment.created_at.to_date}", extension: "csv", seller_id: payment.user_id } end payouts end def all_from_same_seller?(payouts) payouts.map { |payout| payout[:seller_id] }.uniq.size == 1 end class FilenameRegistry def initialize @existing_filenames = Set.new end def generate_unique_name(filename, extension) find_unique_filename(filename, extension).tap do |unique_filename| @existing_filenames << unique_filename end end private def find_unique_filename(filename, extension, index_suffix = 0) candidate = "#{filename}#{index_suffix > 0 ? " (#{index_suffix})" : ""}.#{extension}" if @existing_filenames.include?(candidate) find_unique_filename(filename, extension, index_suffix + 1) else candidate end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/pdf_unstampable_notifier_worker.rb
app/sidekiq/pdf_unstampable_notifier_worker.rb
# frozen_string_literal: true # Before removing this file, make sure there are no more enqueued jobs in production using the class name PdfUnstampableNotifierWorker = PdfUnstampableNotifierJob
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/retry_failed_paypal_payouts_worker.rb
app/sidekiq/retry_failed_paypal_payouts_worker.rb
# frozen_string_literal: true class RetryFailedPaypalPayoutsWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :critical, lock: :until_executed def perform payout_period_end_date = User::PayoutSchedule.manual_payout_end_date failed_payments_users = User.joins(:payments) .where({ payments: { state: "failed", failure_reason: nil, processor: PayoutProcessorType::PAYPAL, payout_period_end_date: } }) .uniq return if failed_payments_users.empty? Rails.logger.info("RETRY FAILED PAYOUTS PAYPAL: #{payout_period_end_date} (Started)") Payouts.create_payments_for_balances_up_to_date_for_users(payout_period_end_date, PayoutProcessorType::PAYPAL, failed_payments_users, perform_async: true, retrying: true) Rails.logger.info("RETRY FAILED PAYOUTS PAYPAL: #{payout_period_end_date} (Finished)") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_integrations_on_tier_change_worker.rb
app/sidekiq/update_integrations_on_tier_change_worker.rb
# frozen_string_literal: true class UpdateIntegrationsOnTierChangeWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) [Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service| integration_service.new.update_on_tier_change(subscription) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/reset_admin_action_call_counts_job.rb
app/sidekiq/reset_admin_action_call_counts_job.rb
# frozen_string_literal: true class ResetAdminActionCallCountsJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform Rails.application.eager_load! AdminActionCallInfo.transaction do AdminActionCallInfo.destroy_all Admin::BaseController.descendants.each do |controller_class| controller_class.public_instance_methods(false).each do |action_name| AdminActionCallInfo.create_or_find_by!(controller_name: controller_class.name, action_name:) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/trigger_community_chat_recap_run_job.rb
app/sidekiq/trigger_community_chat_recap_run_job.rb
# frozen_string_literal: true class TriggerCommunityChatRecapRunJob include Sidekiq::Job sidekiq_options queue: :low, retry: 3, lock: :until_executed def perform(recap_frequency, from_date = nil) raise ArgumentError, "Recap frequency must be daily or weekly" unless recap_frequency.in?(CommunityChatRecapRun.recap_frequencies.values) from_date = (from_date.present? ? Date.parse(from_date) : recap_frequency == "daily" ? Date.yesterday : Date.yesterday - 6.days).beginning_of_day to_date = (recap_frequency == "daily" ? from_date : from_date + 6.days).end_of_day ActiveRecord::Base.transaction do recap_run = CommunityChatRecapRun.find_or_initialize_by(recap_frequency:, from_date:, to_date:) return if recap_run.persisted? community_ids = CommunityChatMessage.alive.where(created_at: from_date..to_date).pluck(:community_id).uniq recap_run.recaps_count = community_ids.size recap_run.finished_at = DateTime.current if community_ids.size == 0 recap_run.save! community_ids.each do |community_id| recap = recap_run.community_chat_recaps.create!(community_id:) GenerateCommunityChatRecapJob.perform_async(recap.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_financial_reports_for_previous_month_job.rb
app/sidekiq/generate_financial_reports_for_previous_month_job.rb
# frozen_string_literal: true class GenerateFinancialReportsForPreviousMonthJob include Sidekiq::Worker sidekiq_options retry: 1, queue: :default, lock: :until_executed def perform return unless Rails.env.production? prev_month_date = Date.current.prev_month CreateCanadaMonthlySalesReportJob.perform_async(prev_month_date.month, prev_month_date.year) GenerateFeesByCreatorLocationReportJob.perform_async(prev_month_date.month, prev_month_date.year) subdivision_codes = Compliance::Countries::TAXABLE_US_STATE_CODES CreateUsStatesSalesSummaryReportJob.perform_async(subdivision_codes, prev_month_date.month, prev_month_date.year) GenerateCanadaSalesReportJob.perform_async(prev_month_date.month, prev_month_date.year) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_in_mongo_worker.rb
app/sidekiq/update_in_mongo_worker.rb
# frozen_string_literal: true class UpdateInMongoWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :mongo def perform(collection, conditions, doc) Mongoer.safe_update(collection, conditions, doc) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_stripe_merchant_account_worker.rb
app/sidekiq/create_stripe_merchant_account_worker.rb
# frozen_string_literal: true class CreateStripeMerchantAccountWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_id) user = User.find(user_id) StripeMerchantAccountManager.create_account(user, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/process_early_fraud_warning_job.rb
app/sidekiq/process_early_fraud_warning_job.rb
# frozen_string_literal: true class ProcessEarlyFraudWarningJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default, lock: :until_executed def perform(early_fraud_warning_id) early_fraud_warning = EarlyFraudWarning.find(early_fraud_warning_id) return if early_fraud_warning.resolved? early_fraud_warning.update_from_stripe! early_fraud_warning.reload if early_fraud_warning.actionable? process_actionable_record!(early_fraud_warning) else process_not_actionable_record!(early_fraud_warning) end end private def process_not_actionable_record!(early_fraud_warning) dispute = early_fraud_warning.dispute refund = early_fraud_warning.refund # It should not happen as an EFW is actionable if it has a dispute or refund associated raise "Cannot determine resolution" if dispute.blank? && refund.blank? resolution = \ if dispute.present? && refund.present? if refund.created_at <= dispute.created_at EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_REFUNDED else EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_DISPUTED end elsif dispute.present? EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_DISPUTED else EarlyFraudWarning::RESOLUTION_NOT_ACTIONABLE_REFUNDED end early_fraud_warning.update_as_resolved!(resolution:) end def process_actionable_record!(early_fraud_warning) early_fraud_warning.with_lock do if early_fraud_warning.chargeable_refundable_for_fraud? process_refundable_for_fraud!(early_fraud_warning) elsif early_fraud_warning.purchase_for_subscription_contactable? process_subscription_contactable!(early_fraud_warning) else process_resolved_ignored!(early_fraud_warning) end end end def process_refundable_for_fraud!(early_fraud_warning) early_fraud_warning.chargeable.refund_for_fraud_and_block_buyer!(GUMROAD_ADMIN_ID) early_fraud_warning.update_as_resolved!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_REFUNDED_FOR_FRAUD ) end def process_subscription_contactable!(early_fraud_warning) already_contacted_ids = early_fraud_warning.associated_early_fraud_warning_ids_for_subscription_contacted if already_contacted_ids.present? early_fraud_warning.update_as_resolved!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED, resolution_message: "Already contacted for EFW id #{already_contacted_ids.join(", ")}" ) else CustomerLowPriorityMailer.subscription_early_fraud_warning_notification( early_fraud_warning.purchase_for_subscription.id ).deliver_later early_fraud_warning.update_as_resolved!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_CUSTOMER_CONTACTED ) end end def process_resolved_ignored!(early_fraud_warning) early_fraud_warning.update_as_resolved!( resolution: EarlyFraudWarning::RESOLUTION_RESOLVED_IGNORED ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_post_blast_emails_job.rb
app/sidekiq/send_post_blast_emails_job.rb
# frozen_string_literal: true class SendPostBlastEmailsJob include Sidekiq::Job include ActionView::Helpers::SanitizeHelper sidekiq_options retry: 10, queue: :default, lock: :until_executed def perform(blast_id) @blast = PostEmailBlast.find(blast_id) @post = @blast.post Rails.logger.info("[#{self.class.name}] blast_id=#{@blast.id} post_id=#{@post.id}") return unless @post.alive? && @post.published? && @post.send_emails? && @blast.completed_at.nil? @blast.update!(started_at: Time.current) if @blast.started_at.nil? @filters = @post.audience_members_filter_params # The filter query can be expensive to run, it's better to run it on the replica DB. Makara::Context.release_all @members = AudienceMember.filter(seller_id: @post.seller_id, params: @filters, with_ids: true).select(:id, :email, :purchase_id, :follower_id, :affiliate_id).to_a # We will check each batch of emails to see if they were already messaged, # but we can already remove all of the ones we know have already been emailed, ahead of time (faster). # This check is only useful if the post has been published twice, or if this job is being retried. remove_already_emailed_members return mark_blast_as_completed if @members.empty? cache = {} @members.each_slice(recipients_slice_size) do |members_slice| members = store_recipients_as_sent(members_slice) recipients = prepare_recipients(members) begin PostEmailApi.process(post: @post, recipients:, cache:, blast: @blast) rescue => e # Delete the sent_post_emails records if there's an error with PostEmailApi.process # We cannot use `transaction` here because it exceeds the lock timeout. emails = members.map(&:email) SentPostEmail.where(post: @post, email: emails).delete_all raise e end end mark_blast_as_completed end private def prepare_recipients(members) members_with_specifics = members.index_with { { email: _1.email } } enrich_with_gathered_records(members_with_specifics) enrich_with_purchases_specifics(members_with_specifics) enrich_with_url_redirects(members_with_specifics) members_with_specifics.values end def remove_already_emailed_members already_sent_emails = Set.new(@post.sent_post_emails.pluck(:email)) return if already_sent_emails.empty? @members.delete_if { _1.email.in?(already_sent_emails) } end def enrich_with_gathered_records(members_with_specifics) members_with_specifics.each do |member, specifics| if @post.seller_or_product_or_variant_type? specifics[:purchase] = Purchase.new(id: member.purchase_id) if member.purchase_id elsif @post.follower_type? specifics[:follower] = Follower.new(id: member.follower_id) if member.follower_id elsif @post.affiliate_type? specifics[:affiliate] = Affiliate.new(id: member.affiliate_id) if member.affiliate_id elsif @post.audience_type? specifics[:follower] = Follower.new(id: member.follower_id) if member.follower_id specifics[:affiliate] = Affiliate.new(id: member.affiliate_id) if member.follower_id.nil? && member.affiliate_id specifics[:purchase] = Purchase.new(id: member.purchase_id) if member.follower_id.nil? && member.affiliate_id.nil? && member.purchase_id end specifics.compact_blank! end end def enrich_with_purchases_specifics(members_with_specifics) purchase_ids = members_with_specifics.map { _2[:purchase]&.id }.compact return if purchase_ids.empty? purchases = Purchase.joins(:link).where(id: purchase_ids).select(:id, :link_id, :json_data, :subscription_id, "links.name as product_name").index_by(&:id) members_with_specifics.each do |_member, specifics| purchase_id = specifics[:purchase]&.id next if purchase_id.nil? purchase = purchases[purchase_id] if purchase.link_id.present? specifics[:product_id] = purchase.link_id specifics[:product_name] = strip_tags(purchase.product_name) end specifics[:subscription] = Subscription.new(id: purchase.subscription_id) if purchase.subscription_id.present? end end def enrich_with_url_redirects(members_with_specifics) return if !post_has_files? && !@post.product_or_variant_type? # Fetch url_redirect for this post * non-purchases. # Because all followers and affiliates will end up seeing the same page, we only need to create one record. if post_has_files? members_with_specifics.each do |_member, specifics| next if specifics.key?(:purchase) @url_redirect_for_non_purchasers ||= UrlRedirect.find_or_create_by!(installment_id: @post.id, purchase_id: nil, subscription_id: nil, link_id: nil) specifics[:url_redirect] = @url_redirect_for_non_purchasers end end # Create url_redirects for this post * purchases. url_redirects_to_create = {} members_with_specifics.each do |member, specifics| next if specifics.key?(:url_redirect) url_redirects_to_create[UrlRedirect.generate_new_token] = { attributes: { installment_id: @post.id, purchase_id: specifics[:purchase]&.id, subscription_id: specifics[:subscription]&.id, link_id: specifics[:product_id], }, member: } end if url_redirects_to_create.present? UrlRedirect.insert_all!(url_redirects_to_create.map { _2[:attributes].merge(token: _1) }) url_redirects = UrlRedirect.where(token: url_redirects_to_create.keys).select(:id, :token).to_a url_redirects.each do |url_redirect| members_with_specifics[url_redirects_to_create[url_redirect.token][:member]][:url_redirect] = url_redirect end end end def mark_blast_as_completed @blast.update!(completed_at: Time.current) end # Stores email addresses in SentPostEmail, just before sending the emails. # In the very unlikely situation an email is already present there, its member won't be returned. # "Unlikely situation" because we've already filtered the sent emails beforehand with `remove_already_emailed_members`, # this behavior only helps if an email is sent by something else in parallel, between the start and the end of this job. def store_recipients_as_sent(members) emails = Set.new(SentPostEmail.insert_all_emails(post: @post, emails: members.map(&:email))) return members if members.size == emails.size members.select { _1.email.in?(emails) } end def post_has_files? return @has_files if defined?(@has_files) @has_files = @post.has_files? end def product @post.link if @post.product_type? || @post.variant_type? end def recipients_slice_size @recipients_slice_size ||= begin $redis.get(RedisKey.blast_recipients_slice_size) || PostEmailApi.max_recipients end.to_i.clamp(1..PostEmailApi.max_recipients) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_payout_reversed_worker.rb
app/sidekiq/handle_payout_reversed_worker.rb
# frozen_string_literal: true class HandlePayoutReversedWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(payment_id, reversing_payout_id, stripe_connect_account_id) @reversing_payout_id = reversing_payout_id @stripe_connect_account_id = stripe_connect_account_id if reversing_payout_succeeded? StripePayoutProcessor.handle_stripe_event_payout_reversed(Payment.find(payment_id), reversing_payout_id) elsif reversing_payout_failed? # The reversing payout that was once reported as `paid`, has now transitioned to `failed`. # We waited for it to either complete its balance transaction, or to fail. It failed, so nothing for us to do. else raise "Timed out waiting for reversing payout to become finalized (to transition to `failed` state or its balance transaction "\ "to transition to `available` state). Payment ID: #{payment_id}. Reversing payout ID: #{reversing_payout_id}" end end private attr_reader :reversing_payout_id, :stripe_connect_account_id def reversing_payout_succeeded? balance_transaction_completed? && (reversing_payout["status"] == "paid") end def balance_transaction_completed? reversing_payout["balance_transaction"]["status"] == "available" end def reversing_payout_failed? reversing_payout["status"] == "failed" end def reversing_payout @_reversing_payout ||= Stripe::Payout.retrieve( { id: reversing_payout_id, expand: %w[balance_transaction] }, { stripe_account: stripe_connect_account_id } ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/refresh_sitemap_daily_worker.rb
app/sidekiq/refresh_sitemap_daily_worker.rb
# frozen_string_literal: true class RefreshSitemapDailyWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :low def perform(date = Date.current.to_s) SitemapService.new.generate(date) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_licenses_for_existing_customers_worker.rb
app/sidekiq/create_licenses_for_existing_customers_worker.rb
# frozen_string_literal: true class CreateLicensesForExistingCustomersWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_id) product = Link.find(product_id) product.sales.successful_gift_or_nongift.not_is_gift_sender_purchase.not_recurring_charge.find_each do |purchase| License.where(link: product, purchase:).first_or_create! end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_canada_monthly_sales_report_job.rb
app/sidekiq/create_canada_monthly_sales_report_job.rb
# frozen_string_literal: true class CreateCanadaMonthlySalesReportJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace def perform(month, year) raise ArgumentError, "Invalid month" unless month.in?(1..12) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) timeout_seconds = ($redis.get(RedisKey.create_canada_monthly_sales_report_job_max_execution_time_seconds) || 1.hour).to_i WithMaxExecutionTime.timeout_queries(seconds: timeout_seconds) do Purchase.successful .not_fully_refunded .not_chargedback_or_chargedback_reversed .where.not(stripe_transaction_id: nil) .where("purchases.created_at BETWEEN ? AND ?", Date.new(year, month).beginning_of_month.beginning_of_day, Date.new(year, month).end_of_month.end_of_day) .where("(country = 'Canada') OR (country IS NULL AND ip_country = 'Canada')") .where("ip_country = 'Canada' OR card_country = 'CA'") .where(state: Compliance::Countries.subdivisions_for_select(Compliance::Countries::CAN.alpha2).map(&:first)) .where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids]) .find_each do |purchase| taxjar_info = purchase.purchase_taxjar_info price_cents = purchase.price_cents_net_of_refunds fee_cents = purchase.fee_cents_net_of_refunds gumroad_tax_cents = purchase.gumroad_tax_cents_net_of_refunds total_cents = purchase.total_cents_net_of_refunds row = [ purchase.external_id, purchase.created_at.strftime("%m/%d/%Y"), ISO3166::Country["CA"].subdivisions[purchase.state]&.name, purchase.link.native_type, Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type], taxjar_info&.gst_tax_rate, taxjar_info&.pst_tax_rate, taxjar_info&.qst_tax_rate, taxjar_info&.combined_tax_rate, Money.new(gumroad_tax_cents).format(no_cents_if_whole: false, symbol: false), Money.new(gumroad_tax_cents).format(no_cents_if_whole: false, symbol: false), Money.new(price_cents).format(no_cents_if_whole: false, symbol: false), Money.new(fee_cents).format(no_cents_if_whole: false, symbol: false), Money.new(purchase.shipping_cents).format(no_cents_if_whole: false, symbol: false), Money.new(total_cents).format(no_cents_if_whole: false, symbol: false), purchase.receipt_url ] temp_file.write(row.to_csv) temp_file.flush end end temp_file.rewind s3_filename = "canada-sales-report-#{year}-#{month}-#{SecureRandom.hex(4)}.csv" s3_report_key = "sales-tax/ca-sales-monthly/#{s3_filename}" s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s SlackMessageWorker.perform_async("payments", "Canada Sales Reporting", "Canada #{year}-#{month} sales report is ready - #{s3_signed_url}", "green") ensure temp_file.close end end private def row_headers [ "Purchase External ID", "Purchase Date", "Member State of Consumption", "Gumroad Product Type", "TaxJar Product Tax Code", "GST Tax Rate", "PST Tax Rate", "QST Tax Rate", "Combined Tax Rate", "Calculated Tax Amount", "Tax Collected by Gumroad", "Price", "Gumroad Fee", "Shipping", "Total", "Receipt URL", ] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/compile_gumroad_daily_analytics_job.rb
app/sidekiq/compile_gumroad_daily_analytics_job.rb
# frozen_string_literal: true class CompileGumroadDailyAnalyticsJob include Sidekiq::Job sidekiq_options retry: 0, queue: :default REFRESH_PERIOD = 45.days private_constant :REFRESH_PERIOD def perform start_date = Date.today - REFRESH_PERIOD end_date = Date.today (start_date..end_date).each do |date| GumroadDailyAnalytic.import(date) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/email_outstanding_balances_csv_worker.rb
app/sidekiq/email_outstanding_balances_csv_worker.rb
# frozen_string_literal: true class EmailOutstandingBalancesCsvWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :raise def perform return unless Rails.env.production? AccountingMailer.email_outstanding_balances_csv.deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/unblock_object_worker.rb
app/sidekiq/unblock_object_worker.rb
# frozen_string_literal: true class UnblockObjectWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(object_value) BlockedObject.unblock!(object_value) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_workflow_post_emails_job.rb
app/sidekiq/send_workflow_post_emails_job.rb
# frozen_string_literal: true class SendWorkflowPostEmailsJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(post_id, earliest_valid_time = nil) @post = Installment.find(post_id) @workflow = @post.workflow return unless @workflow.alive? && @post.alive? && @post.published? @rule_version = @post.installment_rule.version @rule_delay = @post.installment_rule.delayed_delivery_time @filters = @post.audience_members_filter_params @filters[:created_after] = Time.zone.parse(earliest_valid_time) if earliest_valid_time Makara::Context.release_all @members = AudienceMember.filter(seller_id: @post.seller_id, params: @filters, with_ids: true). select(:id, :email, :details, :purchase_id, :follower_id, :affiliate_id).to_a @members.each do |member| if @post.seller_or_product_or_variant_type? enqueue_email_job(member:, type: :purchase, id: member.purchase_id) elsif @post.follower_type? enqueue_email_job(member:, type: :follower, id: member.follower_id) elsif @post.affiliate_type? enqueue_email_job(member:, type: :affiliate, id: member.affiliate_id) elsif @post.audience_type? if member.follower_id enqueue_email_job(member:, type: :follower, id: member.follower_id) elsif member.affiliate_id enqueue_email_job(member:, type: :affiliate, id: member.affiliate_id) else enqueue_email_job(member:, type: :purchase, id: member.purchase_id) end end end end private def enqueue_email_job(member:, type:, id:) if type == :purchase created_at = Time.zone.parse(member.details["purchases"].find { _1["id"] == id }["created_at"]) SendWorkflowInstallmentWorker.perform_at(created_at + @rule_delay, @post.id, @rule_version, id, nil, nil) elsif type == :follower created_at = Time.zone.parse(member.details.dig("follower", "created_at")) SendWorkflowInstallmentWorker.perform_at(created_at + @rule_delay, @post.id, @rule_version, nil, id, nil) elsif type == :affiliate created_at = Time.zone.parse(member.details["affiliates"].find { _1["id"] == id }["created_at"]) SendWorkflowInstallmentWorker.perform_at(created_at + @rule_delay, @post.id, @rule_version, nil, nil, id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/regenerate_creator_analytics_cache_worker.rb
app/sidekiq/regenerate_creator_analytics_cache_worker.rb
# frozen_string_literal: true class RegenerateCreatorAnalyticsCacheWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low, lock: :until_executed def perform(user_id, date_string) user = User.find(user_id) date = Date.parse(date_string) service = CreatorAnalytics::CachingProxy.new(user) WithMaxExecutionTime.timeout_queries(seconds: 20.minutes) do [:date, :state, :referral].each do |type| service.overwrite_cache(date, by: type) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/expire_transcoded_videos_job.rb
app/sidekiq/expire_transcoded_videos_job.rb
# frozen_string_literal: true class ExpireTranscodedVideosJob include Sidekiq::Job sidekiq_options queue: :low, retry: 5 BATCH_SIZE = 100 def perform recentness_limit = $redis.get(RedisKey.transcoded_videos_recentness_limit_in_months) recentness_limit ||= 12 * 100 # 100 years => do not expire by default recentness_limit = recentness_limit.to_i.months loop do ReplicaLagWatcher.watch records = TranscodedVideo.alive.where(last_accessed_at: .. recentness_limit.ago).limit(BATCH_SIZE).load break if records.empty? records.each(&:mark_deleted!) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/duplicate_product_worker.rb
app/sidekiq/duplicate_product_worker.rb
# frozen_string_literal: true class DuplicateProductWorker include Sidekiq::Job sidekiq_options queue: :critical def perform(product_id) ProductDuplicatorService.new(product_id).duplicate rescue => e logger.error("Error while duplicating product id '#{product_id}': #{e.inspect}") Bugsnag.notify(e) ensure product = Link.find(product_id) product.update!(is_duplicating: false) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_payout_status_worker.rb
app/sidekiq/update_payout_status_worker.rb
# frozen_string_literal: true class UpdatePayoutStatusWorker include Sidekiq::Job sidekiq_options retry: 25, queue: :default, lock: :until_executed def perform(payment_id) payment = Payment.find(payment_id) Rails.logger.info("UpdatePayoutStatusWorker invoked for payment #{payment_id}") # This job is supposed to update status only for payments in the processing state return unless payment.processing? if payment.was_created_in_split_mode? payment.split_payments_info.each_with_index do |split_payment_info, index| next if split_payment_info["state"] != "pending" # Don't operate on non-pending parts new_payment_state = PaypalPayoutProcessor.get_latest_payment_state_from_paypal(split_payment_info["amount_cents"], split_payment_info["txn_id"], payment.created_at.beginning_of_day - 1.day, split_payment_info["state"]) payment.split_payments_info[index]["state"] = new_payment_state Rails.logger.info("UpdatePayoutStatusWorker set status for payment #{payment_id} to #{new_payment_state}") end payment.save! if payment.split_payments_info.any? { |split_payment_info| split_payment_info["state"] == "pending" } raise "Some split payment parts are still in the 'pending' state" else PaypalPayoutProcessor.update_split_payment_state(payment) end else new_payment_state = PaypalPayoutProcessor.get_latest_payment_state_from_paypal(payment.amount_cents, payment.txn_id, payment.created_at.beginning_of_day - 1.day, payment.state) Rails.logger.info("UpdatePayoutStatusWorker set status for payment #{payment_id} to #{new_payment_state}") payment.mark!(new_payment_state) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_product_files_archive_worker.rb
app/sidekiq/update_product_files_archive_worker.rb
# frozen_string_literal: true class UpdateProductFilesArchiveWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low PRODUCT_FILES_ARCHIVE_FILE_SIZE_LIMIT = 500.megabytes UNTITLED_FILENAME = "Untitled" # On an EXT4 file system, the command "getconf PATH_MAX /" returns 255 which # is an indication that the pathname cannot exceed 255 bytes. # The actual Tempfile pathname can be much longer than the actual name of # the file. # # For example: # > "个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子".bytesize # => 240 # > "/tmp/个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子人个出租车学习杯子.csv20210323-608-1hgzlxi".bytesize # => 269 # # Therefore, to avoid running into "Errno::ENAMETOOLONG (File name too long)" # error, we can safely set the bytesize limit for the actual name of the file # much smaller. MAX_FILENAME_BYTESIZE = 150 def initialize @used_file_paths = [] end def perform(product_files_archive_id) return if Rails.env.test? product_files_archive = ProductFilesArchive.find(product_files_archive_id) # Check for nil immediately, product_files_archive has mysteriously been # nil which locks up workers by not failing properly if product_files_archive.nil? Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - Archive var was not set") return end if product_files_archive.deleted? Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - Archive is deleted") return end Rails.logger.info("Beginning UpdateProductFilesArchive Job for #{product_files_archive.id}") product_files_archive.mark_in_progress! # Check the estimated size of the archive. If it is larger than our limit, # mark the product_files_archive as failed and exit the job. estimated_size = calculate_estimated_size(product_files_archive) if estimated_size > PRODUCT_FILES_ARCHIVE_FILE_SIZE_LIMIT product_files_archive.mark_failed! Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - Archive is too large.") return end zip_archive_filename = File.join(Dir.tmpdir, "#{product_files_archive.external_id}.zip") product_files = product_files_archive.product_files.not_external_link rich_content_files_and_folders_mapping = product_files_archive.rich_content_provider&.map_rich_content_files_and_folders Zip::File.open(zip_archive_filename, Zip::File::CREATE) do |zip_file| product_files.each do |product_file| next if product_file.stream_only? if rich_content_files_and_folders_mapping.nil? file_path_parts = [product_file.folder&.name, product_file.name_displayable] else file_info = rich_content_files_and_folders_mapping[product_file.id] next if file_info.nil? directory_info = product_files_archive.folder_archive? ? [] : [file_info[:page_title], file_info[:folder_name]] file_path_parts = directory_info.concat([file_info[:file_name]]) end file_path = compose_file_path(file_path_parts, product_file.s3_extension) zip_file.get_output_stream(file_path) do |output_stream| temp_file = Tempfile.new begin product_file.s3_object.download_file(temp_file.path) rescue Aws::S3::Errors::NotFound # If the file does not exist on S3 for any reason, abandon this job without raising an error. product_files_archive.mark_failed! Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - missing file #{product_file.id}") return end temp_file.rewind output_stream.write(temp_file.read) end end end unless File.exist?(zip_archive_filename) product_files_archive.mark_failed! Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - Zip file was not written.") return end # NOTE: Probably better to not have to reopen this file, but couldn't get a # variable to hold the zip file, so had to do it this way. file = File.open(zip_archive_filename, "rb") archive_s3_object = product_files_archive.s3_object archive_s3_object.upload_file(file, content_type: "application/zip") product_files_archive.mark_ready! Rails.logger.info("UpdateProductFilesArchive job completed for id #{product_files_archive.id}.") rescue NoMemoryError, Aws::S3::Errors::NoSuchKey, Errno::ENOENT, Seahorse::Client::NetworkingError, Aws::S3::Errors::ServiceError => e file&.close delete_temp_zip_file_if_exists(zip_archive_filename) product_files_archive.mark_failed! Bugsnag.notify(e) Rails.logger.info("UpdateProductFilesArchive Job #{product_files_archive.id} failed - #{e.class.name}: #{e.message}") raise e ensure file&.close delete_temp_zip_file_if_exists(zip_archive_filename) end # Helper method to delete any zip files that might get left around def delete_temp_zip_file_if_exists(zip_archive_filename) if zip_archive_filename && File.exist?(zip_archive_filename) if File.delete(zip_archive_filename) Rails.logger.info("Temporary zip file deleted.") else Rails.logger.info("Zip file was not deleted.") end end end def calculate_estimated_size(product_files_archive) Rails.logger.info("Calculating estimated archive size.") estimated_size = 0 product_files_archive.product_files.each do |product_file| if product_file.size estimated_size += product_file.size else Rails.logger.info("Fetching product file size from S3.") estimated_size += product_file.s3_object.content_length if product_file.s3? end end estimated_size end private attr_reader :used_file_paths def compose_file_path(file_path_parts, extension) file_path_parts = file_path_parts.map { |name| sanitize_filename(name || "") }.compact_blank # Some file systems have a strict limit on the file path length of # approx 255 bytes (Reference: https://serverfault.com/a/9548/122209). # Since the file name can be a multibyte unicode string, we must # truncate the string by multibyte characters (graphemes). path_without_extension = truncate_path(file_path_parts) file_path = "#{path_without_extension}#{extension}" # Make sure each entry in the zip file has a unique path. If entry names are not unique the zip file will be corrupted. suffix = 1 while used_file_paths.include?(file_path.downcase) file_path = "#{path_without_extension}-#{suffix}#{extension}" suffix += 1 end used_file_paths << file_path.downcase # Some FSs will compare file/folder names in a case-insensitive way file_path end def sanitize_filename(filename) filename = ActiveStorage::Filename.new(filename).sanitized # Additional rules for Windows https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions filename = filename.gsub(/[<>:"\/\\|?*]/, "-").gsub(/[ .]*\z/, "") filename end def truncate_path(path_parts) truncate_part_by_percent = 0.75 while File.join(path_parts).bytesize > MAX_FILENAME_BYTESIZE longest_part = path_parts.max_by(&:bytesize) if longest_part == path_parts.last && path_parts.length > 1 && longest_part.bytesize <= UNTITLED_FILENAME.bytesize path_parts.shift else truncate_to_bytesize = path_parts.length == 1 ? MAX_FILENAME_BYTESIZE : longest_part.bytesize * truncate_part_by_percent path_parts[path_parts.index(longest_part)] = longest_part.truncate_bytes((truncate_to_bytesize).round, omission: nil) end path_parts.compact_blank! end File.join(path_parts) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_purchasing_power_parity_factors_worker.rb
app/sidekiq/update_purchasing_power_parity_factors_worker.rb
# frozen_string_literal: true class UpdatePurchasingPowerParityFactorsWorker include Sidekiq::Job include CurrencyHelper API_URL = "https://api.worldbank.org/v2/en/indicator/PA.NUS.PPP?downloadformat=csv" API_FILE_PREFIX = "API_PA" UPPER_THRESHOLD = 0.8 LOWER_THRESHOLD = 0.4 sidekiq_options retry: 5, queue: :low def perform csv_zip = URI.open(API_URL).read ppp_service = PurchasingPowerParityService.new Zip::File.open_buffer(csv_zip) do |zip| zip.find { |entry| entry.name.start_with?(API_FILE_PREFIX) }.get_input_stream do |io| # The first four lines include irrelevant metadata that break the parsing csv = CSV.new(io.readlines[4..].join, headers: true) year = Integer(csv.read.headers.second_to_last, exception: false) raise "Couldn't determine correct year" if year.nil? || (year - Date.current.year).abs > 2 csv.rewind csv.each do |ppp_data| country = ISO3166::Country.find_country_by_alpha3(ppp_data["Country Code"]) next if country.blank? ppp_rate = (ppp_data[year.to_s].presence || 1).to_f exchange_rate = get_rate(country.currency_code).to_f next if exchange_rate.blank? ppp_factor = (ppp_rate / exchange_rate).round(2) ppp_factor = 1 if ppp_factor > UPPER_THRESHOLD ppp_factor = LOWER_THRESHOLD if ppp_factor < LOWER_THRESHOLD ppp_service.set_factor(country.alpha2, ppp_factor) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_stripe_apple_pay_domain_worker.rb
app/sidekiq/create_stripe_apple_pay_domain_worker.rb
# frozen_string_literal: true class CreateStripeApplePayDomainWorker include Sidekiq::Job sidekiq_options retry: 3, queue: :low def perform(user_id, domain = nil) return if Rails.env.test? user = User.find(user_id) domain ||= Subdomain.from_username(user.username) if domain && StripeApplePayDomain.find_by(user_id:, domain:).blank? response = Stripe::ApplePayDomain.create(domain_name: domain) if response StripeApplePayDomain.create( user_id:, domain:, stripe_id: response.id ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/mass_refund_for_fraud_job.rb
app/sidekiq/mass_refund_for_fraud_job.rb
# frozen_string_literal: true class MassRefundForFraudJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed def perform(product_id, external_ids, admin_user_id) results = { success: 0, failed: 0, errors: {} } external_ids.each do |external_id| purchase = Purchase.find_by_external_id(external_id) unless purchase && purchase.link_id == product_id results[:failed] += 1 results[:errors][external_id] = "Purchase not found" next end begin purchase.refund_for_fraud_and_block_buyer!(admin_user_id) results[:success] += 1 rescue StandardError => e results[:failed] += 1 results[:errors][external_id] = e.message Rails.logger.error("Mass fraud refund failed for purchase #{external_id}: #{e.message}") Bugsnag.notify(e) do |event| event.add_metadata(:mass_refund, { product_id: product_id, purchase_external_id: external_id, admin_user_id: admin_user_id }) end end end Rails.logger.info("Mass fraud refund completed for product #{product_id}: #{results[:success]} succeeded, #{results[:failed]} failed") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_sns_aws_config_event_worker.rb
app/sidekiq/handle_sns_aws_config_event_worker.rb
# frozen_string_literal: true class HandleSnsAwsConfigEventWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :mongo MESSAGE_TYPES_TO_IGNORE = %w[ ConfigurationSnapshotDeliveryStarted ConfigurationSnapshotDeliveryCompleted ConfigurationHistoryDeliveryCompleted ].freeze private_constant :MESSAGE_TYPES_TO_IGNORE def build_default_attachment(params) { color: "danger", text: "```\n#{JSON.pretty_generate(params)}\n```", mrkdwn_in: ["text"] } end def build_message(message) configuration_item = message["configurationItem"] configuration_item_diff = message["configurationItemDiff"] return if configuration_item.nil? || configuration_item_diff.nil? region = configuration_item["awsRegion"] || AWS_DEFAULT_REGION timestamp = configuration_item["configurationItemCaptureTime"] resource_type = configuration_item["resourceType"] resource_id = configuration_item["resourceId"] resource_name = configuration_item["tags"].try(:[], "Name") related_cloudtrail_events = configuration_item["relatedEvents"] return if timestamp.nil? || resource_type.nil? || resource_id.nil? || related_cloudtrail_events.nil? config_url = "https://console.aws.amazon.com/config/home?region=#{region}#/timeline/#{resource_type}/#{resource_id}?time=#{timestamp}" "#{resource_id} • #{resource_name} • <#{config_url}|AWS Config>" end def perform(params) if params["Type"] == "Notification" message_content = JSON.parse(params["Message"]) message_type = message_content["messageType"] return if MESSAGE_TYPES_TO_IGNORE.include?(message_type) message = build_message(message_content) end if message SlackMessageWorker.perform_async("internals_log", "AWS Config", message, "gray") else attachment = build_default_attachment(params) SlackMessageWorker.perform_async("internals_log", "AWS Config", "", "red", attachments: [attachment]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/review_reminder_job.rb
app/sidekiq/review_reminder_job.rb
# frozen_string_literal: true class ReviewReminderJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(purchase_id) purchase = Purchase.find(purchase_id) return unless purchase.eligible_for_review_reminder? SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer", "review_reminder", purchase_id) do CustomerLowPriorityMailer.purchase_review_reminder(purchase_id).deliver_later(queue: :low) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/create_us_states_sales_summary_report_job.rb
app/sidekiq/create_us_states_sales_summary_report_job.rb
# frozen_string_literal: true class CreateUsStatesSalesSummaryReportJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed attr_reader :taxjar_api def perform(subdivision_codes, month, year, push_to_taxjar: true) raise ArgumentError, "Invalid month" unless month.in?(1..12) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) @taxjar_api = TaxjarApi.new @push_to_taxjar = push_to_taxjar subdivisions = subdivision_codes.map do |code| Compliance::Countries::USA.subdivisions[code].tap { |value| raise ArgumentError, "Invalid subdivision code" unless value } end row_headers = [ "State", "GMV", "Number of orders", "Sales tax collected" ] purchase_ids_by_state = Purchase.successful .not_fully_refunded .not_chargedback_or_chargedback_reversed .where.not(stripe_transaction_id: nil) .where("purchases.created_at BETWEEN ? AND ?", Date.new(year, month).beginning_of_month.beginning_of_day, Date.new(year, month).end_of_month.end_of_day) .where("(country = 'United States') OR ((country IS NULL OR country = 'United States') AND ip_country = 'United States')") .where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids]) .pluck(:id, :zip_code, :ip_address) .each_with_object({}) do |purchase_attributes, result| id, zip_code, ip_address = purchase_attributes subdivisions.each do |subdivision| if zip_code.present? if subdivision.code == UsZipCodes.identify_state_code(zip_code) result[subdivision.code] ||= [] result[subdivision.code] << id end elsif subdivision.code == GeoIp.lookup(ip_address)&.region_name result[subdivision.code] ||= [] result[subdivision.code] << id end end end begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) purchase_ids_by_state.each do |subdivision_code, purchase_ids| next if purchase_ids.empty? subdivision = Compliance::Countries::USA.subdivisions[subdivision_code] gmv_cents = 0 order_count = 0 tax_collected_cents = 0 purchase_ids.each do |id| purchase = Purchase.find(id) zip_code = purchase.zip_code if purchase.zip_code.present? && subdivision.code == UsZipCodes.identify_state_code(purchase.zip_code) unless zip_code geo_ip = GeoIp.lookup(purchase.ip_address) zip_code = geo_ip&.postal_code if subdivision.code == geo_ip&.region_name end next unless zip_code price_cents = purchase.price_cents_net_of_refunds shipping_cents = purchase.shipping_cents gumroad_tax_cents = purchase.gumroad_tax_cents_net_of_refunds price_dollars = price_cents / 100.0 unit_price_dollars = price_dollars / purchase.quantity shipping_dollars = shipping_cents / 100.0 amount_dollars = price_dollars + shipping_dollars sales_tax_dollars = gumroad_tax_cents / 100.0 destination = { country: Compliance::Countries::USA.alpha2, state: subdivision.code, zip: zip_code } retries = 0 begin if @push_to_taxjar taxjar_api.create_order_transaction(transaction_id: purchase.external_id, transaction_date: purchase.created_at.iso8601, destination:, quantity: purchase.quantity, product_tax_code: Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type], amount_dollars:, shipping_dollars:, sales_tax_dollars:, unit_price_dollars:) end rescue Taxjar::Error::GatewayTimeout, Taxjar::Error::InternalServerError => e retries += 1 if retries < 3 Rails.logger.info("CreateUsStatesSalesSummaryReportJob: TaxJar error for purchase with external ID #{purchase.external_id}. Retry attempt #{retries}/3. #{e.class}: #{e.message}") sleep(1) retry else Rails.logger.error("CreateUsStatesSalesSummaryReportJob: TaxJar error for purchase with external ID #{purchase.external_id} after 3 retry attempts. #{e.class}: #{e.message}") raise end rescue Taxjar::Error::UnprocessableEntity => e Rails.logger.info("CreateUsStatesSalesSummaryReportJob: Purchase with external ID #{purchase.external_id} was already created as a TaxJar transaction. #{e.class}: #{e.message}") rescue Taxjar::Error::BadRequest => e Bugsnag.notify(e) Rails.logger.info("CreateUsStatesSalesSummaryReportJob: Failed to create TaxJar transaction for purchase with external ID #{purchase.external_id}. #{e.class}: #{e.message}") end gmv_cents += purchase.total_cents_net_of_refunds order_count += 1 tax_collected_cents += gumroad_tax_cents end temp_file.write([ subdivision.name, Money.new(gmv_cents).format(no_cents_if_whole: false, symbol: false), order_count, Money.new(tax_collected_cents).format(no_cents_if_whole: false, symbol: false) ].to_csv) temp_file.flush end temp_file.rewind s3_filename = "us-states-sales-tax-summary-#{year}-#{month}-#{SecureRandom.hex(4)}.csv" s3_report_key = "sales-tax/summary/#{s3_filename}" s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s SlackMessageWorker.perform_async("payments", "US Sales Tax Summary Report", "Multi-state summary report for #{year}-#{month} is ready:\n#{s3_signed_url}", "green") ensure temp_file.close end end private def fetch_taxjar_info(purchase:, subdivision:, zip_code:, price_cents:) return unless @push_to_taxjar origin = { country: GumroadAddress::COUNTRY.alpha2, state: GumroadAddress::STATE, zip: GumroadAddress::ZIP } destination = { country: Compliance::Countries::USA.alpha2, state: subdivision.code, zip: zip_code } nexus_address = { country: Compliance::Countries::USA.alpha2, state: subdivision.code } product_tax_code = Link::NATIVE_TYPES_TO_TAX_CODE[purchase.link.native_type] quantity = purchase.quantity unit_price_dollars = price_cents / 100.0 / quantity shipping_dollars = purchase.shipping_cents / 100.0 begin taxjar_api.calculate_tax_for_order(origin:, destination:, nexus_address:, quantity:, product_tax_code:, unit_price_dollars:, shipping_dollars:) rescue Taxjar::Error::NotFound, Taxjar::Error::BadRequest end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_utm_link_stats_job.rb
app/sidekiq/update_utm_link_stats_job.rb
# frozen_string_literal: true class UpdateUtmLinkStatsJob include Sidekiq::Job sidekiq_options queue: :low, lock: :until_executed, retry: 1 def perform(utm_link_id) utm_link = UtmLink.find(utm_link_id) utm_link.update!( total_clicks: utm_link.utm_link_visits.count, unique_clicks: utm_link.utm_link_visits.distinct.count(:browser_guid) ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/suspend_accounts_with_payment_address_worker.rb
app/sidekiq/suspend_accounts_with_payment_address_worker.rb
# frozen_string_literal: true class SuspendAccountsWithPaymentAddressWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_id) suspended_user = User.find(user_id) return if suspended_user.payment_address.blank? User.where(payment_address: suspended_user.payment_address).where.not(id: suspended_user.id).find_each do |user| user.flag_for_fraud( author_name: "suspend_sellers_other_accounts", content: "Flagged for fraud automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of usage of payment address #{suspended_user.payment_address} (from User##{suspended_user.id})" ) user.suspend_for_fraud( author_name: "suspend_sellers_other_accounts", content: "Suspended for fraud automatically on #{Time.current.to_fs(:formatted_date_full_month)} because of usage of payment address #{suspended_user.payment_address} (from User##{suspended_user.id})" ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_resend_event_job.rb
app/sidekiq/handle_resend_event_job.rb
# frozen_string_literal: true class HandleResendEventJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(event_json) resend_event_info = ResendEventInfo.new(event_json) return if resend_event_info.invalid? HandleEmailEventInfo.perform(resend_event_info) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/unsubscribe_and_fail_worker.rb
app/sidekiq/unsubscribe_and_fail_worker.rb
# frozen_string_literal: true class UnsubscribeAndFailWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) return if !subscription.alive?(include_pending_cancellation: false) || subscription.is_test_subscription || !subscription.overdue_for_charge? subscription.unsubscribe_and_fail! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/sync_stuck_payouts_job.rb
app/sidekiq/sync_stuck_payouts_job.rb
# frozen_string_literal: true class SyncStuckPayoutsJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed def perform(processor) Payment.where(processor:, state: %w(creating processing unclaimed)).find_each do |payment| Rails.logger.info("Syncing payout #{payment.id} stuck in #{payment.state} state") begin payment.with_lock do payment.sync_with_payout_processor end rescue => e Rails.logger.error("Error syncing payout #{payment.id}: #{e.message}") next end Rails.logger.info("Payout #{payment.id} synced to #{payment.state} state") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/reindex_user_elasticsearch_data_worker.rb
app/sidekiq/reindex_user_elasticsearch_data_worker.rb
# frozen_string_literal: true class ReindexUserElasticsearchDataWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low, lock: :until_executed ADMIN_NOTE = "Refreshed ES Data" def perform(user_id, admin_id) user = User.find user_id admin = User.find admin_id DevTools.reindex_all_for_user(user.id) comment = user.comments.build comment.author_id = admin.id comment.author_name = admin.name comment.comment_type = :note comment.content = ADMIN_NOTE comment.save! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/process_payment_worker.rb
app/sidekiq/process_payment_worker.rb
# frozen_string_literal: true class ProcessPaymentWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low, lock: :until_executed def perform(payment_id) payment = Payment.find(payment_id) return unless payment.processing? PayoutProcessorType.get(payment.processor).process_payments([payment]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/custom_domain_verification_worker.rb
app/sidekiq/custom_domain_verification_worker.rb
# frozen_string_literal: true class CustomDomainVerificationWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(custom_domain_id) custom_domain = CustomDomain.find(custom_domain_id) return if custom_domain.deleted? return unless custom_domain.valid? custom_domain.verify custom_domain.save! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/suspend_users_worker.rb
app/sidekiq/suspend_users_worker.rb
# frozen_string_literal: true class SuspendUsersWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(author_id, user_ids, reason, additional_notes) User.where(id: user_ids).or(User.where(external_id: user_ids)).find_each(batch_size: 100) do |user| user.flag_for_tos_violation(author_id:, bulk: true) author_name = User.find(author_id).name_or_username content = "Suspended for a policy violation by #{author_name} on #{Time.current.to_fs(:formatted_date_full_month)} as part of mass suspension. Reason: #{reason}." content += "\nAdditional notes: #{additional_notes}" if additional_notes.present? user.suspend_for_tos_violation(author_id:, content:) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/reindex_recommendable_products_worker.rb
app/sidekiq/reindex_recommendable_products_worker.rb
# frozen_string_literal: true class ReindexRecommendableProductsWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default SCROLL_SIZE = 1000 SCROLL_SORT = ["_doc"] def perform response = EsClient.search( index: Link.index_name, scroll: "1m", body: { query: { term: { is_recommendable: true } } }, size: SCROLL_SIZE, sort: SCROLL_SORT, _source: false ) index = 0 loop do hits = response.dig("hits", "hits") ids = hits.map { |hit| hit["_id"] } filtered_ids = Purchase. where(link_id: ids). group(:link_id). having("max(created_at) >= ?", Product::Searchable::DEFAULT_SALES_VOLUME_RECENTNESS.ago). pluck(:link_id) unless filtered_ids.empty? args = filtered_ids.map do |id| [id, "update", ["sales_volume", "total_fee_cents", "past_year_fee_cents"]] end Sidekiq::Client.push_bulk( "class" => SendToElasticsearchWorker, "args" => args, "queue" => "low", "at" => index.minutes.from_now.to_i, ) end break if hits.size < SCROLL_SIZE index += 1 response = EsClient.scroll( index: Link.index_name, body: { scroll_id: response["_scroll_id"] }, scroll: "1m" ) end EsClient.clear_scroll(scroll_id: response["_scroll_id"]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/million_dollar_milestone_check_worker.rb
app/sidekiq/million_dollar_milestone_check_worker.rb
# frozen_string_literal: true class MillionDollarMilestoneCheckWorker include Sidekiq::Job include Rails.application.routes.url_helpers MILLION_DOLLARS_IN_CENTS = 1_000_000_00 sidekiq_options retry: 5, queue: :low def perform purchase_creation_time_range = Range.new(3.weeks.ago.days_ago(2), 2.weeks.ago) seller_ids_sub_query = Purchase.created_between(purchase_creation_time_range). all_success_states.not_chargedback_or_chargedback_reversed. select(:seller_id). distinct User.not_million_dollar_announcement_sent.where(id: seller_ids_sub_query).find_each do |user| next if user.gross_sales_cents_total_as_seller < MILLION_DOLLARS_IN_CENTS compliance_info = user.alive_user_compliance_info message = "<#{user.profile_url}|#{user.name_or_username}> has crossed $1M in earnings :tada:\n" \ "• Name: #{user.name}\n" \ "• Username: #{user.username}\n" \ "• Email: #{user.email}\n" if compliance_info.present? message += "• First name: #{compliance_info.first_name}\n" \ "• Last name: #{compliance_info.last_name}\n" \ "• Street address: #{compliance_info.street_address}\n" \ "• City: #{compliance_info.city}\n" \ "• State: #{compliance_info.state}\n" \ "• ZIP code: #{compliance_info.zip_code}\n" \ "• Country: #{compliance_info.country}" end if user.update(million_dollar_announcement_sent: true) SlackMessageWorker.perform_async("awards", "Gumroad Awards", message, "hotpink") else Bugsnag.notify("Failed to send Slack notification for million dollar milestone", user_id: user.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_year_in_review_email_job.rb
app/sidekiq/send_year_in_review_email_job.rb
# frozen_string_literal: true class SendYearInReviewEmailJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(seller_id, year, recipient = nil) analytics_data = {} seller = User.find(seller_id) range = Date.new(year).all_year payout_csv_url = seller.financial_annual_report_url_for(year:) # Don't send email to user without any payouts return unless payout_csv_url.present? data_by_date = CreatorAnalytics::CachingProxy.new(seller).data_for_dates(range.begin, range.end, by: :date) analytics_data[:total_views_count] = data_by_date[:by_date][:views].values.flatten.sum analytics_data[:total_sales_count] = data_by_date[:by_date][:sales].values.flatten.sum analytics_data[:total_products_sold_count] = data_by_date[:by_date][:sales].transform_values(&:sum).filter { |_, total| total.nonzero? }.keys.count analytics_data[:total_amount_cents] = data_by_date[:by_date][:totals].values.flatten.sum # Don't send email to creators who received earnings only from affiliate sales return if analytics_data[:total_amount_cents].zero? analytics_data[:top_selling_products] = map_top_selling_products(seller, data_by_date[:by_date]) data_by_state = CreatorAnalytics::CachingProxy.new(seller).data_for_dates(range.begin, range.end, by: :state) analytics_data[:by_country] = build_stats_by_country(data_by_state[:by_state]) analytics_data[:total_countries_with_sales_count] = analytics_data[:by_country].size analytics_data[:total_unique_customers_count] = seller.sales .successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback .where("created_at between :start and :end", start: range.begin.in_time_zone(seller.timezone), end: range.end.in_time_zone(seller.timezone).end_of_day) .select(:email) .distinct .count CreatorMailer.year_in_review( seller:, year:, analytics_data:, payout_csv_url:, recipient:, ).deliver_now end private def calculate_stats_by_country(data) data.values.each_with_object({}) do |hash, result| hash.each do |country, stats| sum = Array.wrap(stats).sum result[country] = result.key?(country) ? result[country] + sum : sum end end end def build_stats_by_country(data_by_state) totals = calculate_stats_by_country(data_by_state[:totals]) sales = calculate_stats_by_country(data_by_state[:sales]) views = calculate_stats_by_country(data_by_state[:views]) stats_by_country = totals.to_h do |country_name, total_amount_cents| [ Compliance::Countries.country_with_flag_by_name(country_name), # SendGrid has a hard limit of 10KB for the custom arguments # Ref: https://docs.sendgrid.com/api-reference/mail-send/limitations # # Mapping to an Array instead of a Hash w/ key/value pairs to cut down the size of the analytics data in half [ views[country_name] || 0, # Views sales[country_name], # Sales total_amount_cents.nonzero? ? total_amount_cents / 100 : 0, # Total ] ] end # Split data by "Elsewhere" vs. All other countries all_other_sales, elsewhere_sales = stats_by_country.partition do |(country_key, _)| country_key != Compliance::Countries.elsewhere_with_flag end # Remove countries with $0 sales, sort by total and append "Elsewhere" sales all_other_sales .filter { |(_, (_, _, total))| total.nonzero? } .sort_by { |(_, (_, _, total))| -total } .concat(elsewhere_sales) .to_h end def map_top_selling_products(seller, data_by_date) top_product_totals = data_by_date[:totals].transform_values(&:sum) .filter { |_, total| total.nonzero? } .sort_by { |key, total| [-total, key] } .first(5) .to_h top_product_permalinks = top_product_totals.keys top_product_stats = top_product_permalinks.index_with do |permalink| # SendGrid has a hard limit of 10KB for the custom arguments # Ref: https://docs.sendgrid.com/api-reference/mail-send/limitations # # Mapping to an Array instead of a Hash w/ key/value pairs to cut down the size of the analytics data in half [ data_by_date[:views][permalink].sum, # Views data_by_date[:sales][permalink].sum, # Sales top_product_totals[permalink] / 100, # Total ] end seller.products.where(unique_permalink: top_product_permalinks).map do |product| ProductPresenter.card_for_email(product:).merge( { stats: top_product_stats[product.unique_permalink] } ) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_finances_report_worker.rb
app/sidekiq/send_finances_report_worker.rb
# frozen_string_literal: true class SendFinancesReportWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace def perform return unless Rails.env.production? last_month = Time.current.last_month AccountingMailer.funds_received_report(last_month.month, last_month.year).deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/cancel_preorder_worker.rb
app/sidekiq/cancel_preorder_worker.rb
# frozen_string_literal: true class CancelPreorderWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(preorder_id) preorder = Preorder.find_by(id: preorder_id) return unless preorder.is_authorization_successful? preorder.mark_cancelled!(auto_cancelled: true) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/refresh_sitemap_monthly_worker.rb
app/sidekiq/refresh_sitemap_monthly_worker.rb
# frozen_string_literal: true class RefreshSitemapMonthlyWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :low def perform # Update sitemap of products updated in the last month last_month_start = 1.month.ago.beginning_of_month last_month_end = last_month_start.end_of_month updated_products = Link.select("DISTINCT DATE_FORMAT(created_at,'01-%m-%Y') AS created_month").where(updated_at: (last_month_start..last_month_end)) product_created_months = updated_products.map do |product| Date.parse(product.attributes["created_month"]) end # Generate sitemaps with 30 minutes gap to reduce the pressure on DB product_created_months.each_with_index do |month, index| RefreshSitemapDailyWorker.perform_in((30 * index).minutes, month.to_s) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_bundle_purchases_content_job.rb
app/sidekiq/update_bundle_purchases_content_job.rb
# frozen_string_literal: true class UpdateBundlePurchasesContentJob include Sidekiq::Job sidekiq_options retry: 3, queue: :low def perform(bundle_id) bundle = Link.is_bundle.find(bundle_id) return if !bundle.has_outdated_purchases? bundle.update!(has_outdated_purchases: false) content_updated_at = bundle.bundle_products.alive.maximum(:updated_at) bundle.sales .is_bundle_purchase .successful_gift_or_nongift .not_chargedback .not_fully_refunded .where(created_at: ..content_updated_at) .find_in_batches do |batch| batch.each { Purchase::UpdateBundlePurchaseContentService.new(_1).perform } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/push_notification_worker.rb
app/sidekiq/push_notification_worker.rb
# frozen_string_literal: true class PushNotificationWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :critical def perform(receiver_id, app_type, title, body = nil, data = {}, sound = nil) receiver = User.find receiver_id receiver.devices.where(app_type:).each do |device| case device.device_type when "ios" PushNotificationService::Ios.new(device_token: device.token, title:, body:, data:, app_type:, sound:).process when "android" PushNotificationService::Android.new(device_token: device.token, title:, body:, data:, app_type:, sound:).process end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_currencies_worker.rb
app/sidekiq/update_currencies_worker.rb
# frozen_string_literal: true class UpdateCurrenciesWorker include Sidekiq::Job include CurrencyHelper sidekiq_options retry: 5, queue: :default def perform rates = JSON.parse(URI.open(CURRENCY_SOURCE).read)["rates"] rates.each do |currency, rate| currency_namespace.set(currency.to_s, rate) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/post_to_individual_ping_endpoint_worker.rb
app/sidekiq/post_to_individual_ping_endpoint_worker.rb
# frozen_string_literal: true class PostToIndividualPingEndpointWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :critical ERROR_CODES_TO_RETRY = [499, 500, 502, 503, 504].freeze BACKOFF_STRATEGY = [60, 180, 600, 3600].freeze NOTIFICATION_THROTTLE_PERIOD = 1.week.freeze def perform(post_url, params, content_type = Mime[:url_encoded_form].to_s, user_id = nil) retry_count = params["retry_count"] || 0 body = if content_type == Mime[:json] params.to_json elsif content_type == Mime[:url_encoded_form] params.deep_transform_keys { encode_brackets(_1) } else params end response = HTTParty.post(post_url, body:, timeout: 5, headers: { "Content-Type" => content_type }) Rails.logger.info("PostToIndividualPingEndpointWorker response=#{response.code} url=#{post_url} content_type=#{content_type} params=#{params.inspect}") unless response.success? if ERROR_CODES_TO_RETRY.include?(response.code) && retry_count < (BACKOFF_STRATEGY.length - 1) PostToIndividualPingEndpointWorker.perform_in(BACKOFF_STRATEGY[retry_count].seconds, post_url, params.merge("retry_count" => retry_count + 1), content_type, user_id) else send_ping_failure_notification(post_url, response.code, user_id) end end # rescue clause to handle connection errors. Without this, the job # would fail if the user inputted post_url is invalid. rescue *INTERNET_EXCEPTIONS => e Rails.logger.info("[#{e.class}] PostToIndividualPingEndpointWorker error=\"#{e.message}\" url=#{post_url} content_type=#{content_type} params=#{params.inspect}") end private def encode_brackets(key) key.to_s.gsub(/[\[\]]/) { |char| URI.encode_www_form_component(char) } end def send_ping_failure_notification(post_url, response_code, user_id = nil) return unless Feature.active?(:alert_on_ping_endpoint_failure) return unless user_id.present? seller = User.find_by(id: user_id) return unless seller # Only send notifications for seller.notification_endpoint failures, not resource subscriptions # TODO: We can configure notifications for resource subscription URLs too when we have a UI to edit/delete resource subscription URLs return unless post_url == seller.notification_endpoint if seller.last_ping_failure_notification_at.present? last_notification = Time.zone.parse(seller.last_ping_failure_notification_at) return if last_notification >= NOTIFICATION_THROTTLE_PERIOD.ago end ContactingCreatorMailer.ping_endpoint_failure(seller.id, post_url, response_code).deliver_later(queue: "critical") seller.last_ping_failure_notification_at = Time.current.to_s seller.save! end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_cached_sales_related_products_infos_job.rb
app/sidekiq/update_cached_sales_related_products_infos_job.rb
# frozen_string_literal: true class UpdateCachedSalesRelatedProductsInfosJob include Sidekiq::Job sidekiq_options retry: 3, queue: :low, lock: :until_executed # We don't need to store the fact that a (popular) product is related to 100k other ones, # especially when many of these have been only purchased a small number of times, # which will end up making no difference in the final recommendations. # However, the higher limit, the larger the "breadth" of the recommendations will be: A user who already # purchased a lot of similar products will still be able to be recommended new, lesser known products. RELATED_PRODUCTS_LIMIT = 500 def perform(product_id) product = Link.find(product_id) counts = SalesRelatedProductsInfo.related_product_ids_and_sales_counts(product.id, limit: RELATED_PRODUCTS_LIMIT) cache = CachedSalesRelatedProductsInfo.find_or_create_by!(product:) cache.update!(counts:) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false