Compare commits
62
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce8f40debb | ||
|
|
5ca8aec7c3 | ||
|
|
4b8b33c4fd | ||
|
|
b7035de400 | ||
|
|
cec1a64d6f | ||
|
|
8b0caa6909 | ||
|
|
56160bfc63 | ||
|
|
abca836f0c | ||
|
|
64640092aa | ||
|
|
d478f6e42e | ||
|
|
ea34071553 | ||
|
|
fb86b1354a | ||
|
|
ab28802d5a | ||
|
|
f6ec3f3a72 | ||
|
|
d51148951f | ||
|
|
79bb3d0ef3 | ||
|
|
7418882a4f | ||
|
|
d38bd5139e | ||
|
|
fcc6973245 | ||
|
|
2590c57893 | ||
|
|
f225e2fcd8 | ||
|
|
b626e0cbf1 | ||
|
|
35f42e71f6 | ||
|
|
eb04882e5a | ||
|
|
e511527f32 | ||
|
|
ce5a859a4f | ||
|
|
94985bbc77 | ||
|
|
f31d9a3e76 | ||
|
|
79082bea58 | ||
|
|
b9f68fc839 | ||
|
|
e10ef03490 | ||
|
|
6f9f2c32c9 | ||
|
|
f999112671 | ||
|
|
be37c5b80c | ||
|
|
3970149b06 | ||
|
|
9c33ce50b3 | ||
|
|
36a2412f42 | ||
|
|
3ba4340042 | ||
|
|
411048715d | ||
|
|
9a7a2486e4 | ||
|
|
39af360a18 | ||
|
|
ac1743514b | ||
|
|
c1df37b41d | ||
|
|
7c3b07c507 | ||
|
|
62203da528 | ||
|
|
029294e16b | ||
|
|
2c095bed86 | ||
|
|
7c6508dd04 | ||
|
|
cef23891af | ||
|
|
19a851c01d | ||
|
|
a22e11c810 | ||
|
|
efe6e64dcd | ||
|
|
d6f5c627eb | ||
|
|
51b4a8f9fc | ||
|
|
1268b2cf55 | ||
|
|
125ae5523a | ||
|
|
59f60936a7 | ||
|
|
216a2c0e73 | ||
|
|
708296a746 | ||
|
|
b9168664f7 | ||
|
|
01cd7b878d | ||
|
|
acb2816826 |
@@ -159,7 +159,7 @@ gem 'working_hours'
|
||||
gem 'pg_search'
|
||||
|
||||
# Subscriptions, Billing
|
||||
gem 'stripe'
|
||||
gem 'stripe', '17.2.0.pre.alpha.2'
|
||||
|
||||
## - helper gems --##
|
||||
## to populate db with sample data
|
||||
|
||||
+2
-2
@@ -902,7 +902,7 @@ GEM
|
||||
squasher (0.7.2)
|
||||
stackprof (0.2.25)
|
||||
statsd-ruby (1.5.0)
|
||||
stripe (8.5.0)
|
||||
stripe (17.2.0.pre.alpha.2)
|
||||
telephone_number (1.4.20)
|
||||
test-prof (1.2.1)
|
||||
thor (1.4.0)
|
||||
@@ -1110,7 +1110,7 @@ DEPENDENCIES
|
||||
spring-watcher-listen
|
||||
squasher
|
||||
stackprof
|
||||
stripe
|
||||
stripe (= 17.2.0.pre.alpha.2)
|
||||
telephone_number
|
||||
test-prof
|
||||
tidewave
|
||||
|
||||
@@ -30,4 +30,32 @@ class AccountPolicy < ApplicationPolicy
|
||||
def toggle_deletion?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def v2_pricing_plans?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def v2_topup_options?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def v2_topup?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def v2_subscribe?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def cancel_subscription?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def credit_grants?
|
||||
@account_user.administrator?
|
||||
end
|
||||
|
||||
def change_pricing_plan?
|
||||
@account_user.administrator?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,6 +6,17 @@ if resource.custom_attributes.present?
|
||||
json.subscribed_quantity resource.custom_attributes['subscribed_quantity']
|
||||
json.subscription_status resource.custom_attributes['subscription_status']
|
||||
json.subscription_ends_on resource.custom_attributes['subscription_ends_on']
|
||||
json.stripe_subscription_id resource.custom_attributes['stripe_subscription_id'] if resource.custom_attributes['stripe_subscription_id'].present?
|
||||
json.stripe_billing_version resource.custom_attributes['stripe_billing_version'] if resource.custom_attributes['stripe_billing_version'].present?
|
||||
json.stripe_customer_id resource.custom_attributes['stripe_customer_id'] if resource.custom_attributes['stripe_customer_id'].present?
|
||||
if resource.custom_attributes['pending_stripe_pricing_plan_id'].present?
|
||||
json.pending_stripe_pricing_plan_id resource.custom_attributes['pending_stripe_pricing_plan_id']
|
||||
end
|
||||
if resource.custom_attributes['pending_subscription_quantity'].present?
|
||||
json.pending_subscription_quantity resource.custom_attributes['pending_subscription_quantity']
|
||||
end
|
||||
json.stripe_pricing_plan_id resource.custom_attributes['stripe_pricing_plan_id'] if resource.custom_attributes['stripe_pricing_plan_id'].present?
|
||||
json.next_billing_date resource.custom_attributes['next_billing_date'] if resource.custom_attributes['next_billing_date'].present?
|
||||
json.industry resource.custom_attributes['industry'] if resource.custom_attributes['industry'].present?
|
||||
json.company_size resource.custom_attributes['company_size'] if resource.custom_attributes['company_size'].present?
|
||||
json.timezone resource.custom_attributes['timezone'] if resource.custom_attributes['timezone'].present?
|
||||
|
||||
@@ -431,6 +431,14 @@ Rails.application.routes.draw do
|
||||
post :subscription
|
||||
get :limits
|
||||
post :toggle_deletion
|
||||
# V2 Billing endpoints
|
||||
get :credit_grants
|
||||
get :v2_pricing_plans
|
||||
get :v2_topup_options
|
||||
post :v2_topup
|
||||
post :v2_subscribe
|
||||
post :cancel_subscription
|
||||
post :change_pricing_plan
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Stripe V2 Billing Scheduled Jobs
|
||||
# Add these to your config/sidekiq_cron.yml or config/schedule.yml
|
||||
|
||||
v2_credit_sync:
|
||||
cron: "0 * * * *" # Every hour
|
||||
class: "Enterprise::Billing::CreditSyncJob"
|
||||
queue: low
|
||||
description: "Sync V2 billing credits with Stripe"
|
||||
@@ -0,0 +1,96 @@
|
||||
module Enterprise::Api::V1::Accounts::Concerns::BillingV2
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
before_action :validate_topup_amount, only: [:v2_topup]
|
||||
end
|
||||
|
||||
def credit_grants
|
||||
service = Enterprise::Billing::V2::CreditManagementService.new(account: @account)
|
||||
grants = service.fetch_credit_grants
|
||||
|
||||
render json: { credit_grants: grants }
|
||||
end
|
||||
|
||||
def v2_pricing_plans
|
||||
plans = Enterprise::Billing::V2::PlanCatalog.plans
|
||||
render json: { pricing_plans: plans }
|
||||
end
|
||||
|
||||
def v2_topup_options
|
||||
options = Enterprise::Billing::V2::TopupCatalog.options
|
||||
render json: { topup_options: options }
|
||||
end
|
||||
|
||||
def v2_topup
|
||||
service = Enterprise::Billing::V2::TopupService.new(account: @account)
|
||||
result = service.create_topup(credits: params[:credits].to_i)
|
||||
|
||||
if result[:success]
|
||||
render json: { success: true, message: result[:message] }
|
||||
else
|
||||
render json: { error: result[:message] }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def v2_subscribe
|
||||
service = Enterprise::Billing::V2::CheckoutSessionService.new(account: @account)
|
||||
result = service.create_subscription_checkout(
|
||||
pricing_plan_id: params[:pricing_plan_id],
|
||||
quantity: subscription_quantity
|
||||
)
|
||||
|
||||
if result[:success]
|
||||
render json: { success: true, redirect_url: result[:redirect_url], session_id: result[:session_id] }
|
||||
else
|
||||
render json: { error: result[:message] }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def cancel_subscription
|
||||
service = Enterprise::Billing::V2::CancelSubscriptionService.new(account: @account)
|
||||
result = service.cancel_subscription
|
||||
|
||||
if result[:success]
|
||||
# Include account ID and updated attributes for frontend store update
|
||||
@account.reload
|
||||
render json: result.merge(
|
||||
id: @account.id,
|
||||
custom_attributes: @account.custom_attributes
|
||||
)
|
||||
else
|
||||
render json: { error: result[:message] }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def change_pricing_plan
|
||||
service = Enterprise::Billing::V2::ChangePlanService.new(account: @account)
|
||||
result = service.change_plan(
|
||||
new_pricing_plan_id: params[:pricing_plan_id],
|
||||
quantity: params[:quantity]&.to_i
|
||||
)
|
||||
|
||||
if result[:success]
|
||||
# Include account ID and updated attributes for frontend store update
|
||||
@account.reload
|
||||
render json: result.merge(
|
||||
id: @account.id,
|
||||
custom_attributes: @account.custom_attributes
|
||||
)
|
||||
else
|
||||
render json: { error: result[:message] }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def subscription_quantity
|
||||
[params[:quantity].to_i, 1].max
|
||||
end
|
||||
|
||||
def validate_topup_amount
|
||||
return if params[:credits].to_i.positive?
|
||||
|
||||
render json: { error: 'Topup amount must be greater than 0' }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
@@ -1,5 +1,7 @@
|
||||
class Enterprise::Api::V1::AccountsController < Api::BaseController
|
||||
include BillingHelper
|
||||
include Enterprise::Api::V1::Accounts::Concerns::BillingV2
|
||||
|
||||
before_action :fetch_account
|
||||
before_action :check_authorization
|
||||
before_action :check_cloud_env, only: [:limits, :toggle_deletion]
|
||||
|
||||
@@ -6,8 +6,17 @@ class Enterprise::Webhooks::StripeController < ActionController::API
|
||||
|
||||
# Attempt to verify the signature. If successful, we'll handle the event
|
||||
begin
|
||||
event = Stripe::Webhook.construct_event(payload, sig_header, ENV.fetch('STRIPE_WEBHOOK_SECRET', nil))
|
||||
::Enterprise::Billing::HandleStripeEventService.new.perform(event: event)
|
||||
# Determine which webhook secret to use based on event type
|
||||
webhook_secret = determine_webhook_secret(payload)
|
||||
|
||||
event = Stripe::Webhook.construct_event(payload, sig_header, webhook_secret)
|
||||
|
||||
# Check if this is a V2 billing event
|
||||
if v2_billing_event?(event.type)
|
||||
::Enterprise::Billing::V2::WebhookHandlerService.new.perform(event: event)
|
||||
else
|
||||
::Enterprise::Billing::HandleStripeEventService.new.perform(event: event)
|
||||
end
|
||||
# If we fail to verify the signature, then something was wrong with the request
|
||||
rescue JSON::ParserError, Stripe::SignatureVerificationError
|
||||
# Invalid payload
|
||||
@@ -18,4 +27,23 @@ class Enterprise::Webhooks::StripeController < ActionController::API
|
||||
# We've successfully processed the event without blowing up
|
||||
head :ok
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def determine_webhook_secret(payload)
|
||||
# Parse the payload to check event type without full verification
|
||||
parsed_payload = JSON.parse(payload)
|
||||
event_type = parsed_payload['type']
|
||||
|
||||
if v2_billing_event?(event_type)
|
||||
ENV.fetch('STRIPE_WEBHOOK_SECRET_V2', nil)
|
||||
else
|
||||
ENV.fetch('STRIPE_WEBHOOK_SECRET', nil)
|
||||
end
|
||||
end
|
||||
|
||||
def v2_billing_event?(event_type)
|
||||
Rails.logger.debug { "V2 billing event: #{event_type}" }
|
||||
event_type.start_with?('v2.')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
class Enterprise::Billing::CreditSyncJob < ApplicationJob
|
||||
queue_as :low
|
||||
|
||||
def perform(account = nil)
|
||||
if account
|
||||
sync_single_account(account)
|
||||
else
|
||||
sync_all_accounts
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def sync_all_accounts
|
||||
Rails.logger.info '[CreditSyncJob] Starting credit sync for all accounts'
|
||||
|
||||
accounts_with_stripe = Account.where(
|
||||
"custom_attributes->>'stripe_customer_id' IS NOT NULL AND (custom_attributes->>'stripe_billing_version')::integer = 2"
|
||||
)
|
||||
synced_count = 0
|
||||
failed_count = 0
|
||||
|
||||
accounts_with_stripe.find_each do |account|
|
||||
result = sync_account_credits(account)
|
||||
if result[:success]
|
||||
synced_count += 1 if result[:credits_reported].to_i.positive?
|
||||
else
|
||||
failed_count += 1
|
||||
Rails.logger.error "[CreditSyncJob] Failed to sync account #{account.id}: #{result[:message]}"
|
||||
end
|
||||
end
|
||||
|
||||
Rails.logger.info "[CreditSyncJob] Completed. Synced: #{synced_count}, Failed: #{failed_count}"
|
||||
{ synced: synced_count, failed: failed_count }
|
||||
end
|
||||
|
||||
def sync_single_account(account)
|
||||
Rails.logger.info "[CreditSyncJob] Syncing credits for account #{account.id}"
|
||||
result = sync_account_credits(account)
|
||||
|
||||
if result[:success]
|
||||
Rails.logger.info "[CreditSyncJob] Successfully synced account #{account.id}"
|
||||
else
|
||||
Rails.logger.error "[CreditSyncJob] Failed to sync account #{account.id}: #{result[:message]}"
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
def sync_account_credits(account)
|
||||
consumed_credits = account.custom_attributes&.[]('captain_responses_usage').to_i
|
||||
last_synced_credits = account.custom_attributes&.[]('stripe_last_synced_credits').to_i
|
||||
credits_to_report = consumed_credits - last_synced_credits
|
||||
|
||||
if credits_to_report.positive?
|
||||
handle_positive_credits(account, credits_to_report, consumed_credits)
|
||||
elsif credits_to_report.negative?
|
||||
handle_negative_credits(account, credits_to_report, consumed_credits)
|
||||
else
|
||||
{ success: true, message: 'Already in sync', credits_reported: 0 }
|
||||
end
|
||||
rescue StandardError => e
|
||||
handle_sync_error(account, e)
|
||||
end
|
||||
|
||||
def handle_positive_credits(account, credits_to_report, consumed_credits)
|
||||
reporter = Enterprise::Billing::V2::UsageReporterService.new(account: account)
|
||||
result = reporter.report(credits_to_report)
|
||||
|
||||
return result unless result[:success]
|
||||
|
||||
update_last_synced_credits(account, consumed_credits)
|
||||
Rails.logger.info "[CreditSyncJob] Account #{account.id}: reported #{credits_to_report} credits (total: #{consumed_credits})"
|
||||
result.merge(credits_reported: credits_to_report)
|
||||
end
|
||||
|
||||
def handle_negative_credits(account, credits_to_report, consumed_credits)
|
||||
Rails.logger.warn "[CreditSyncJob] Account #{account.id} has negative difference: #{credits_to_report}"
|
||||
update_last_synced_credits(account, consumed_credits)
|
||||
{ success: true, message: 'Reset sync point due to negative difference', credits_reported: 0 }
|
||||
end
|
||||
|
||||
def handle_sync_error(account, error)
|
||||
Rails.logger.error "[CreditSyncJob] Error syncing account #{account.id}: #{error.message}"
|
||||
Rails.logger.error error.backtrace.join("\n")
|
||||
{ success: false, message: error.message }
|
||||
end
|
||||
|
||||
def update_last_synced_credits(account, credits)
|
||||
account.with_lock do
|
||||
current_attributes = account.custom_attributes.present? ? account.custom_attributes.deep_dup : {}
|
||||
current_attributes['stripe_last_synced_credits'] = credits
|
||||
account.update!(custom_attributes: current_attributes)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,13 @@
|
||||
module Enterprise::Account::PlanUsageAndLimits
|
||||
# Total credits
|
||||
CAPTAIN_RESPONSES = 'captain_responses'.freeze
|
||||
CAPTAIN_DOCUMENTS = 'captain_documents'.freeze
|
||||
|
||||
# Response credits breakdown (monthly + topup)
|
||||
CAPTAIN_RESPONSES_MONTHLY = 'captain_responses_monthly'.freeze
|
||||
CAPTAIN_RESPONSES_TOPUP = 'captain_responses_topup'.freeze
|
||||
|
||||
# Usage tracking
|
||||
CAPTAIN_RESPONSES_USAGE = 'captain_responses_usage'.freeze
|
||||
CAPTAIN_DOCUMENTS_USAGE = 'captain_documents_usage'.freeze
|
||||
|
||||
@@ -16,8 +23,7 @@ module Enterprise::Account::PlanUsageAndLimits
|
||||
end
|
||||
|
||||
def increment_response_usage
|
||||
current_usage = custom_attributes[CAPTAIN_RESPONSES_USAGE].to_i || 0
|
||||
custom_attributes[CAPTAIN_RESPONSES_USAGE] = current_usage + 1
|
||||
custom_attributes[CAPTAIN_RESPONSES_USAGE] = (custom_attributes[CAPTAIN_RESPONSES_USAGE].to_i || 0) + 1
|
||||
save
|
||||
end
|
||||
|
||||
@@ -58,11 +64,12 @@ module Enterprise::Account::PlanUsageAndLimits
|
||||
else
|
||||
custom_attributes[CAPTAIN_RESPONSES_USAGE].to_i || 0
|
||||
end
|
||||
|
||||
consumed = 0 if consumed.negative?
|
||||
|
||||
{
|
||||
total_count: total_count,
|
||||
monthly: (self[:limits][CAPTAIN_RESPONSES_MONTHLY].to_i if type == :responses),
|
||||
topup: (self[:limits][CAPTAIN_RESPONSES_TOPUP].to_i if type == :responses),
|
||||
current_available: (total_count - consumed).clamp(0, total_count),
|
||||
consumed: consumed
|
||||
}
|
||||
@@ -96,17 +103,12 @@ module Enterprise::Account::PlanUsageAndLimits
|
||||
end
|
||||
|
||||
def agent_limits
|
||||
subscribed_quantity = custom_attributes['subscribed_quantity']
|
||||
subscribed_quantity || get_limits(:agents)
|
||||
custom_attributes['subscribed_quantity'] || get_limits(:agents)
|
||||
end
|
||||
|
||||
def get_limits(limit_name)
|
||||
config_name = "ACCOUNT_#{limit_name.to_s.upcase}_LIMIT"
|
||||
return self[:limits][limit_name.to_s] if self[:limits][limit_name.to_s].present?
|
||||
|
||||
return GlobalConfig.get(config_name)[config_name] if GlobalConfig.get(config_name)[config_name].present?
|
||||
|
||||
ChatwootApp.max_limit
|
||||
self[:limits][limit_name.to_s].presence || GlobalConfig.get(config_name)[config_name].presence || ChatwootApp.max_limit
|
||||
end
|
||||
|
||||
def validate_limit_keys
|
||||
@@ -119,7 +121,9 @@ module Enterprise::Account::PlanUsageAndLimits
|
||||
'inboxes' => { 'type': 'number' },
|
||||
'agents' => { 'type': 'number' },
|
||||
'captain_responses' => { 'type': 'number' },
|
||||
'captain_documents' => { 'type': 'number' }
|
||||
'captain_documents' => { 'type': 'number' },
|
||||
'captain_responses_monthly' => { 'type': 'number' },
|
||||
'captain_responses_topup' => { 'type': 'number' }
|
||||
},
|
||||
'required' => [],
|
||||
'additionalProperties' => false
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
module Enterprise::Billing::Concerns::BillingIntentWorkflow
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
# Execute a billing intent with automatic reserve and commit
|
||||
def execute_billing_intent(intent_params)
|
||||
intent = create_billing_intent(intent_params)
|
||||
reserve_billing_intent(intent['id'])
|
||||
yield(intent) if block_given?
|
||||
commit_billing_intent(intent['id'])
|
||||
intent
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
module Enterprise::Billing::Concerns::PlanDataHelper
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def fetch_plan_version(plan_id)
|
||||
plan = retrieve_pricing_plan(plan_id)
|
||||
version = extract_attribute(plan, :latest_version)
|
||||
raise StandardError, "No version found for pricing plan #{plan_id}" if version.blank?
|
||||
|
||||
version
|
||||
end
|
||||
|
||||
def fetch_plan_lookup_key(plan_id)
|
||||
lookup_key = Enterprise::Billing::V2::PlanCatalog.lookup_key_for_plan(plan_id)
|
||||
raise StandardError, "Lookup key not found for pricing plan #{plan_id}" unless lookup_key
|
||||
|
||||
lookup_key
|
||||
end
|
||||
|
||||
def plan_display_name(plan_id)
|
||||
Enterprise::Billing::V2::PlanCatalog.definition_for(plan_id)&.dig(:display_name) || 'Unknown Plan'
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,90 @@
|
||||
module Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
# Plan hierarchy: Hacker (default) -> Startup -> Business -> Enterprise
|
||||
# Each higher tier includes all features from the lower tiers
|
||||
|
||||
# Basic features available starting with the Startup plan
|
||||
STARTUP_PLAN_FEATURES = %w[
|
||||
inbound_emails
|
||||
help_center
|
||||
campaigns
|
||||
team_management
|
||||
channel_twitter
|
||||
channel_facebook
|
||||
channel_email
|
||||
channel_instagram
|
||||
captain_integration
|
||||
advanced_search_indexing
|
||||
advanced_search
|
||||
].freeze
|
||||
|
||||
# Additional features available starting with the Business plan
|
||||
BUSINESS_PLAN_FEATURES = %w[sla custom_roles].freeze
|
||||
|
||||
# Additional features available only in the Enterprise plan
|
||||
ENTERPRISE_PLAN_FEATURES = %w[audit_logs disable_branding saml].freeze
|
||||
|
||||
def update_plan_features(plan_name)
|
||||
if plan_name.blank? || plan_name == 'Hacker'
|
||||
disable_all_premium_features
|
||||
else
|
||||
enable_features_for_current_plan(plan_name)
|
||||
end
|
||||
|
||||
# Enable any manually managed features configured in internal_attributes
|
||||
enable_account_manually_managed_features
|
||||
|
||||
account.save!
|
||||
end
|
||||
|
||||
def disable_all_premium_features
|
||||
# Disable all features (for default Hacker plan or during plan changes)
|
||||
account.disable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.disable_features(*BUSINESS_PLAN_FEATURES)
|
||||
account.disable_features(*ENTERPRISE_PLAN_FEATURES)
|
||||
end
|
||||
|
||||
def enable_features_for_current_plan(plan_name)
|
||||
# First disable all premium features to handle downgrades
|
||||
disable_all_premium_features
|
||||
|
||||
# Then enable features based on the current plan
|
||||
enable_plan_specific_features(plan_name)
|
||||
end
|
||||
|
||||
def enable_plan_specific_features(plan_name)
|
||||
return if plan_name.blank?
|
||||
|
||||
# Enable features based on plan hierarchy
|
||||
case plan_name
|
||||
when 'Startup', 'Startups'
|
||||
# Startup plan gets the basic features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
when 'Business'
|
||||
# Business plan gets Startup features + Business features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.enable_features(*BUSINESS_PLAN_FEATURES)
|
||||
when 'Enterprise'
|
||||
# Enterprise plan gets all features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.enable_features(*BUSINESS_PLAN_FEATURES)
|
||||
account.enable_features(*ENTERPRISE_PLAN_FEATURES)
|
||||
end
|
||||
end
|
||||
|
||||
def reset_captain_usage
|
||||
account.reset_response_usage if account.respond_to?(:reset_response_usage)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def enable_account_manually_managed_features
|
||||
# Get manually managed features from internal attributes using the service
|
||||
service = Internal::Accounts::InternalAttributesService.new(account)
|
||||
features = service.manually_managed_features
|
||||
|
||||
# Enable each feature
|
||||
account.enable_features(*features) if features.present?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,42 @@
|
||||
module Enterprise::Billing::Concerns::PlanProvisioningHelper
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def provision_new_plan(new_pricing_plan_id)
|
||||
sync_plan_credits(new_pricing_plan_id)
|
||||
|
||||
plan_definition = Enterprise::Billing::V2::PlanCatalog.definition_for(new_pricing_plan_id)
|
||||
return unless plan_definition
|
||||
|
||||
plan_name = extract_plan_name(plan_definition)
|
||||
enable_plan_specific_features(plan_name) if plan_name.present?
|
||||
end
|
||||
|
||||
def sync_plan_credits(pricing_plan_id)
|
||||
plan_credits = Enterprise::Billing::V2::PlanCatalog.monthly_credits_for(pricing_plan_id)
|
||||
|
||||
Enterprise::Billing::V2::CreditManagementService
|
||||
.new(account: account)
|
||||
.sync_monthly_response_credits(plan_credits.to_i)
|
||||
end
|
||||
|
||||
def extract_plan_name(plan_definition)
|
||||
plan_definition[:display_name].split.find { |word| %w[Startup Startups Business Enterprise].include?(word) }
|
||||
end
|
||||
|
||||
def update_account_plan(new_pricing_plan_id, quantity, next_billing_date)
|
||||
attributes = {
|
||||
'stripe_pricing_plan_id' => new_pricing_plan_id,
|
||||
'pending_stripe_pricing_plan_id' => nil,
|
||||
'pending_subscription_quantity' => nil,
|
||||
'subscribed_quantity' => quantity,
|
||||
'next_billing_date' => next_billing_date
|
||||
}
|
||||
|
||||
plan_definition = Enterprise::Billing::V2::PlanCatalog.definition_for(new_pricing_plan_id)
|
||||
attributes['plan_name'] = plan_definition[:display_name] if plan_definition
|
||||
|
||||
update_custom_attributes(attributes)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,92 @@
|
||||
module Enterprise::Billing::Concerns::ProrationLineItemBuilder
|
||||
extend ActiveSupport::Concern
|
||||
include Enterprise::Billing::Concerns::PlanDataHelper
|
||||
|
||||
private
|
||||
|
||||
def build_proration_line_items(context, proration_data)
|
||||
return build_seat_change_line_items(context, proration_data) if seat_only_change?(context)
|
||||
|
||||
build_plan_change_line_items(context, proration_data)
|
||||
end
|
||||
|
||||
def seat_only_change?(context)
|
||||
!context[:plan_changed] && context[:seats_changed]
|
||||
end
|
||||
|
||||
def build_seat_change_line_items(context, proration_data)
|
||||
[{
|
||||
amount: (proration_data[:net_amount] * 100).to_i,
|
||||
description: build_seat_change_description(context),
|
||||
metadata: build_seat_change_metadata(context, proration_data)
|
||||
}]
|
||||
end
|
||||
|
||||
def build_plan_change_line_items(context, proration_data)
|
||||
line_items = []
|
||||
old_plan_name = plan_display_name(context[:old_plan_id])
|
||||
new_plan_name = plan_display_name(context[:target_plan_id])
|
||||
|
||||
line_items << build_credit_line_item(context, proration_data, old_plan_name) if proration_data[:credit_amount].positive?
|
||||
line_items << build_charge_line_item(context, proration_data, new_plan_name) if proration_data[:charge_amount].positive?
|
||||
|
||||
line_items
|
||||
end
|
||||
|
||||
def build_credit_line_item(context, proration_data, old_plan_name)
|
||||
{
|
||||
amount: -(proration_data[:credit_amount] * 100).to_i,
|
||||
description: credit_description(old_plan_name, context[:old_quantity]),
|
||||
metadata: credit_metadata(old_plan_name, context[:old_quantity], proration_data[:days_remaining])
|
||||
}
|
||||
end
|
||||
|
||||
def build_charge_line_item(context, proration_data, new_plan_name)
|
||||
{
|
||||
amount: (proration_data[:charge_amount] * 100).to_i,
|
||||
description: charge_description(new_plan_name, context[:target_quantity]),
|
||||
metadata: charge_metadata(new_plan_name, context[:target_quantity], proration_data[:days_remaining])
|
||||
}
|
||||
end
|
||||
|
||||
def credit_description(plan_name, quantity)
|
||||
"Credit for unused time on #{plan_name} (#{quantity} seat#{quantity > 1 ? 's' : ''})"
|
||||
end
|
||||
|
||||
def charge_description(plan_name, quantity)
|
||||
"Prorated charge for #{plan_name} (#{quantity} seat#{quantity > 1 ? 's' : ''})"
|
||||
end
|
||||
|
||||
def build_seat_change_description(context)
|
||||
plan_name = plan_display_name(context[:target_plan_id])
|
||||
change_type = context[:target_quantity] > context[:old_quantity] ? 'increase' : 'decrease'
|
||||
quantity_diff = (context[:target_quantity] - context[:old_quantity]).abs
|
||||
|
||||
"Seat #{change_type} for #{plan_name}: #{context[:old_quantity]} → #{context[:target_quantity]} " \
|
||||
"seats (#{quantity_diff} seat#{quantity_diff > 1 ? 's' : ''})"
|
||||
end
|
||||
|
||||
def base_metadata(type, days_remaining, **additional_fields)
|
||||
{
|
||||
type: type,
|
||||
days_remaining: days_remaining,
|
||||
billing_version: 'v2'
|
||||
}.merge(additional_fields)
|
||||
end
|
||||
|
||||
def credit_metadata(plan_name, quantity, days_remaining)
|
||||
base_metadata('proration_credit', days_remaining, old_plan: plan_name, old_quantity: quantity)
|
||||
end
|
||||
|
||||
def charge_metadata(plan_name, quantity, days_remaining)
|
||||
base_metadata('proration_charge', days_remaining, new_plan: plan_name, new_quantity: quantity)
|
||||
end
|
||||
|
||||
def build_seat_change_metadata(context, proration_data)
|
||||
base_metadata('seat_change', proration_data[:days_remaining],
|
||||
plan_name: plan_display_name(context[:target_plan_id]),
|
||||
old_quantity: context[:old_quantity],
|
||||
new_quantity: context[:target_quantity],
|
||||
quantity_change: context[:target_quantity] - context[:old_quantity])
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,65 @@
|
||||
module Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
# Stripe client instance with API key
|
||||
def stripe_client
|
||||
@stripe_client ||= Stripe::StripeClient.new(ENV.fetch('STRIPE_SECRET_KEY', nil))
|
||||
end
|
||||
|
||||
# Pricing Plan Subscriptions
|
||||
def retrieve_pricing_plan_subscription(subscription_id)
|
||||
stripe_client.v2.billing.pricing_plan_subscriptions.retrieve(subscription_id)
|
||||
end
|
||||
|
||||
# Pricing Plans
|
||||
def retrieve_pricing_plan(pricing_plan_id)
|
||||
stripe_client.v2.billing.pricing_plans.retrieve(pricing_plan_id)
|
||||
end
|
||||
|
||||
def retrieve_billing_cadence(cadence_id)
|
||||
stripe_client.v2.billing.cadences.retrieve(cadence_id)
|
||||
end
|
||||
|
||||
def create_billing_intent(params)
|
||||
response = Faraday.post('https://api.stripe.com/v2/billing/intents') do |req|
|
||||
req.headers['Authorization'] = "Bearer #{ENV.fetch('STRIPE_SECRET_KEY', nil)}"
|
||||
req.headers['Stripe-Version'] = default_stripe_version
|
||||
req.headers['Content-Type'] = 'application/json'
|
||||
req.body = params.to_json
|
||||
end
|
||||
|
||||
JSON.parse(response.body)
|
||||
end
|
||||
|
||||
def reserve_billing_intent(billing_intent_id)
|
||||
stripe_client.v2.billing.intents.reserve(billing_intent_id)
|
||||
end
|
||||
|
||||
def commit_billing_intent(billing_intent_id)
|
||||
stripe_client.v2.billing.intents.commit(billing_intent_id)
|
||||
end
|
||||
|
||||
# Checkout Sessions (V1 API but used with V2 plans)
|
||||
def create_checkout_session(params)
|
||||
Stripe::Checkout::Session.create(params, { stripe_version: checkout_stripe_version })
|
||||
end
|
||||
|
||||
# Credit Grants (V1 API but used with V2)
|
||||
def retrieve_credit_grant(grant_id)
|
||||
Stripe::Billing::CreditGrant.retrieve(grant_id)
|
||||
end
|
||||
|
||||
def default_stripe_version
|
||||
'2025-10-29.preview'
|
||||
end
|
||||
|
||||
def checkout_stripe_version
|
||||
'2025-10-29.preview;checkout_product_catalog_preview=v1'
|
||||
end
|
||||
|
||||
def extract_attribute(object, key)
|
||||
object.respond_to?(key) ? object.public_send(key) : object[key.to_s]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,41 @@
|
||||
module Enterprise::Billing::Concerns::SubscriptionDataManager
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def fetch_subscription_metadata
|
||||
subscription_id = fetch_subscription_id
|
||||
subscription = retrieve_pricing_plan_subscription(subscription_id)
|
||||
cadence_id = extract_cadence_id(subscription)
|
||||
cadence = retrieve_billing_cadence(cadence_id)
|
||||
next_billing_date = extract_attribute(cadence, :next_billing_date)
|
||||
|
||||
store_next_billing_date(next_billing_date)
|
||||
|
||||
{
|
||||
subscription_id: subscription_id,
|
||||
subscription: subscription,
|
||||
cadence_id: cadence_id,
|
||||
cadence: cadence,
|
||||
next_billing_date: next_billing_date
|
||||
}
|
||||
end
|
||||
|
||||
def fetch_subscription_id
|
||||
subscription_id = custom_attribute('stripe_subscription_id')
|
||||
raise StandardError, 'No pricing plan subscription ID found' if subscription_id.blank?
|
||||
|
||||
subscription_id
|
||||
end
|
||||
|
||||
def extract_cadence_id(subscription)
|
||||
cadence_id = extract_attribute(subscription, :billing_cadence)
|
||||
raise StandardError, 'No billing cadence found in subscription' if cadence_id.blank?
|
||||
|
||||
cadence_id
|
||||
end
|
||||
|
||||
def store_next_billing_date(next_billing_date)
|
||||
update_custom_attributes({ 'next_billing_date' => next_billing_date })
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,6 @@
|
||||
class Enterprise::Billing::CreateStripeCustomerService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
|
||||
pattr_initialize [:account!]
|
||||
|
||||
DEFAULT_QUANTITY = 2
|
||||
@@ -6,22 +8,11 @@ class Enterprise::Billing::CreateStripeCustomerService
|
||||
def perform
|
||||
return if existing_subscription?
|
||||
|
||||
raise_config_error unless v2_configs_present?
|
||||
|
||||
customer_id = prepare_customer_id
|
||||
subscription = Stripe::Subscription.create(
|
||||
{
|
||||
customer: customer_id,
|
||||
items: [{ price: price_id, quantity: default_quantity }]
|
||||
}
|
||||
)
|
||||
account.update!(
|
||||
custom_attributes: {
|
||||
stripe_customer_id: customer_id,
|
||||
stripe_price_id: subscription['plan']['id'],
|
||||
stripe_product_id: subscription['plan']['product'],
|
||||
plan_name: default_plan['name'],
|
||||
subscribed_quantity: subscription['quantity']
|
||||
}
|
||||
)
|
||||
update_account_for_v2_billing(customer_id)
|
||||
enable_plan_specific_features('Hacker')
|
||||
end
|
||||
|
||||
private
|
||||
@@ -35,22 +26,16 @@ class Enterprise::Billing::CreateStripeCustomerService
|
||||
customer_id
|
||||
end
|
||||
|
||||
def default_quantity
|
||||
default_plan['default_quantity'] || DEFAULT_QUANTITY
|
||||
end
|
||||
|
||||
def billing_email
|
||||
account.administrators.first.email
|
||||
end
|
||||
|
||||
def default_plan
|
||||
installation_config = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLANS')
|
||||
@default_plan ||= installation_config.value.first
|
||||
def v2_configs_present?
|
||||
InstallationConfig.find_by(name: 'STRIPE_HACKER_PLAN_ID').present?
|
||||
end
|
||||
|
||||
def price_id
|
||||
price_ids = default_plan['price_ids']
|
||||
price_ids.first
|
||||
def raise_config_error
|
||||
raise StandardError, 'V2 billing configuration is required. Please configure STRIPE_HACKER_PLAN_ID.'
|
||||
end
|
||||
|
||||
def existing_subscription?
|
||||
@@ -66,4 +51,23 @@ class Enterprise::Billing::CreateStripeCustomerService
|
||||
)
|
||||
subscriptions.data.present?
|
||||
end
|
||||
|
||||
def update_account_for_v2_billing(customer_id)
|
||||
hacker_plan_config = InstallationConfig.find_by(name: 'STRIPE_HACKER_PLAN_ID')
|
||||
|
||||
attributes = {
|
||||
stripe_customer_id: customer_id,
|
||||
stripe_billing_version: 2
|
||||
}
|
||||
|
||||
if hacker_plan_config&.value.present?
|
||||
attributes.merge!(
|
||||
stripe_pricing_plan_id: hacker_plan_config.value,
|
||||
plan_name: 'Hacker',
|
||||
subscribed_quantity: DEFAULT_QUANTITY
|
||||
)
|
||||
end
|
||||
|
||||
account.update!(custom_attributes: attributes)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,30 +1,9 @@
|
||||
class Enterprise::Billing::HandleStripeEventService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
|
||||
CLOUD_PLANS_CONFIG = 'CHATWOOT_CLOUD_PLANS'.freeze
|
||||
|
||||
# Plan hierarchy: Hacker (default) -> Startups -> Business -> Enterprise
|
||||
# Each higher tier includes all features from the lower tiers
|
||||
|
||||
# Basic features available starting with the Startups plan
|
||||
STARTUP_PLAN_FEATURES = %w[
|
||||
inbound_emails
|
||||
help_center
|
||||
campaigns
|
||||
team_management
|
||||
channel_twitter
|
||||
channel_facebook
|
||||
channel_email
|
||||
channel_instagram
|
||||
captain_integration
|
||||
advanced_search_indexing
|
||||
advanced_search
|
||||
].freeze
|
||||
|
||||
# Additional features available starting with the Business plan
|
||||
BUSINESS_PLAN_FEATURES = %w[sla custom_roles].freeze
|
||||
|
||||
# Additional features available only in the Enterprise plan
|
||||
ENTERPRISE_PLAN_FEATURES = %w[audit_logs disable_branding saml].freeze
|
||||
|
||||
def perform(event:)
|
||||
@event = event
|
||||
|
||||
@@ -33,6 +12,8 @@ class Enterprise::Billing::HandleStripeEventService
|
||||
process_subscription_updated
|
||||
when 'customer.subscription.deleted'
|
||||
process_subscription_deleted
|
||||
when 'billing.credit_grant.created'
|
||||
process_credit_grant_created
|
||||
else
|
||||
Rails.logger.debug { "Unhandled event type: #{event.type}" }
|
||||
end
|
||||
@@ -47,7 +28,8 @@ class Enterprise::Billing::HandleStripeEventService
|
||||
return if plan.blank? || account.blank?
|
||||
|
||||
update_account_attributes(subscription, plan)
|
||||
update_plan_features
|
||||
plan_name = account.custom_attributes['plan_name']
|
||||
update_plan_features(plan_name)
|
||||
reset_captain_usage
|
||||
end
|
||||
|
||||
@@ -73,65 +55,22 @@ class Enterprise::Billing::HandleStripeEventService
|
||||
Enterprise::Billing::CreateStripeCustomerService.new(account: account).perform
|
||||
end
|
||||
|
||||
def update_plan_features
|
||||
if default_plan?
|
||||
disable_all_premium_features
|
||||
else
|
||||
enable_features_for_current_plan
|
||||
end
|
||||
|
||||
# Enable any manually managed features configured in internal_attributes
|
||||
enable_account_manually_managed_features
|
||||
|
||||
account.save!
|
||||
end
|
||||
|
||||
def disable_all_premium_features
|
||||
# Disable all features (for default Hacker plan)
|
||||
account.disable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.disable_features(*BUSINESS_PLAN_FEATURES)
|
||||
account.disable_features(*ENTERPRISE_PLAN_FEATURES)
|
||||
end
|
||||
|
||||
def enable_features_for_current_plan
|
||||
# First disable all premium features to handle downgrades
|
||||
disable_all_premium_features
|
||||
|
||||
# Then enable features based on the current plan
|
||||
enable_plan_specific_features
|
||||
end
|
||||
|
||||
def reset_captain_usage
|
||||
account.reset_response_usage
|
||||
end
|
||||
|
||||
def enable_plan_specific_features
|
||||
plan_name = account.custom_attributes['plan_name']
|
||||
return if plan_name.blank?
|
||||
|
||||
# Enable features based on plan hierarchy
|
||||
case plan_name
|
||||
when 'Startups'
|
||||
# Startups plan gets the basic features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
when 'Business'
|
||||
# Business plan gets Startups features + Business features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.enable_features(*BUSINESS_PLAN_FEATURES)
|
||||
when 'Enterprise'
|
||||
# Enterprise plan gets all features
|
||||
account.enable_features(*STARTUP_PLAN_FEATURES)
|
||||
account.enable_features(*BUSINESS_PLAN_FEATURES)
|
||||
account.enable_features(*ENTERPRISE_PLAN_FEATURES)
|
||||
end
|
||||
end
|
||||
|
||||
def subscription
|
||||
@subscription ||= @event.data.object
|
||||
end
|
||||
|
||||
def account
|
||||
@account ||= Account.where("custom_attributes->>'stripe_customer_id' = ?", subscription.customer).first
|
||||
@account ||= begin
|
||||
customer_id = if @event.type.start_with?('billing.credit_grant')
|
||||
# Credit grant events have customer directly on the object
|
||||
@event.data.object.respond_to?(:customer) ? @event.data.object.customer : @event.data.object['customer']
|
||||
else
|
||||
# Subscription events have customer on subscription
|
||||
subscription.customer
|
||||
end
|
||||
|
||||
Account.where("custom_attributes->>'stripe_customer_id' = ?", customer_id).first
|
||||
end
|
||||
end
|
||||
|
||||
def find_plan(plan_id)
|
||||
@@ -139,18 +78,49 @@ class Enterprise::Billing::HandleStripeEventService
|
||||
cloud_plans.find { |config| config['product_id'].include?(plan_id) }
|
||||
end
|
||||
|
||||
def default_plan?
|
||||
cloud_plans = InstallationConfig.find_by(name: CLOUD_PLANS_CONFIG)&.value || []
|
||||
default_plan = cloud_plans.first || {}
|
||||
account.custom_attributes['plan_name'] == default_plan['name']
|
||||
def process_credit_grant_created
|
||||
grant_id = extract_credit_grant_id(@event.data.object)
|
||||
return if grant_id.blank?
|
||||
|
||||
# Retrieve the full credit grant object from Stripe API
|
||||
grant = retrieve_credit_grant(grant_id)
|
||||
return if grant.blank?
|
||||
|
||||
amount = extract_credit_amount(grant)
|
||||
return if amount.zero?
|
||||
|
||||
service = Enterprise::Billing::V2::CreditManagementService.new(account: account)
|
||||
service.add_response_topup_credits(amount)
|
||||
end
|
||||
|
||||
def enable_account_manually_managed_features
|
||||
# Get manually managed features from internal attributes using the service
|
||||
service = Internal::Accounts::InternalAttributesService.new(account)
|
||||
features = service.manually_managed_features
|
||||
def extract_credit_grant_id(grant_object)
|
||||
grant_object.respond_to?(:id) ? grant_object.id : grant_object['id']
|
||||
end
|
||||
|
||||
# Enable each feature
|
||||
account.enable_features(*features) if features.present?
|
||||
def extract_credit_amount(grant)
|
||||
# First, try to get credits from metadata
|
||||
metadata = extract_attribute(grant, :metadata)
|
||||
if metadata
|
||||
credits = extract_attribute(metadata, :credits)
|
||||
return credits.to_i if credits.present? && credits.to_i.positive?
|
||||
end
|
||||
|
||||
# Fallback: extract from amount object
|
||||
amount_data = extract_attribute(grant, :amount)
|
||||
return 0 unless amount_data
|
||||
|
||||
0
|
||||
end
|
||||
|
||||
def extract_attribute(object, attribute)
|
||||
object.respond_to?(attribute) ? object.public_send(attribute) : object[attribute.to_s]
|
||||
end
|
||||
|
||||
def extract_amount_value(amount_data, unit_type)
|
||||
unit = extract_attribute(amount_data, unit_type)
|
||||
return 0 unless unit
|
||||
|
||||
value = extract_attribute(unit, :value)
|
||||
value.to_i
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
class Enterprise::Billing::V2::BaseService
|
||||
attr_reader :account
|
||||
|
||||
def initialize(account:)
|
||||
@account = account
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def stripe_client
|
||||
@stripe_client ||= Stripe::StripeClient.new(
|
||||
api_key: ENV.fetch('STRIPE_SECRET_KEY', nil)
|
||||
)
|
||||
end
|
||||
|
||||
def response_monthly_credits
|
||||
account.limits&.[]('captain_responses_monthly').to_i
|
||||
end
|
||||
|
||||
def response_topup_credits
|
||||
account.limits&.[]('captain_responses_topup').to_i
|
||||
end
|
||||
|
||||
def response_usage
|
||||
account.custom_attributes&.[]('captain_responses_usage').to_i
|
||||
end
|
||||
|
||||
# Update response credits (monthly/topup with auto-calculation of total)
|
||||
def update_response_credits(monthly: nil, topup: nil)
|
||||
# Calculate and update total in limits hash ONLY
|
||||
return unless monthly || topup
|
||||
|
||||
new_monthly = monthly || response_monthly_credits
|
||||
new_topup = topup || response_topup_credits
|
||||
total_credits = new_monthly + new_topup
|
||||
limits = {
|
||||
'captain_responses_monthly' => new_monthly,
|
||||
'captain_responses_topup' => new_topup,
|
||||
'captain_responses' => total_credits
|
||||
}
|
||||
update_limits(limits)
|
||||
end
|
||||
|
||||
def update_limits(updates)
|
||||
return if updates.blank?
|
||||
|
||||
current_limits = account.limits.present? ? account.limits.deep_dup : {}
|
||||
updates.each do |key, value|
|
||||
current_limits[key.to_s] = value
|
||||
end
|
||||
|
||||
account.update!(limits: current_limits)
|
||||
end
|
||||
|
||||
def update_custom_attributes(updates)
|
||||
return if updates.blank?
|
||||
|
||||
current_attributes = account.custom_attributes.present? ? account.custom_attributes.deep_dup : {}
|
||||
updates.each do |key, value|
|
||||
current_attributes[key.to_s] = value
|
||||
end
|
||||
|
||||
account.update!(custom_attributes: current_attributes)
|
||||
end
|
||||
|
||||
def custom_attribute(key)
|
||||
account.custom_attributes&.[](key.to_s)
|
||||
end
|
||||
|
||||
def with_locked_account(&)
|
||||
account.with_lock(&)
|
||||
end
|
||||
|
||||
# Convenient accessors for common attributes
|
||||
def stripe_customer_id
|
||||
custom_attribute('stripe_customer_id')
|
||||
end
|
||||
|
||||
def stripe_subscription_id
|
||||
custom_attribute('stripe_subscription_id')
|
||||
end
|
||||
|
||||
def pricing_plan_id
|
||||
custom_attribute('stripe_pricing_plan_id')
|
||||
end
|
||||
|
||||
def subscribed_quantity
|
||||
custom_attribute('subscribed_quantity').to_i
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,60 @@
|
||||
class Enterprise::Billing::V2::CancelSubscriptionService < Enterprise::Billing::V2::BaseService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
include Enterprise::Billing::Concerns::BillingIntentWorkflow
|
||||
include Enterprise::Billing::Concerns::SubscriptionDataManager
|
||||
|
||||
# Cancel subscription using Stripe's V2 Billing Intent API
|
||||
# Creates a deactivate billing intent for the pricing plan subscription
|
||||
# Subscription remains active until the end of the current billing period
|
||||
#
|
||||
# @return [Hash] { success:, cancel_at_period_end:, period_end:, message: }
|
||||
#
|
||||
def cancel_subscription
|
||||
with_locked_account do
|
||||
metadata = fetch_subscription_metadata
|
||||
intent_params = build_deactivate_params(metadata[:subscription_id], metadata[:cadence_id])
|
||||
execute_billing_intent(intent_params)
|
||||
update_account_status(metadata[:next_billing_date])
|
||||
build_success_response
|
||||
end
|
||||
rescue Stripe::StripeError => e
|
||||
{ success: false, message: "Stripe error: #{e.message}" }
|
||||
rescue StandardError => e
|
||||
{ success: false, message: "Cancellation error: #{e.message}" }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_deactivate_params(subscription_id, cadence_id)
|
||||
{
|
||||
cadence: cadence_id,
|
||||
currency: 'usd',
|
||||
actions: [{
|
||||
type: 'deactivate',
|
||||
deactivate: {
|
||||
type: 'pricing_plan_subscription_details',
|
||||
pricing_plan_subscription_details: { pricing_plan_subscription: subscription_id }
|
||||
}
|
||||
}]
|
||||
}
|
||||
end
|
||||
|
||||
def update_account_status(next_billing_date)
|
||||
# Mark subscription as cancelling (will be cancelled at period end)
|
||||
# Store next_billing_date so the UI can show when the subscription ends
|
||||
update_custom_attributes({
|
||||
'subscription_status' => 'cancel_at_period_end',
|
||||
'subscription_cancelled_at' => Time.current.iso8601,
|
||||
'subscription_ends_at' => next_billing_date
|
||||
})
|
||||
end
|
||||
|
||||
def build_success_response
|
||||
{
|
||||
success: true,
|
||||
cancel_at_period_end: true,
|
||||
message: 'Subscription cancellation initiated. It will be deactivated at the end of the current billing period.'
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,142 @@
|
||||
class Enterprise::Billing::V2::ChangePlanService < Enterprise::Billing::V2::BaseService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
include Enterprise::Billing::Concerns::ProrationLineItemBuilder
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
include Enterprise::Billing::Concerns::PlanProvisioningHelper
|
||||
include Enterprise::Billing::Concerns::BillingIntentWorkflow
|
||||
include Enterprise::Billing::Concerns::SubscriptionDataManager
|
||||
include Enterprise::Billing::Concerns::PlanDataHelper
|
||||
|
||||
def change_plan(new_pricing_plan_id: nil, quantity: nil)
|
||||
validation_error = validate_parameters(new_pricing_plan_id, quantity)
|
||||
return validation_error if validation_error
|
||||
|
||||
with_locked_account do
|
||||
perform_subscription_change(new_pricing_plan_id, quantity)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_parameters(new_pricing_plan_id, quantity)
|
||||
return { success: false, message: 'Must specify either new_pricing_plan_id or quantity' } if new_pricing_plan_id.nil? && quantity.nil?
|
||||
return { success: false, message: 'Invalid quantity' } if !quantity.nil? && !quantity.positive?
|
||||
|
||||
# Validate customer has a default payment method using common service
|
||||
payment_service = Enterprise::Billing::V2::InvoicePaymentService.new(account: account)
|
||||
payment_method_validation = payment_service.validate_payment_method
|
||||
return payment_method_validation unless payment_method_validation.nil?
|
||||
|
||||
nil
|
||||
end
|
||||
|
||||
def perform_subscription_change(new_pricing_plan_id, quantity)
|
||||
change_context = build_change_context(new_pricing_plan_id, quantity)
|
||||
return no_change_response(change_context) unless change_required?(change_context)
|
||||
|
||||
execute_change(change_context)
|
||||
end
|
||||
|
||||
def build_change_context(new_pricing_plan_id, quantity)
|
||||
old_plan_id = pricing_plan_id
|
||||
old_quantity = subscribed_quantity
|
||||
target_plan_id = new_pricing_plan_id || old_plan_id
|
||||
target_quantity = quantity || old_quantity
|
||||
|
||||
{
|
||||
old_plan_id: old_plan_id,
|
||||
old_quantity: old_quantity,
|
||||
target_plan_id: target_plan_id,
|
||||
target_quantity: target_quantity,
|
||||
plan_changed: old_plan_id != target_plan_id,
|
||||
seats_changed: old_quantity != target_quantity
|
||||
}
|
||||
end
|
||||
|
||||
def change_required?(context)
|
||||
context[:plan_changed] || context[:seats_changed]
|
||||
end
|
||||
|
||||
def no_change_response(context)
|
||||
plan_name = plan_display_name(context[:target_plan_id])
|
||||
{ success: false, message: "Subscription already has plan #{plan_name} with #{context[:target_quantity]} seat(s)" }
|
||||
end
|
||||
|
||||
def execute_change(context)
|
||||
# Create and execute billing intent to update the Stripe subscription
|
||||
intent_params = build_change_plan_params(context[:target_plan_id], context[:target_quantity])
|
||||
execute_billing_intent(intent_params)
|
||||
|
||||
next_billing_date = custom_attribute('next_billing_date')
|
||||
proration_data = calculate_proration(
|
||||
old_plan_id: context[:old_plan_id],
|
||||
new_plan_id: context[:target_plan_id],
|
||||
old_quantity: context[:old_quantity],
|
||||
new_quantity: context[:target_quantity],
|
||||
next_billing_date: next_billing_date
|
||||
)
|
||||
line_items = build_proration_line_items(context, proration_data)
|
||||
create_and_charge_invoice(line_items)
|
||||
|
||||
update_account_plan(context[:target_plan_id], context[:target_quantity], next_billing_date)
|
||||
provision_new_plan(context[:target_plan_id]) if context[:plan_changed]
|
||||
|
||||
{ success: true, message: 'Plan change successful' }
|
||||
end
|
||||
|
||||
def build_change_plan_params(new_pricing_plan_id, quantity)
|
||||
metadata = fetch_subscription_metadata
|
||||
plan_version = fetch_plan_version(new_pricing_plan_id)
|
||||
lookup_key = fetch_plan_lookup_key(new_pricing_plan_id)
|
||||
|
||||
{
|
||||
cadence: metadata[:cadence_id],
|
||||
currency: 'usd',
|
||||
actions: [build_modify_action(metadata[:subscription_id], new_pricing_plan_id, plan_version, lookup_key, quantity)]
|
||||
}
|
||||
end
|
||||
|
||||
def build_modify_action(subscription_id, plan_id, plan_version, lookup_key, quantity)
|
||||
{
|
||||
type: 'modify',
|
||||
modify: {
|
||||
type: 'pricing_plan_subscription_details',
|
||||
pricing_plan_subscription_details: {
|
||||
pricing_plan_subscription: subscription_id,
|
||||
new_pricing_plan: plan_id,
|
||||
new_pricing_plan_version: plan_version,
|
||||
component_configurations: [{ lookup_key: lookup_key, quantity: quantity }]
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def calculate_proration(old_plan_id:, new_plan_id:, old_quantity:, new_quantity:, next_billing_date:)
|
||||
old_plan_price = Enterprise::Billing::V2::PlanCatalog.definition_for(old_plan_id)&.dig(:base_fee) || 0.0
|
||||
new_plan_price = Enterprise::Billing::V2::PlanCatalog.definition_for(new_plan_id)&.dig(:base_fee) || 0.0
|
||||
|
||||
Enterprise::Billing::V2::ProrationCalculator.calculate(
|
||||
old_plan_price: old_plan_price,
|
||||
new_plan_price: new_plan_price,
|
||||
old_quantity: old_quantity,
|
||||
new_quantity: new_quantity,
|
||||
next_billing_date: next_billing_date
|
||||
)
|
||||
end
|
||||
|
||||
def create_and_charge_invoice(line_items)
|
||||
# Return success with no invoice if no line items (negligible proration)
|
||||
return { success: true, amount: 0.0, message: 'No charges due to negligible proration' } if line_items.empty?
|
||||
|
||||
# Use common invoice payment service
|
||||
payment_service = Enterprise::Billing::V2::InvoicePaymentService.new(account: account)
|
||||
payment_service.create_and_pay_invoice(
|
||||
line_items: line_items,
|
||||
description: 'Proration charges for plan/seat changes',
|
||||
metadata: {
|
||||
account_id: account.id.to_s,
|
||||
type: 'proration'
|
||||
}
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,85 @@
|
||||
class Enterprise::Billing::V2::CheckoutSessionService < Enterprise::Billing::V2::BaseService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
|
||||
def create_subscription_checkout(pricing_plan_id:, quantity: 1)
|
||||
@pricing_plan_id = pricing_plan_id
|
||||
@quantity = quantity.to_i.positive? ? quantity.to_i : 1
|
||||
|
||||
base_url = ENV.fetch('FRONTEND_URL')
|
||||
@success_url = "#{base_url}/app/accounts/#{@account.id}/settings/billing?session_id={CHECKOUT_SESSION_ID}"
|
||||
@cancel_url = "#{base_url}/app/accounts/#{@account.id}/settings/billing"
|
||||
|
||||
validate_params
|
||||
store_pending_subscription_quantity
|
||||
session = create_checkout_session(checkout_session_params)
|
||||
{ success: true, redirect_url: session.url }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_params
|
||||
raise StandardError, 'Customer ID required. Please create a Stripe customer first.' if stripe_customer_id.blank?
|
||||
end
|
||||
|
||||
def store_pending_subscription_quantity
|
||||
# Store quantity in custom_attributes for webhook to use
|
||||
# This is more reliable than extracting from subscription component_values
|
||||
update_custom_attributes({
|
||||
'pending_subscription_quantity' => @quantity,
|
||||
'pending_subscription_pricing_plan' => @pricing_plan_id
|
||||
})
|
||||
end
|
||||
|
||||
def checkout_session_params
|
||||
{
|
||||
customer: stripe_customer_id,
|
||||
checkout_items: build_checkout_items,
|
||||
automatic_tax: {
|
||||
enabled: true
|
||||
},
|
||||
customer_update: {
|
||||
address: 'auto',
|
||||
shipping: 'auto'
|
||||
},
|
||||
success_url: @success_url,
|
||||
cancel_url: @cancel_url,
|
||||
metadata: session_metadata
|
||||
}
|
||||
end
|
||||
|
||||
def build_checkout_items
|
||||
lookup_key = extract_license_lookup_key
|
||||
raise StandardError, "Lookup key not found for pricing plan #{@pricing_plan_id}" unless lookup_key
|
||||
|
||||
[
|
||||
{
|
||||
type: 'pricing_plan_subscription_item',
|
||||
pricing_plan_subscription_item: {
|
||||
pricing_plan: @pricing_plan_id,
|
||||
component_configurations: {
|
||||
lookup_key => {
|
||||
type: 'license_fee_component',
|
||||
license_fee_component: {
|
||||
quantity: @quantity
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
end
|
||||
|
||||
def extract_license_lookup_key
|
||||
Enterprise::Billing::V2::PlanCatalog.lookup_key_for_plan(@pricing_plan_id)
|
||||
end
|
||||
|
||||
def session_metadata
|
||||
{
|
||||
account_id: account.id,
|
||||
pricing_plan_id: @pricing_plan_id,
|
||||
quantity: @quantity,
|
||||
billing_version: 'v2'
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
class Enterprise::Billing::V2::CreditManagementService < Enterprise::Billing::V2::BaseService
|
||||
# Sync monthly response credits (resets on billing cycle with topup preservation)
|
||||
def sync_monthly_response_credits(amount)
|
||||
with_locked_account do
|
||||
# Preserve topup credits but cap at remaining balance
|
||||
preserved_topup = preserve_topup_on_reset(
|
||||
current_topup: response_topup_credits,
|
||||
new_monthly: amount,
|
||||
current_usage: response_usage
|
||||
)
|
||||
update_response_credits(monthly: amount, topup: preserved_topup)
|
||||
end
|
||||
end
|
||||
|
||||
# Add topup credits for responses
|
||||
def add_response_topup_credits(amount)
|
||||
with_locked_account do
|
||||
new_topup = response_topup_credits + amount
|
||||
update_response_credits(topup: new_topup)
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_credit_grants
|
||||
return [] if stripe_customer_id.blank?
|
||||
|
||||
response = Stripe::Billing::CreditGrant.list(
|
||||
{ customer: stripe_customer_id, limit: 100 }
|
||||
)
|
||||
|
||||
grants = response.data.map do |grant|
|
||||
transform_credit_grant(grant)
|
||||
end
|
||||
grants.reject { |grant| grant[:credits].zero? }
|
||||
rescue Stripe::StripeError => e
|
||||
Rails.logger.error("Failed to fetch credit grants: #{e.message}")
|
||||
[]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Preserve topup credits on monthly reset, capped at remaining balance
|
||||
# Formula: min(current_topup, max(0, (new_monthly + current_topup) - current_usage))
|
||||
def preserve_topup_on_reset(current_topup:, new_monthly:, current_usage:)
|
||||
# Calculate remaining balance after usage
|
||||
total_after_sync = new_monthly + current_topup
|
||||
remaining_balance = [total_after_sync - current_usage, 0].max
|
||||
|
||||
# Cap topup at remaining balance to avoid over-crediting
|
||||
[current_topup, remaining_balance].min
|
||||
end
|
||||
|
||||
def transform_credit_grant(grant)
|
||||
category = grant_attribute(grant, :category)
|
||||
metadata = grant_attribute(grant, :metadata) || {}
|
||||
|
||||
{
|
||||
id: grant_attribute(grant, :id),
|
||||
name: grant_attribute(grant, :name),
|
||||
credits: calculate_grant_credits(category, metadata),
|
||||
category: category,
|
||||
source: metadata['source'] || category,
|
||||
effective_at: parse_timestamp(grant_attribute(grant, :effective_at)),
|
||||
expires_at: parse_timestamp(grant_attribute(grant, :expires_at)),
|
||||
voided_at: parse_timestamp(grant_attribute(grant, :voided_at)),
|
||||
created_at: parse_timestamp(grant_attribute(grant, :created))
|
||||
}
|
||||
end
|
||||
|
||||
def grant_attribute(grant, key)
|
||||
grant[key] || grant.public_send(key)
|
||||
end
|
||||
|
||||
def calculate_grant_credits(category, metadata)
|
||||
return metadata['credits'].to_i if category == 'paid' && metadata['credits']
|
||||
|
||||
0
|
||||
end
|
||||
|
||||
def parse_timestamp(timestamp)
|
||||
return nil unless timestamp
|
||||
|
||||
Time.zone.at(timestamp)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,104 @@
|
||||
class Enterprise::Billing::V2::InvoicePaymentService < Enterprise::Billing::V2::BaseService
|
||||
# Common service for creating invoices with line items and charging immediately
|
||||
# Used by both TopupService and ChangePlanService
|
||||
#
|
||||
# @param line_items [Array<Hash>] Array of line items: [{ amount:, description:, metadata: }]
|
||||
# @param description [String] Description for the invoice
|
||||
# @param currency [String] Currency code (default: 'usd')
|
||||
# @param metadata [Hash] Metadata for the invoice
|
||||
# @return [Hash] { success:, invoice_id:, invoice_url:, amount:, status: }
|
||||
|
||||
# Validate that customer has a default payment method
|
||||
# @return [Hash, nil] Returns error hash if validation fails, nil if success
|
||||
def validate_payment_method
|
||||
return { success: false, message: 'No Stripe customer ID found' } if stripe_customer_id.blank?
|
||||
|
||||
customer = Stripe::Customer.retrieve(stripe_customer_id)
|
||||
|
||||
if customer.invoice_settings.default_payment_method.nil? && customer.default_source.nil?
|
||||
return {
|
||||
success: false,
|
||||
message: 'No default payment method found. Please add a default payment method before making a purchase.'
|
||||
}
|
||||
end
|
||||
|
||||
nil
|
||||
rescue Stripe::StripeError => e
|
||||
Rails.logger.error("Failed to check payment method: #{e.message}")
|
||||
{ success: false, message: "Error validating payment method: #{e.message}" }
|
||||
end
|
||||
|
||||
# Create invoice with line items and charge immediately
|
||||
#
|
||||
# @param line_items [Array<Hash>] Line items: [{ amount: (cents), description:, metadata: }]
|
||||
# @param description [String] Invoice description
|
||||
# @param currency [String] Currency (default: 'usd')
|
||||
# @param metadata [Hash] Invoice metadata
|
||||
# @return [Hash] { success:, invoice_id:, invoice_url:, amount:, status: }
|
||||
def create_and_pay_invoice(line_items:, description:, currency: 'usd', metadata: {})
|
||||
invoice = create_invoice(stripe_customer_id, currency, description, metadata)
|
||||
add_line_items_to_invoice(invoice.id, stripe_customer_id, line_items, currency)
|
||||
finalize_and_pay_invoice(invoice.id)
|
||||
rescue Stripe::StripeError => e
|
||||
Rails.logger.error("Error creating invoice: #{e.message}")
|
||||
{ success: false, message: "Error creating invoice: #{e.message}" }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def create_invoice(customer_id, currency, description, metadata)
|
||||
Stripe::Invoice.create({
|
||||
customer: customer_id,
|
||||
currency: currency,
|
||||
collection_method: 'charge_automatically',
|
||||
auto_advance: false,
|
||||
description: description,
|
||||
metadata: metadata.stringify_keys
|
||||
})
|
||||
end
|
||||
|
||||
def add_line_items_to_invoice(invoice_id, customer_id, line_items, currency)
|
||||
line_items.each do |item|
|
||||
Stripe::InvoiceItem.create({
|
||||
customer: customer_id,
|
||||
amount: item[:amount],
|
||||
currency: currency,
|
||||
invoice: invoice_id,
|
||||
description: item[:description],
|
||||
metadata: (item[:metadata] || {}).stringify_keys
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
# Finalize invoice and pay it immediately
|
||||
# @param invoice_id [String] Stripe invoice ID
|
||||
# @return [Hash] { success:, invoice_id:, invoice_url:, amount:, status: }
|
||||
def finalize_and_pay_invoice(invoice_id)
|
||||
# Finalize the invoice
|
||||
finalized_invoice = Stripe::Invoice.finalize_invoice(
|
||||
invoice_id,
|
||||
{ auto_advance: false }
|
||||
)
|
||||
|
||||
# Pay the invoice immediately if not already paid
|
||||
if finalized_invoice.status == 'paid'
|
||||
build_invoice_response(finalized_invoice)
|
||||
else
|
||||
paid_invoice = Stripe::Invoice.pay(invoice_id, {})
|
||||
build_invoice_response(paid_invoice)
|
||||
end
|
||||
rescue Stripe::StripeError => e
|
||||
Rails.logger.error("Error finalizing/paying invoice: #{e.message}")
|
||||
{ success: false, message: "Error processing payment: #{e.message}" }
|
||||
end
|
||||
|
||||
def build_invoice_response(invoice)
|
||||
{
|
||||
success: true,
|
||||
invoice_id: invoice.id,
|
||||
invoice_url: invoice.hosted_invoice_url,
|
||||
amount: invoice.total / 100.0,
|
||||
status: invoice.status
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,112 @@
|
||||
module Enterprise::Billing::V2::PlanCatalog
|
||||
DEFAULT_CURRENCY = 'usd'.freeze
|
||||
CREDIT_UNIT = 'Credits'.freeze
|
||||
|
||||
PLAN_DEFINITIONS = [
|
||||
{
|
||||
key: :free,
|
||||
display_name: 'Chatwoot Hacker',
|
||||
base_fee: 0.0,
|
||||
monthly_credits: 0,
|
||||
config_key: 'STRIPE_HACKER_PLAN_ID',
|
||||
licensed_item_lookup_key: 'chatwoot_hacker_license_fee_v2'
|
||||
},
|
||||
{
|
||||
key: :startup,
|
||||
display_name: 'Chatwoot Startup',
|
||||
base_fee: 19.0,
|
||||
monthly_credits: 300,
|
||||
config_key: 'STRIPE_STARTUP_PLAN_ID',
|
||||
licensed_item_lookup_key: 'chatwoot_startup_license_fee_v2'
|
||||
},
|
||||
{
|
||||
key: :business,
|
||||
display_name: 'Chatwoot Business',
|
||||
base_fee: 39.0,
|
||||
monthly_credits: 500,
|
||||
config_key: 'STRIPE_BUSINESS_PLAN_ID',
|
||||
licensed_item_lookup_key: 'chatwoot_business_license_fee_v2'
|
||||
},
|
||||
{
|
||||
key: :enterprise,
|
||||
display_name: 'Chatwoot Enterprise',
|
||||
base_fee: 99.0,
|
||||
monthly_credits: 800,
|
||||
config_key: 'STRIPE_ENTERPRISE_PLAN_ID',
|
||||
licensed_item_lookup_key: 'chatwoot_enterprise_license_fee_v2'
|
||||
}
|
||||
].freeze
|
||||
|
||||
module_function
|
||||
|
||||
def plans
|
||||
PLAN_DEFINITIONS.map do |definition|
|
||||
plan_id = plan_id_for(definition)
|
||||
build_plan(definition, plan_id)
|
||||
end
|
||||
end
|
||||
|
||||
def definition_for(plan_id)
|
||||
PLAN_DEFINITIONS.each do |definition|
|
||||
return definition if plan_id_for(definition) == plan_id
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
def monthly_credits_for(plan_id)
|
||||
definition = definition_for(plan_id)
|
||||
definition ? definition[:monthly_credits] : nil
|
||||
end
|
||||
|
||||
def plan_id_for(definition)
|
||||
InstallationConfig.find_by(name: definition[:config_key])&.value
|
||||
end
|
||||
|
||||
def lookup_key_for_plan(plan_id)
|
||||
# Returns the licensed_item_lookup_key for checkout sessions
|
||||
definition = definition_for(plan_id)
|
||||
definition&.dig(:licensed_item_lookup_key)
|
||||
end
|
||||
|
||||
def build_plan(definition, plan_id)
|
||||
{
|
||||
id: plan_id,
|
||||
display_name: definition[:display_name],
|
||||
currency: DEFAULT_CURRENCY,
|
||||
tax_behavior: 'exclusive',
|
||||
components: build_components(definition)
|
||||
}
|
||||
end
|
||||
|
||||
def build_components(definition)
|
||||
components = [service_action_component(definition), rate_card_component(definition)]
|
||||
components << license_fee_component(definition) if definition[:base_fee]&.positive?
|
||||
components
|
||||
end
|
||||
|
||||
def service_action_component(definition)
|
||||
{
|
||||
type: 'service_action',
|
||||
name: 'Monthly Credits',
|
||||
credit_amount: definition[:monthly_credits],
|
||||
credit_unit: CREDIT_UNIT
|
||||
}
|
||||
end
|
||||
|
||||
def rate_card_component(_definition)
|
||||
{
|
||||
type: 'rate_card',
|
||||
name: 'Overage Rate',
|
||||
rate_unit: CREDIT_UNIT,
|
||||
meter_id: nil
|
||||
}
|
||||
end
|
||||
|
||||
def license_fee_component(definition)
|
||||
{
|
||||
type: 'license_fee',
|
||||
name: 'Base Fee',
|
||||
unit_amount: definition[:base_fee].round(2)
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,99 @@
|
||||
# rubocop:disable Style/ClassAndModuleChildren
|
||||
module Enterprise
|
||||
module Billing
|
||||
module V2
|
||||
class ProrationCalculator
|
||||
# Calculate prorated amounts for subscription changes
|
||||
#
|
||||
# @param old_plan_price [Float] Price per unit of the old plan
|
||||
# @param new_plan_price [Float] Price per unit of the new plan
|
||||
# @param old_quantity [Integer] Old quantity/seats
|
||||
# @param new_quantity [Integer] New quantity/seats
|
||||
# @param next_billing_date [String/Time] Next billing date (ISO 8601)
|
||||
# @return [Hash] { credit_amount:, charge_amount:, net_amount:, days_remaining:, total_days: }
|
||||
#
|
||||
def self.calculate(old_plan_price:, new_plan_price:, old_quantity:, new_quantity:, next_billing_date:)
|
||||
new(
|
||||
old_plan_price: old_plan_price,
|
||||
new_plan_price: new_plan_price,
|
||||
old_quantity: old_quantity,
|
||||
new_quantity: new_quantity,
|
||||
next_billing_date: next_billing_date
|
||||
).calculate
|
||||
end
|
||||
|
||||
def initialize(old_plan_price:, new_plan_price:, old_quantity:, new_quantity:, next_billing_date:)
|
||||
@old_plan_price = old_plan_price.to_f
|
||||
@new_plan_price = new_plan_price.to_f
|
||||
@old_quantity = old_quantity.to_i
|
||||
@new_quantity = new_quantity.to_i
|
||||
@next_billing_date = parse_date(next_billing_date)
|
||||
@current_date = Time.zone.now
|
||||
end
|
||||
|
||||
def calculate
|
||||
{
|
||||
credit_amount: credit_amount,
|
||||
charge_amount: charge_amount,
|
||||
net_amount: net_amount,
|
||||
days_remaining: days_remaining,
|
||||
total_days: total_days,
|
||||
proration_factor: proration_factor
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def parse_date(date)
|
||||
return date if date.is_a?(Time) || date.is_a?(DateTime)
|
||||
|
||||
Time.zone.parse(date.to_s)
|
||||
rescue StandardError
|
||||
raise ArgumentError, "Invalid next_billing_date format: #{date}"
|
||||
end
|
||||
|
||||
# Credit from unused time on old plan
|
||||
def credit_amount
|
||||
@credit_amount ||= (@old_plan_price * @old_quantity * proration_factor).round(2)
|
||||
end
|
||||
|
||||
# Charge for new plan for remaining time
|
||||
def charge_amount
|
||||
@charge_amount ||= (@new_plan_price * @new_quantity * proration_factor).round(2)
|
||||
end
|
||||
|
||||
# Net amount to charge (positive) or credit (negative)
|
||||
def net_amount
|
||||
@net_amount ||= (charge_amount - credit_amount).round(2)
|
||||
end
|
||||
|
||||
# Number of days remaining in current billing period
|
||||
def days_remaining
|
||||
@days_remaining ||= (@next_billing_date.to_date - @current_date.to_date).to_i
|
||||
end
|
||||
|
||||
# Total days in the actual billing period (calculate from current cycle)
|
||||
# This ensures proration factor never exceeds 1.0
|
||||
def total_days
|
||||
@total_days ||= begin
|
||||
# Calculate the total days in this billing cycle
|
||||
# Assume billing started one month ago from next_billing_date
|
||||
billing_start = @next_billing_date - 1.month
|
||||
((@next_billing_date.to_date - billing_start.to_date).to_i)
|
||||
end
|
||||
end
|
||||
|
||||
# Fraction of billing period remaining
|
||||
# This value should always be between 0.0 and 1.0
|
||||
def proration_factor
|
||||
@proration_factor ||= begin
|
||||
factor = days_remaining.to_f / total_days
|
||||
# Ensure factor never exceeds 1.0
|
||||
[factor, 1.0].min.round(4)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
# rubocop:enable Style/ClassAndModuleChildren
|
||||
@@ -0,0 +1,116 @@
|
||||
class Enterprise::Billing::V2::SubscriptionProvisioningService < Enterprise::Billing::V2::BaseService
|
||||
include Enterprise::Billing::Concerns::PlanFeatureManager
|
||||
include Enterprise::Billing::Concerns::PlanProvisioningHelper
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
|
||||
def provision(subscription_id:)
|
||||
process_subscription(subscription_id)
|
||||
end
|
||||
|
||||
def refresh
|
||||
return if stripe_subscription_id.blank?
|
||||
|
||||
process_subscription(stripe_subscription_id)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def process_subscription(subscription_id)
|
||||
# Retrieve pricing plan subscription details from Stripe V2 API
|
||||
subscription = retrieve_pricing_plan_subscription(subscription_id)
|
||||
|
||||
# Check if subscription is canceled
|
||||
if servicing_status(subscription) == 'canceled'
|
||||
cancel_subscription
|
||||
reset_captain_usage
|
||||
return { pricing_plan_id: nil, quantity: nil }
|
||||
end
|
||||
|
||||
# Extract details from the subscription
|
||||
pricing_plan_id = extract_pricing_plan_id(subscription)
|
||||
quantity = extract_subscription_quantity(subscription)
|
||||
billing_cadence = extract_billing_cadence(subscription)
|
||||
|
||||
# Update account with subscription details
|
||||
update_subscription_details(subscription_id, pricing_plan_id, quantity, billing_cadence)
|
||||
|
||||
# Provision the subscription: sync credits and enable features
|
||||
provision_new_plan(pricing_plan_id) if pricing_plan_id.present?
|
||||
|
||||
# Reset usage for the new billing cycle
|
||||
reset_captain_usage
|
||||
|
||||
{ pricing_plan_id: pricing_plan_id, quantity: quantity }
|
||||
end
|
||||
|
||||
def servicing_status(subscription_plan)
|
||||
extract_attribute(subscription_plan, :servicing_status)
|
||||
end
|
||||
|
||||
def cancel_subscription
|
||||
hacker_plan_config = InstallationConfig.find_by(name: 'STRIPE_HACKER_PLAN_ID')
|
||||
pricing_plan_id = hacker_plan_config.value
|
||||
|
||||
# Update subscription status and plan details
|
||||
attributes = {
|
||||
'plan_name': 'Hacker',
|
||||
'stripe_pricing_plan_id': pricing_plan_id,
|
||||
'subscribed_quantity': 2,
|
||||
'stripe_subscription_id': nil,
|
||||
'billing_cadence': nil,
|
||||
'subscription_status': 'canceled'
|
||||
}
|
||||
update_custom_attributes(attributes)
|
||||
|
||||
# Sync credits for Hacker plan (0 credits)
|
||||
sync_plan_credits(pricing_plan_id)
|
||||
|
||||
# Disable all premium features and save
|
||||
disable_all_premium_features
|
||||
account.save!
|
||||
end
|
||||
|
||||
def extract_pricing_plan_id(subscription)
|
||||
extract_attribute(subscription, :pricing_plan)
|
||||
end
|
||||
|
||||
def extract_billing_cadence(subscription)
|
||||
extract_attribute(subscription, :billing_cadence)
|
||||
end
|
||||
|
||||
def extract_subscription_quantity(_subscription)
|
||||
# Get quantity from account custom_attributes (set during checkout)
|
||||
pending_quantity = custom_attribute('pending_subscription_quantity')
|
||||
return pending_quantity.to_i if pending_quantity.present? && pending_quantity.to_i.positive?
|
||||
|
||||
return subscribed_quantity if subscribed_quantity.positive?
|
||||
|
||||
1
|
||||
end
|
||||
|
||||
def update_subscription_details(subscription_id, pricing_plan_id, quantity, billing_cadence)
|
||||
Rails.logger.info "[V2 Billing] Updating subscription details: subscription_id=#{subscription_id}, " \
|
||||
"pricing_plan_id=#{pricing_plan_id}, quantity=#{quantity}"
|
||||
|
||||
attributes = {
|
||||
'stripe_subscription_id' => subscription_id,
|
||||
'subscribed_quantity' => quantity,
|
||||
'subscription_status' => 'active',
|
||||
'pending_subscription_quantity' => nil,
|
||||
'pending_subscription_pricing_plan' => nil,
|
||||
'billing_cadence' => billing_cadence,
|
||||
'next_billing_date' => nil,
|
||||
'pending_stripe_pricing_plan_id' => nil,
|
||||
'stripe_billing_version' => 2
|
||||
}
|
||||
attributes['stripe_pricing_plan_id'] = pricing_plan_id if pricing_plan_id.present?
|
||||
|
||||
# Add plan name from catalog
|
||||
if pricing_plan_id.present?
|
||||
plan_definition = Enterprise::Billing::V2::PlanCatalog.definition_for(pricing_plan_id)
|
||||
attributes['plan_name'] = plan_definition[:display_name] if plan_definition
|
||||
end
|
||||
|
||||
update_custom_attributes(attributes)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
module Enterprise::Billing::V2::TopupCatalog
|
||||
DEFAULT_TOPUPS = [
|
||||
{ credits: 1000, amount: 20.0 },
|
||||
{ credits: 2000, amount: 40.0 },
|
||||
{ credits: 3000, amount: 60.0 },
|
||||
{ credits: 4000, amount: 80.0 }
|
||||
].freeze
|
||||
|
||||
module_function
|
||||
|
||||
def options
|
||||
custom_options = InstallationConfig.find_by(name: 'STRIPE_TOPUP_OPTIONS')&.value
|
||||
parsed = parse_options(custom_options)
|
||||
(parsed.presence || DEFAULT_TOPUPS).sort_by { |opt| opt[:credits] }.map do |option|
|
||||
{
|
||||
credits: option[:credits],
|
||||
amount: option[:amount],
|
||||
currency: option[:currency] || 'usd'
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def parse_options(raw)
|
||||
return [] if raw.blank?
|
||||
|
||||
JSON.parse(raw, symbolize_names: true)
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def find_option(credits)
|
||||
options.find { |option| option[:credits].to_i == credits.to_i }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,145 @@
|
||||
class Enterprise::Billing::V2::TopupService < Enterprise::Billing::V2::BaseService
|
||||
def create_topup(credits:)
|
||||
validation_result = validate_topup_request(credits)
|
||||
return validation_result unless validation_result[:valid]
|
||||
|
||||
topup_definition = validation_result[:topup_definition]
|
||||
amount_cents = (topup_definition[:amount] * 100).to_i
|
||||
currency = topup_definition[:currency] || 'usd'
|
||||
|
||||
with_locked_account do
|
||||
process_topup_transaction(credits, amount_cents, currency, topup_definition[:amount])
|
||||
end
|
||||
rescue Stripe::StripeError => e
|
||||
{ success: false, message: "Stripe error: #{e.message}" }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_topup_request(credits)
|
||||
return { valid: false, success: false, message: 'Invalid topup amount' } unless credits.to_i.positive?
|
||||
|
||||
plan_validation = validate_subscription_plan
|
||||
return plan_validation unless plan_validation[:valid]
|
||||
|
||||
topup_definition = Enterprise::Billing::V2::TopupCatalog.find_option(credits)
|
||||
return { valid: false, success: false, message: 'Unsupported topup amount' } unless topup_definition
|
||||
return { valid: false, success: false, message: 'Stripe customer not configured' } if stripe_customer_id.blank?
|
||||
|
||||
payment_service = Enterprise::Billing::V2::InvoicePaymentService.new(account: account)
|
||||
payment_method_validation = payment_service.validate_payment_method
|
||||
return payment_method_validation.merge(valid: false) if payment_method_validation
|
||||
|
||||
{ valid: true, topup_definition: topup_definition }
|
||||
end
|
||||
|
||||
def validate_subscription_plan
|
||||
plan_name = custom_attribute('plan_name')
|
||||
|
||||
# Block topup if no plan or on Hacker plan
|
||||
if plan_name.blank? || plan_name.downcase == 'hacker'
|
||||
return {
|
||||
valid: false,
|
||||
success: false,
|
||||
message: 'Top-ups are only available for Startup, Business, and Enterprise plans. Please upgrade your plan to purchase credits.'
|
||||
}
|
||||
end
|
||||
|
||||
{ valid: true }
|
||||
end
|
||||
|
||||
def process_topup_transaction(credits, amount_cents, currency, amount)
|
||||
line_items = build_topup_line_items(credits, amount_cents)
|
||||
invoice_result = charge_topup_invoice(line_items, currency)
|
||||
return invoice_result unless invoice_result[:success]
|
||||
|
||||
credit_grant = create_stripe_credit_grant(amount_cents, currency, credits)
|
||||
return { success: false, message: 'Failed to create credit grant in Stripe' } unless credit_grant
|
||||
|
||||
build_success_response(credits, amount, currency, invoice_result[:invoice_id], credit_grant['id'])
|
||||
end
|
||||
|
||||
def build_topup_line_items(credits, amount_cents)
|
||||
[{
|
||||
amount: amount_cents,
|
||||
description: "Credit Topup: #{credits} credits",
|
||||
metadata: {
|
||||
account_id: account.id.to_s,
|
||||
credits: credits.to_s,
|
||||
topup: 'true'
|
||||
}
|
||||
}]
|
||||
end
|
||||
|
||||
def charge_topup_invoice(line_items, currency)
|
||||
payment_service = Enterprise::Billing::V2::InvoicePaymentService.new(account: account)
|
||||
payment_service.create_and_pay_invoice(
|
||||
line_items: line_items,
|
||||
description: 'Credit top-up purchase',
|
||||
currency: currency,
|
||||
metadata: {
|
||||
account_id: account.id.to_s,
|
||||
topup: 'true'
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
def build_success_response(credits, amount, currency, invoice_id, credit_grant_id)
|
||||
{
|
||||
success: true,
|
||||
message: 'Top-up purchased successfully',
|
||||
credits: credits,
|
||||
amount: amount,
|
||||
currency: currency,
|
||||
invoice_id: invoice_id,
|
||||
credit_grant_id: credit_grant_id
|
||||
}
|
||||
end
|
||||
|
||||
# Create Credit Grant in Stripe using monetary amount (not custom_pricing_unit)
|
||||
# Following Stripe UBB Integration Guide section 8
|
||||
def create_stripe_credit_grant(amount_cents, currency, credits)
|
||||
Stripe::Billing::CreditGrant.create(
|
||||
credit_grant_params(amount_cents, currency, credits)
|
||||
)
|
||||
end
|
||||
|
||||
def credit_grant_params(amount_cents, currency, credits)
|
||||
{
|
||||
customer: stripe_customer_id,
|
||||
name: "Topup: #{credits} credits",
|
||||
amount: credit_grant_amount(amount_cents, currency),
|
||||
applicability_config: credit_grant_applicability,
|
||||
category: 'paid',
|
||||
metadata: credit_grant_metadata(credits)
|
||||
}
|
||||
end
|
||||
|
||||
def credit_grant_amount(amount_cents, currency)
|
||||
{
|
||||
type: 'monetary',
|
||||
monetary: {
|
||||
currency: currency,
|
||||
value: amount_cents
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def credit_grant_applicability
|
||||
# Apply credit grant to all metered usage for this customer
|
||||
# This ensures topup credits offset meter-based billing
|
||||
{
|
||||
scope: {
|
||||
price_type: 'metered'
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def credit_grant_metadata(credits)
|
||||
{
|
||||
account_id: account.id.to_s,
|
||||
source: 'topup',
|
||||
credits: credits.to_s
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,35 @@
|
||||
class Enterprise::Billing::V2::UsageReporterService < Enterprise::Billing::V2::BaseService
|
||||
def report(credits_used, _feature = nil)
|
||||
return { success: false, message: 'Missing Stripe configuration' } unless valid_configuration?
|
||||
|
||||
event = Stripe::Billing::MeterEvent.create(
|
||||
meter_event_params(credits_used),
|
||||
stripe_api_options
|
||||
)
|
||||
|
||||
{ success: true, event_id: event.identifier }
|
||||
rescue Stripe::StripeError => e
|
||||
{ success: false, message: e.message }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def valid_configuration?
|
||||
stripe_customer_id.present?
|
||||
end
|
||||
|
||||
def meter_event_params(credits_used)
|
||||
{
|
||||
event_name: 'chatwoot.usage',
|
||||
payload: {
|
||||
value: credits_used.to_s,
|
||||
stripe_customer_id: stripe_customer_id
|
||||
},
|
||||
identifier: "#{account.id}_#{Time.current.to_i}_#{SecureRandom.hex(4)}"
|
||||
}
|
||||
end
|
||||
|
||||
def stripe_api_options
|
||||
{ api_key: ENV.fetch('STRIPE_SECRET_KEY', nil), stripe_version: '2025-08-27.preview' }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,60 @@
|
||||
class Enterprise::Billing::V2::WebhookHandlerService
|
||||
include Enterprise::Billing::Concerns::StripeV2ClientHelper
|
||||
|
||||
def perform(event:)
|
||||
@event = event
|
||||
return { success: false, message: 'Event is required' } if @event.blank?
|
||||
|
||||
return { success: false, message: 'Account not found' } if account.blank?
|
||||
|
||||
case @event.type
|
||||
when 'v2.billing.pricing_plan_subscription.servicing_activated'
|
||||
Rails.logger.info "Handling subscription servicing activated event: #{@event.related_object.id}"
|
||||
handle_subscription_servicing_activated(@event.related_object.id)
|
||||
when 'v2.billing.cadence.billed'
|
||||
Rails.logger.info "Handling cadence billed event: #{@event.related_object.id}"
|
||||
refresh_account_subscription_details(@event.related_object.id)
|
||||
else
|
||||
{ success: true }
|
||||
end
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "Error processing V2 webhook: #{e.message}"
|
||||
{ success: false, error: e.message }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def account
|
||||
@account ||= begin
|
||||
related_object = @event.related_object
|
||||
subscription_id = related_object.id
|
||||
|
||||
customer_id = fetch_customer_id_from_subscription(subscription_id)
|
||||
found_account = Account.find_by("custom_attributes->>'stripe_customer_id' = ?", customer_id) if customer_id.present?
|
||||
|
||||
Rails.logger.warn "Could not find account for subscription #{subscription_id}" if found_account.blank?
|
||||
|
||||
found_account
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_customer_id_from_subscription(subscription_id)
|
||||
subscription = retrieve_pricing_plan_subscription(subscription_id)
|
||||
return nil unless subscription&.billing_cadence
|
||||
|
||||
cadence = retrieve_billing_cadence(subscription.billing_cadence)
|
||||
cadence.payer&.customer
|
||||
end
|
||||
|
||||
def handle_subscription_servicing_activated(subscription_id)
|
||||
Enterprise::Billing::V2::SubscriptionProvisioningService
|
||||
.new(account: account)
|
||||
.provision(subscription_id: subscription_id)
|
||||
end
|
||||
|
||||
def refresh_account_subscription_details(_cadence_id)
|
||||
Enterprise::Billing::V2::SubscriptionProvisioningService
|
||||
.new(account: account)
|
||||
.refresh
|
||||
end
|
||||
end
|
||||
@@ -205,8 +205,10 @@ RSpec.describe 'Enterprise Billing APIs', type: :request do
|
||||
},
|
||||
'conversation' => {},
|
||||
'captain' => {
|
||||
'documents' => { 'consumed' => 0, 'current_available' => ChatwootApp.max_limit, 'total_count' => ChatwootApp.max_limit },
|
||||
'responses' => { 'consumed' => 0, 'current_available' => ChatwootApp.max_limit, 'total_count' => ChatwootApp.max_limit }
|
||||
'documents' => { 'consumed' => 0, 'current_available' => ChatwootApp.max_limit, 'total_count' => ChatwootApp.max_limit,
|
||||
'monthly' => nil, 'topup' => nil },
|
||||
'responses' => { 'consumed' => 0, 'current_available' => ChatwootApp.max_limit, 'total_count' => ChatwootApp.max_limit,
|
||||
'monthly' => 0, 'topup' => 0 }
|
||||
},
|
||||
'non_web_inboxes' => {}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,34 @@ require 'rails_helper'
|
||||
RSpec.describe 'Enterprise::Webhooks::StripeController', type: :request do
|
||||
describe 'POST /enterprise/webhooks/stripe' do
|
||||
let(:params) { { content: 'hello' } }
|
||||
let(:v1_event_params) { { type: 'invoice.created', data: { object: {} } }.to_json }
|
||||
|
||||
it 'call the Enterprise::Billing::HandleStripeEventService with the params' do
|
||||
handle_stripe = double
|
||||
allow(Stripe::Webhook).to receive(:construct_event).and_return(params)
|
||||
it 'delegates to the v1 handler for legacy events' do
|
||||
handle_stripe = instance_double(Enterprise::Billing::HandleStripeEventService)
|
||||
event = instance_double(Stripe::Event, type: 'invoice.created')
|
||||
|
||||
allow(Stripe::Webhook).to receive(:construct_event).and_return(event)
|
||||
allow(Enterprise::Billing::HandleStripeEventService).to receive(:new).and_return(handle_stripe)
|
||||
allow(handle_stripe).to receive(:perform)
|
||||
post '/enterprise/webhooks/stripe', headers: { 'Stripe-Signature': 'test' }, params: params
|
||||
expect(handle_stripe).to have_received(:perform).with(event: params)
|
||||
|
||||
post '/enterprise/webhooks/stripe', headers: { 'Stripe-Signature': 'test' }, params: v1_event_params, as: :json
|
||||
|
||||
expect(handle_stripe).to have_received(:perform).with(event: event)
|
||||
end
|
||||
|
||||
it 'delegates v2 billing events to the v2 webhook handler' do
|
||||
v2_event_params = { type: 'v2.billing.pricing_plan_subscription.servicing_activated', data: { object: {} } }.to_json
|
||||
event = instance_double(Stripe::Event, type: 'v2.billing.pricing_plan_subscription.servicing_activated')
|
||||
handler_double = instance_double(Enterprise::Billing::V2::WebhookHandlerService, perform: { success: true })
|
||||
|
||||
allow(Stripe::Webhook).to receive(:construct_event).and_return(event)
|
||||
allow(Enterprise::Billing::V2::WebhookHandlerService).to receive(:new).and_return(handler_double)
|
||||
|
||||
post '/enterprise/webhooks/stripe', headers: { 'Stripe-Signature': 'test' }, params: v2_event_params, as: :json
|
||||
|
||||
expect(Enterprise::Billing::V2::WebhookHandlerService).to have_received(:new)
|
||||
expect(handler_double).to have_received(:perform).with(event: event)
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
|
||||
it 'returns a bad request if the headers are missing' do
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe Enterprise::Billing::CreditSyncJob, type: :job do
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
before do
|
||||
allow(ENV).to receive(:fetch).and_call_original
|
||||
allow(ENV).to receive(:fetch).with('STRIPE_SECRET_KEY', nil).and_return('sk_test_123')
|
||||
allow(InstallationConfig).to receive(:find_by).and_call_original
|
||||
allow(InstallationConfig).to receive(:find_by).with(name: 'STRIPE_METER_ID')
|
||||
.and_return(instance_double(InstallationConfig, value: 'mtr_test_123'))
|
||||
end
|
||||
|
||||
describe '#perform' do
|
||||
context 'with no arguments' do
|
||||
let!(:account) do
|
||||
create(:account, custom_attributes: {
|
||||
'stripe_customer_id' => 'cus_123',
|
||||
'stripe_billing_version' => 2,
|
||||
'captain_responses_usage' => 100,
|
||||
'stripe_last_synced_credits' => 50
|
||||
})
|
||||
end
|
||||
|
||||
it 'syncs all accounts with Stripe customer ID' do
|
||||
usage_reporter = instance_double(Enterprise::Billing::V2::UsageReporterService)
|
||||
allow(Enterprise::Billing::V2::UsageReporterService).to receive(:new).and_return(usage_reporter)
|
||||
allow(usage_reporter).to receive(:report).with(50).and_return({ success: true, event_id: 'evt_123' })
|
||||
|
||||
result = described_class.new.perform
|
||||
|
||||
expect(result).to eq({ synced: 1, failed: 0 })
|
||||
expect(account.reload.custom_attributes['stripe_last_synced_credits']).to eq(100)
|
||||
end
|
||||
end
|
||||
|
||||
context 'with account argument' do
|
||||
let(:account) do
|
||||
create(:account, custom_attributes: {
|
||||
'stripe_customer_id' => 'cus_123',
|
||||
'captain_responses_usage' => 100,
|
||||
'stripe_last_synced_credits' => 30
|
||||
})
|
||||
end
|
||||
|
||||
it 'syncs single account' do
|
||||
usage_reporter = instance_double(Enterprise::Billing::V2::UsageReporterService)
|
||||
allow(Enterprise::Billing::V2::UsageReporterService).to receive(:new).and_return(usage_reporter)
|
||||
allow(usage_reporter).to receive(:report).and_return({ success: true, event_id: 'evt_123' })
|
||||
|
||||
result = described_class.new.perform(account)
|
||||
|
||||
expect(result[:success]).to be true
|
||||
expect(result[:credits_reported]).to eq(70)
|
||||
expect(account.reload.custom_attributes['stripe_last_synced_credits']).to eq(100)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -12,7 +12,7 @@ RSpec.describe Enterprise::CreateStripeCustomerJob, type: :job do
|
||||
.on_queue('default')
|
||||
end
|
||||
|
||||
it 'executes perform' do
|
||||
it 'uses V1 customer creation service' do
|
||||
create_stripe_customer_service = double
|
||||
allow(Enterprise::Billing::CreateStripeCustomerService)
|
||||
.to receive(:new)
|
||||
|
||||
+80
-117
@@ -5,137 +5,100 @@ describe Enterprise::Billing::CreateStripeCustomerService do
|
||||
|
||||
let(:account) { create(:account) }
|
||||
let!(:admin1) { create(:user, account: account, role: :administrator) }
|
||||
let(:admin2) { create(:user, account: account, role: :administrator) }
|
||||
let(:subscriptions_list) { double }
|
||||
|
||||
describe '#perform' do
|
||||
before do
|
||||
create(
|
||||
:installation_config,
|
||||
{ name: 'CHATWOOT_CLOUD_PLANS', value: [
|
||||
{ 'name' => 'A Plan Name', 'product_id' => ['prod_hacker_random'], 'price_ids' => ['price_hacker_random'] }
|
||||
] }
|
||||
)
|
||||
context 'when V2 configs are missing' do
|
||||
it 'raises a configuration error' do
|
||||
expect do
|
||||
create_stripe_customer_service.new(account: account).perform
|
||||
end.to raise_error(StandardError, /V2 billing configuration is required/)
|
||||
end
|
||||
end
|
||||
|
||||
it 'does not call stripe methods if customer id is present' do
|
||||
account.update!(custom_attributes: { stripe_customer_id: 'cus_random_number' })
|
||||
allow(subscriptions_list).to receive(:data).and_return([])
|
||||
allow(Stripe::Customer).to receive(:create)
|
||||
allow(Stripe::Subscription).to receive(:list).and_return(subscriptions_list)
|
||||
allow(Stripe::Subscription).to receive(:create)
|
||||
.and_return(
|
||||
{
|
||||
plan: { id: 'price_random_number', product: 'prod_random_number' },
|
||||
quantity: 2
|
||||
}.with_indifferent_access
|
||||
)
|
||||
context 'with V2 billing' do
|
||||
let(:cloud_plans_config) do
|
||||
create(:installation_config,
|
||||
name: 'CHATWOOT_CLOUD_PLANS',
|
||||
value: [
|
||||
{
|
||||
'name' => 'Startup',
|
||||
'price_ids' => ['price_startup_123'],
|
||||
'default_quantity' => 2
|
||||
}
|
||||
])
|
||||
end
|
||||
|
||||
create_stripe_customer_service.new(account: account).perform
|
||||
let(:hacker_plan_config) do
|
||||
create(:installation_config,
|
||||
name: 'STRIPE_HACKER_PLAN_ID',
|
||||
value: 'bpp_hacker_123')
|
||||
end
|
||||
|
||||
expect(Stripe::Customer).not_to have_received(:create)
|
||||
expect(Stripe::Subscription)
|
||||
.to have_received(:create)
|
||||
.with({ customer: 'cus_random_number', items: [{ price: 'price_hacker_random', quantity: 2 }] })
|
||||
before do
|
||||
# Setup configs
|
||||
cloud_plans_config
|
||||
hacker_plan_config
|
||||
end
|
||||
|
||||
expect(account.reload.custom_attributes).to eq(
|
||||
{
|
||||
stripe_customer_id: 'cus_random_number',
|
||||
stripe_price_id: 'price_random_number',
|
||||
stripe_product_id: 'prod_random_number',
|
||||
subscribed_quantity: 2,
|
||||
plan_name: 'A Plan Name'
|
||||
}.with_indifferent_access
|
||||
)
|
||||
end
|
||||
|
||||
it 'calls stripe methods to create a customer and updates the account' do
|
||||
customer = double
|
||||
allow(Stripe::Customer).to receive(:create).and_return(customer)
|
||||
allow(customer).to receive(:id).and_return('cus_random_number')
|
||||
allow(Stripe::Subscription)
|
||||
.to receive(:create)
|
||||
.and_return(
|
||||
{
|
||||
plan: { id: 'price_random_number', product: 'prod_random_number' },
|
||||
quantity: 2
|
||||
}.with_indifferent_access
|
||||
)
|
||||
|
||||
create_stripe_customer_service.new(account: account).perform
|
||||
|
||||
expect(Stripe::Customer).to have_received(:create).with({ name: account.name, email: admin1.email })
|
||||
expect(Stripe::Subscription)
|
||||
.to have_received(:create)
|
||||
.with({ customer: customer.id, items: [{ price: 'price_hacker_random', quantity: 2 }] })
|
||||
|
||||
expect(account.reload.custom_attributes).to eq(
|
||||
{
|
||||
stripe_customer_id: customer.id,
|
||||
stripe_price_id: 'price_random_number',
|
||||
stripe_product_id: 'prod_random_number',
|
||||
subscribed_quantity: 2,
|
||||
plan_name: 'A Plan Name'
|
||||
}.with_indifferent_access
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'when checking for existing subscriptions' do
|
||||
before do
|
||||
create(
|
||||
:installation_config,
|
||||
{ name: 'CHATWOOT_CLOUD_PLANS', value: [
|
||||
{ 'name' => 'A Plan Name', 'product_id' => ['prod_hacker_random'], 'price_ids' => ['price_hacker_random'] }
|
||||
] }
|
||||
)
|
||||
end
|
||||
|
||||
context 'when account has no stripe_customer_id' do
|
||||
it 'creates a new subscription' do
|
||||
it 'creates a stripe customer and sets up V2 billing' do
|
||||
customer = double
|
||||
allow(Stripe::Customer).to receive(:create).and_return(customer)
|
||||
allow(customer).to receive(:id).and_return('cus_random_number')
|
||||
allow(Stripe::Subscription).to receive(:create).and_return(
|
||||
{
|
||||
plan: { id: 'price_random_number', product: 'prod_random_number' },
|
||||
quantity: 2
|
||||
}.with_indifferent_access
|
||||
|
||||
# Mock the plan feature manager
|
||||
service = create_stripe_customer_service.new(account: account)
|
||||
allow(service).to receive(:enable_plan_specific_features)
|
||||
|
||||
service.perform
|
||||
|
||||
expect(Stripe::Customer).to have_received(:create).with({ name: account.name, email: admin1.email })
|
||||
expect(account.reload.custom_attributes).to include(
|
||||
'stripe_customer_id' => 'cus_random_number',
|
||||
'stripe_billing_version' => 2,
|
||||
'stripe_pricing_plan_id' => 'bpp_hacker_123',
|
||||
'plan_name' => 'Hacker',
|
||||
'subscribed_quantity' => 2
|
||||
)
|
||||
expect(service).to have_received(:enable_plan_specific_features).with('Hacker')
|
||||
end
|
||||
|
||||
it 'does not create new customer when customer already exists with V2' do
|
||||
account.update!(custom_attributes: { stripe_customer_id: 'cus_existing_v2' })
|
||||
|
||||
allow(Stripe::Customer).to receive(:create)
|
||||
# Stub the subscription check to return no subscriptions
|
||||
subscriptions_response = OpenStruct.new(data: [])
|
||||
allow(Stripe::Subscription).to receive(:list).and_return(subscriptions_response)
|
||||
|
||||
# Mock the plan feature manager
|
||||
service = create_stripe_customer_service.new(account: account)
|
||||
allow(service).to receive(:enable_plan_specific_features)
|
||||
|
||||
service.perform
|
||||
|
||||
expect(Stripe::Customer).not_to have_received(:create)
|
||||
expect(account.reload.custom_attributes).to include(
|
||||
'stripe_customer_id' => 'cus_existing_v2',
|
||||
'stripe_billing_version' => 2,
|
||||
'stripe_pricing_plan_id' => 'bpp_hacker_123',
|
||||
'plan_name' => 'Hacker',
|
||||
'subscribed_quantity' => 2
|
||||
)
|
||||
end
|
||||
|
||||
it 'skips setup when active subscription exists' do
|
||||
account.update!(custom_attributes: { stripe_customer_id: 'cus_existing_v2' })
|
||||
|
||||
allow(Stripe::Customer).to receive(:create)
|
||||
# Stub the subscription check to return active subscription
|
||||
subscription_data = OpenStruct.new(id: 'sub_123')
|
||||
subscriptions_response = OpenStruct.new(data: [subscription_data])
|
||||
allow(Stripe::Subscription).to receive(:list).and_return(subscriptions_response)
|
||||
|
||||
create_stripe_customer_service.new(account: account).perform
|
||||
|
||||
expect(Stripe::Customer).to have_received(:create)
|
||||
expect(Stripe::Subscription).to have_received(:create)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when account has stripe_customer_id' do
|
||||
let(:stripe_customer_id) { 'cus_random_number' }
|
||||
|
||||
before do
|
||||
account.update!(custom_attributes: { stripe_customer_id: stripe_customer_id })
|
||||
end
|
||||
|
||||
context 'when customer has active subscriptions' do
|
||||
before do
|
||||
allow(Stripe::Subscription).to receive(:list).and_return(subscriptions_list)
|
||||
allow(subscriptions_list).to receive(:data).and_return(['subscription'])
|
||||
allow(Stripe::Subscription).to receive(:create)
|
||||
end
|
||||
|
||||
it 'does not create a new subscription' do
|
||||
create_stripe_customer_service.new(account: account).perform
|
||||
|
||||
expect(Stripe::Subscription).not_to have_received(:create)
|
||||
expect(Stripe::Subscription).to have_received(:list).with(
|
||||
{
|
||||
customer: stripe_customer_id,
|
||||
status: 'active',
|
||||
limit: 1
|
||||
}
|
||||
)
|
||||
end
|
||||
expect(Stripe::Customer).not_to have_received(:create)
|
||||
expect(account.reload.custom_attributes['stripe_customer_id']).to eq('cus_existing_v2')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -317,4 +317,146 @@ describe Enterprise::Billing::HandleStripeEventService do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe 'credit grant handling' do
|
||||
let(:credit_service) { instance_double(Enterprise::Billing::V2::CreditManagementService) }
|
||||
|
||||
before do
|
||||
allow(Enterprise::Billing::V2::CreditManagementService).to receive(:new)
|
||||
.with(account: account).and_return(credit_service)
|
||||
end
|
||||
|
||||
context 'when handling monthly credit grant' do
|
||||
it 'adds credits from Stripe' do
|
||||
allow(credit_service).to receive(:add_response_topup_credits)
|
||||
|
||||
# Webhook event object (minimal, just has ID)
|
||||
grant_event_object = OpenStruct.new(
|
||||
id: 'credgr_test_123',
|
||||
customer: 'cus_123'
|
||||
)
|
||||
allow(event).to receive(:type).and_return('billing.credit_grant.created')
|
||||
allow(data).to receive(:object).and_return(grant_event_object)
|
||||
|
||||
# Full grant object from API (has complete amount structure)
|
||||
api_grant_response = OpenStruct.new(
|
||||
id: 'credgr_test_123',
|
||||
customer: 'cus_123',
|
||||
metadata: { 'credits' => '2000' },
|
||||
amount: OpenStruct.new(
|
||||
type: 'custom_pricing_unit',
|
||||
custom_pricing_unit: OpenStruct.new(value: 2000)
|
||||
),
|
||||
expires_at: Time.current
|
||||
)
|
||||
allow(Stripe::Billing::CreditGrant).to receive(:retrieve)
|
||||
.with('credgr_test_123')
|
||||
.and_return(api_grant_response)
|
||||
|
||||
stripe_event_service.new.perform(event: event)
|
||||
|
||||
expect(credit_service).to have_received(:add_response_topup_credits).with(2000)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when handling topup credit grant' do
|
||||
it 'adds topup credits' do
|
||||
allow(credit_service).to receive(:add_response_topup_credits)
|
||||
|
||||
# Webhook event object (minimal, just has ID)
|
||||
grant_event_object = OpenStruct.new(
|
||||
id: 'credgr_test_456',
|
||||
customer: 'cus_123'
|
||||
)
|
||||
allow(event).to receive(:type).and_return('billing.credit_grant.created')
|
||||
allow(data).to receive(:object).and_return(grant_event_object)
|
||||
|
||||
# Full grant object from API (has complete amount structure)
|
||||
api_grant_response = OpenStruct.new(
|
||||
id: 'credgr_test_456',
|
||||
customer: 'cus_123',
|
||||
metadata: { 'credits' => '500' },
|
||||
amount: OpenStruct.new(
|
||||
type: 'custom_pricing_unit',
|
||||
custom_pricing_unit: OpenStruct.new(value: 500)
|
||||
),
|
||||
expires_at: nil
|
||||
)
|
||||
allow(Stripe::Billing::CreditGrant).to receive(:retrieve)
|
||||
.with('credgr_test_456')
|
||||
.and_return(api_grant_response)
|
||||
|
||||
stripe_event_service.new.perform(event: event)
|
||||
|
||||
expect(credit_service).to have_received(:add_response_topup_credits).with(500)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when handling monetary type credit grant' do
|
||||
it 'adds credits from monetary grant' do
|
||||
allow(credit_service).to receive(:add_response_topup_credits)
|
||||
|
||||
# Webhook event object (minimal, just has ID)
|
||||
grant_event_object = OpenStruct.new(
|
||||
id: 'credgr_test_monetary',
|
||||
customer: 'cus_123'
|
||||
)
|
||||
allow(event).to receive(:type).and_return('billing.credit_grant.created')
|
||||
allow(data).to receive(:object).and_return(grant_event_object)
|
||||
|
||||
# Full grant object from API with monetary amount
|
||||
api_grant_response = OpenStruct.new(
|
||||
id: 'credgr_test_monetary',
|
||||
customer: 'cus_123',
|
||||
metadata: { 'credits' => '1000' },
|
||||
amount: OpenStruct.new(
|
||||
type: 'monetary',
|
||||
monetary: OpenStruct.new(
|
||||
currency: 'usd',
|
||||
value: 1000
|
||||
)
|
||||
),
|
||||
expires_at: Time.current
|
||||
)
|
||||
allow(Stripe::Billing::CreditGrant).to receive(:retrieve)
|
||||
.with('credgr_test_monetary')
|
||||
.and_return(api_grant_response)
|
||||
|
||||
stripe_event_service.new.perform(event: event)
|
||||
|
||||
expect(credit_service).to have_received(:add_response_topup_credits).with(1000)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when handling credit grant with zero amount' do
|
||||
it 'does not call credit service' do
|
||||
# Webhook event object (minimal, just has ID)
|
||||
grant_event_object = OpenStruct.new(
|
||||
id: 'credgr_test_zero',
|
||||
customer: 'cus_123'
|
||||
)
|
||||
allow(event).to receive(:type).and_return('billing.credit_grant.created')
|
||||
allow(data).to receive(:object).and_return(grant_event_object)
|
||||
|
||||
# Full grant object from API with zero amount
|
||||
api_grant_response = OpenStruct.new(
|
||||
id: 'credgr_test_zero',
|
||||
customer: 'cus_123',
|
||||
amount: OpenStruct.new(
|
||||
type: 'custom_pricing_unit',
|
||||
custom_pricing_unit: OpenStruct.new(value: 0)
|
||||
),
|
||||
expires_at: Time.current
|
||||
)
|
||||
allow(Stripe::Billing::CreditGrant).to receive(:retrieve)
|
||||
.with('credgr_test_zero')
|
||||
.and_return(api_grant_response)
|
||||
|
||||
stripe_event_service.new.perform(event: event)
|
||||
|
||||
# Ensure we don't accidentally call these methods
|
||||
expect(Enterprise::Billing::V2::CreditManagementService).not_to have_received(:new)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Enterprise::Billing::V2::CreditManagementService do
|
||||
let(:account) { create(:account) }
|
||||
let(:service) { described_class.new(account: account) }
|
||||
|
||||
before do
|
||||
account.update!(
|
||||
custom_attributes: { 'captain_responses_usage' => 0 },
|
||||
limits: { 'captain_responses_monthly' => 100, 'captain_responses_topup' => 50 }
|
||||
)
|
||||
end
|
||||
|
||||
describe '#sync_monthly_response_credits' do
|
||||
it 'updates monthly credits' do
|
||||
service.sync_monthly_response_credits(500)
|
||||
|
||||
expect(account.reload.limits['captain_responses_monthly']).to eq(500)
|
||||
expect(account.limits['captain_responses']).to eq(550)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#add_response_topup_credits' do
|
||||
it 'adds topup credits' do
|
||||
service.add_response_topup_credits(100)
|
||||
|
||||
expect(account.reload.limits['captain_responses_topup']).to eq(150)
|
||||
expect(account.limits['captain_responses']).to eq(250)
|
||||
end
|
||||
end
|
||||
end
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Enterprise::Billing::V2::SubscriptionProvisioningService do
|
||||
let(:account) { create(:account) }
|
||||
let(:service) { described_class.new(account: account) }
|
||||
let(:subscription_id) { 'bpps_subscription_123' }
|
||||
let(:pricing_plan_id) { 'bpp_business_plan_123' }
|
||||
|
||||
before do
|
||||
account.update!(custom_attributes: { 'pending_subscription_quantity' => 5 })
|
||||
create(:installation_config, name: 'STRIPE_BUSINESS_PLAN_ID', value: pricing_plan_id)
|
||||
end
|
||||
|
||||
describe '#provision' do
|
||||
let(:subscription_response) do
|
||||
# Mock Stripe::V2::Billing::PricingPlanSubscription object
|
||||
instance_double(
|
||||
Stripe::V2::Billing::PricingPlanSubscription,
|
||||
id: subscription_id,
|
||||
pricing_plan: pricing_plan_id,
|
||||
billing_cadence: 'bpc_cadence_123',
|
||||
servicing_status: 'active'
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
# Mock the retrieve_pricing_plan_subscription method directly
|
||||
allow(service).to receive(:retrieve_pricing_plan_subscription).with(subscription_id).and_return(subscription_response)
|
||||
end
|
||||
|
||||
it 'provisions subscription' do
|
||||
result = service.provision(subscription_id: subscription_id)
|
||||
|
||||
expect(result[:pricing_plan_id]).to eq(pricing_plan_id)
|
||||
expect(result[:quantity]).to eq(5)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#refresh' do
|
||||
let(:subscription_response) do
|
||||
# Mock Stripe::V2::Billing::PricingPlanSubscription object
|
||||
instance_double(
|
||||
Stripe::V2::Billing::PricingPlanSubscription,
|
||||
id: 'bpps_sub_456',
|
||||
pricing_plan: pricing_plan_id,
|
||||
billing_cadence: 'bpc_cadence_123',
|
||||
servicing_status: 'active'
|
||||
)
|
||||
end
|
||||
|
||||
before do
|
||||
account.update!(custom_attributes: { 'stripe_subscription_id' => 'bpps_sub_456' })
|
||||
|
||||
# Mock the retrieve_pricing_plan_subscription method directly
|
||||
allow(service).to receive(:retrieve_pricing_plan_subscription).with('bpps_sub_456').and_return(subscription_response)
|
||||
end
|
||||
|
||||
it 'refreshes subscription' do
|
||||
result = service.refresh
|
||||
|
||||
expect(result[:pricing_plan_id]).to eq(pricing_plan_id)
|
||||
end
|
||||
end
|
||||
|
||||
describe '#cancel subscription' do
|
||||
let(:subscription_response) do
|
||||
# Mock Stripe::V2::Billing::PricingPlanSubscription object with canceled status
|
||||
instance_double(
|
||||
Stripe::V2::Billing::PricingPlanSubscription,
|
||||
id: subscription_id,
|
||||
pricing_plan: pricing_plan_id,
|
||||
billing_cadence: 'bpc_cadence_123',
|
||||
servicing_status: 'canceled'
|
||||
)
|
||||
end
|
||||
|
||||
let(:hacker_plan_id) { 'bpp_hacker_plan_123' }
|
||||
|
||||
before do
|
||||
create(:installation_config, name: 'STRIPE_HACKER_PLAN_ID', value: hacker_plan_id)
|
||||
|
||||
# Mock the retrieve_pricing_plan_subscription method directly
|
||||
allow(service).to receive(:retrieve_pricing_plan_subscription).with(subscription_id).and_return(subscription_response)
|
||||
end
|
||||
|
||||
it 'cancels subscription and resets to hacker plan' do
|
||||
result = service.provision(subscription_id: subscription_id)
|
||||
|
||||
expect(result[:pricing_plan_id]).to be_nil
|
||||
expect(result[:quantity]).to be_nil
|
||||
expect(account.custom_attributes['plan_name']).to eq('Hacker')
|
||||
expect(account.custom_attributes['stripe_subscription_id']).to be_nil
|
||||
expect(account.custom_attributes['subscription_status']).to eq('canceled')
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,35 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Enterprise::Billing::V2::TopupService do
|
||||
let(:account) { create(:account, custom_attributes: { 'stripe_customer_id' => 'cus_123', 'plan_name' => 'Business' }) }
|
||||
let(:service) { described_class.new(account: account) }
|
||||
|
||||
before do
|
||||
allow(Enterprise::Billing::V2::TopupCatalog).to receive(:find_option).with(500).and_return(
|
||||
credits: 500,
|
||||
amount: 50.0,
|
||||
currency: 'usd'
|
||||
)
|
||||
allow(Stripe::Customer).to receive(:retrieve).and_return(
|
||||
OpenStruct.new(invoice_settings: OpenStruct.new(default_payment_method: 'pm_123'), default_source: nil)
|
||||
)
|
||||
allow(Stripe::Invoice).to receive(:create).and_return(Stripe::Invoice.construct_from(id: 'in_123'))
|
||||
allow(Stripe::InvoiceItem).to receive(:create)
|
||||
allow(Stripe::Invoice).to receive(:finalize_invoice).and_return(
|
||||
Stripe::Invoice.construct_from(id: 'in_123', status: 'open')
|
||||
)
|
||||
allow(Stripe::Invoice).to receive(:pay).and_return(
|
||||
Stripe::Invoice.construct_from(id: 'in_123', status: 'paid', total: 5000, hosted_invoice_url: 'https://invoice.stripe.com')
|
||||
)
|
||||
allow(Stripe::Billing::CreditGrant).to receive(:create).and_return({ 'id' => 'credgr_123' })
|
||||
end
|
||||
|
||||
describe '#create_topup' do
|
||||
it 'creates topup' do
|
||||
result = service.create_topup(credits: 500)
|
||||
|
||||
expect(result[:success]).to be true
|
||||
expect(result[:credits]).to eq(500)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Enterprise::Billing::V2::UsageReporterService do
|
||||
let(:account) { create(:account, custom_attributes: { 'stripe_billing_version' => 2, 'stripe_customer_id' => 'cus_123' }) }
|
||||
let(:service) { described_class.new(account: account) }
|
||||
|
||||
describe '#report' do
|
||||
it 'posts usage to Stripe' do
|
||||
allow(Stripe::Billing::MeterEvent).to receive(:create).and_return(OpenStruct.new(identifier: 'me_123'))
|
||||
|
||||
result = service.report(5, 'ai_test')
|
||||
|
||||
expect(result[:success]).to be true
|
||||
expect(result[:event_id]).to eq('me_123')
|
||||
expect(Stripe::Billing::MeterEvent).to have_received(:create)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
require 'rails_helper'
|
||||
|
||||
describe Enterprise::Billing::V2::WebhookHandlerService do
|
||||
let(:account) { create(:account, custom_attributes: { 'stripe_customer_id' => 'cus_123' }) }
|
||||
let(:service) { described_class.new }
|
||||
let(:pricing_plan_id) { 'bpp_plan_123' }
|
||||
|
||||
describe '#perform' do
|
||||
let(:subscription_response) do
|
||||
OpenStruct.new(
|
||||
id: 'bpps_sub_123',
|
||||
billing_cadence: 'cad_123',
|
||||
pricing_plan: pricing_plan_id,
|
||||
servicing_status: 'active'
|
||||
)
|
||||
end
|
||||
let(:cadence_response) { OpenStruct.new(payer: OpenStruct.new(customer: 'cus_123')) }
|
||||
let(:event) do
|
||||
event_double = double
|
||||
allow(event_double).to receive(:blank?).and_return(false)
|
||||
allow(event_double).to receive(:type).and_return('v2.billing.pricing_plan_subscription.servicing_activated')
|
||||
allow(event_double).to receive(:related_object).and_return(OpenStruct.new(id: 'bpps_sub_123'))
|
||||
event_double
|
||||
end
|
||||
|
||||
before do
|
||||
account # Ensure account is created
|
||||
create(:installation_config, name: 'STRIPE_BUSINESS_PLAN_ID', value: pricing_plan_id)
|
||||
|
||||
# Mock the Stripe gem client methods
|
||||
stripe_client_double = double
|
||||
v2_double = double
|
||||
billing_double = double
|
||||
subscriptions_double = double
|
||||
cadences_double = double
|
||||
|
||||
allow(service).to receive(:stripe_client).and_return(stripe_client_double)
|
||||
allow(stripe_client_double).to receive(:v2).and_return(v2_double)
|
||||
allow(v2_double).to receive(:billing).and_return(billing_double)
|
||||
allow(billing_double).to receive(:pricing_plan_subscriptions).and_return(subscriptions_double)
|
||||
allow(billing_double).to receive(:cadences).and_return(cadences_double)
|
||||
|
||||
allow(subscriptions_double).to receive(:retrieve).with('bpps_sub_123').and_return(subscription_response)
|
||||
allow(cadences_double).to receive(:retrieve).with('cad_123').and_return(cadence_response)
|
||||
end
|
||||
|
||||
it 'handles subscription activation' do
|
||||
# Mock the subscription provisioning service
|
||||
provisioning_service_double = instance_double(
|
||||
Enterprise::Billing::V2::SubscriptionProvisioningService,
|
||||
provision: { pricing_plan_id: pricing_plan_id, quantity: 1 }
|
||||
)
|
||||
allow(Enterprise::Billing::V2::SubscriptionProvisioningService).to receive(:new)
|
||||
.with(account: account)
|
||||
.and_return(provisioning_service_double)
|
||||
|
||||
result = service.perform(event: event)
|
||||
|
||||
expect(provisioning_service_double).to have_received(:provision).with(subscription_id: 'bpps_sub_123')
|
||||
expect(result[:pricing_plan_id]).to eq(pricing_plan_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user