Compare commits

..
Author SHA1 Message Date
Muhsin 662922cd75 fix(conversations): add id tiebreaker to message thread seed so CSAT survey renders
The dashboard seeds the message thread from the conversation payload and then
paginates backward by id (before: messages[0].id). The seed was ordered by
created_at only, so on an auto-resolve burst where the input_csat survey shares
the exact same second as trailing activity messages, a lower-id activity could
win the tie and become the seed. Backward pagination then never loads the
higher-id survey, so the CSAT bubble is missing from the conversation even
though the rating exists and is counted in reports.

Order the seed by created_at DESC, id DESC: the seed stays the chronologically
latest message (no change for delayed-webhook rows), and same-second ties
resolve to the highest id so the survey is always reachable.
2026-07-03 13:27:48 +04:00
27 changed files with 103 additions and 604 deletions
@@ -35,25 +35,11 @@ class Public::Api::V1::Inboxes::ContactsController < Public::Api::V1::InboxesCon
end
def valid_hmac?
expected_identifier = hmac_identifier
return false if expected_identifier.blank?
return false unless params[:identifier].to_s == expected_identifier
expected_hash = OpenSSL::HMAC.hexdigest(
params[:identifier_hash] == OpenSSL::HMAC.hexdigest(
'sha256',
@inbox_channel.hmac_token,
expected_identifier
params[:identifier].to_s
)
identifier_hash = params[:identifier_hash].to_s
return false unless identifier_hash.bytesize == expected_hash.bytesize
ActiveSupport::SecurityUtils.secure_compare(identifier_hash, expected_hash)
end
def hmac_identifier
return params[:identifier].to_s if @contact_inbox.blank?
@contact_inbox.contact.identifier.to_s
end
def permitted_params
-12
View File
@@ -22,16 +22,4 @@ module BillingHelper
def agents(account)
account.users.count
end
# current_period_end moved to the subscription item in newer Stripe API versions; read both.
def subscription_period_end(subscription)
subscription['current_period_end'] || subscription['items']['data'].first&.[]('current_period_end')
end
def subscription_ends_on(subscription)
period_end = subscription_period_end(subscription)
return if period_end.blank?
Time.zone.at(period_end)
end
end
@@ -14,10 +14,6 @@ class EnterpriseAccountAPI extends ApiClient {
return axios.post(`${this.url}subscription`);
}
selectBillingCurrency(currency) {
return axios.post(`${this.url}select_billing_currency`, { currency });
}
getLimits() {
return axios.get(`${this.url}limits`);
}
@@ -31,11 +27,6 @@ class EnterpriseAccountAPI extends ApiClient {
createTopupCheckout(credits) {
return axios.post(`${this.url}topup_checkout`, { credits });
}
// Topup packages for the account's billing currency.
getTopupOptions() {
return axios.get(`${this.url}topup_options`);
}
}
export default new EnterpriseAccountAPI();
@@ -1,35 +0,0 @@
// Single source of truth for billing currencies on the frontend.
// Adding a currency = one entry in BILLING_CURRENCY_CONFIG, add the code to
// SUPPORTED_BILLING_CURRENCIES, and add its label key under
// BILLING_SETTINGS.CURRENCY.OPTIONS in the locale files.
export const DEFAULT_BILLING_CURRENCY = 'usd';
// Order here drives the order of the currency toggle in the UI.
export const SUPPORTED_BILLING_CURRENCIES = ['usd', 'brl'];
export const BILLING_CURRENCY_CONFIG = {
usd: {
code: 'usd',
intlLocale: 'en-US',
i18nLabelKey: 'BILLING_SETTINGS.CURRENCY.OPTIONS.USD',
},
brl: {
code: 'brl',
intlLocale: 'pt-BR',
i18nLabelKey: 'BILLING_SETTINGS.CURRENCY.OPTIONS.BRL',
},
};
export const getCurrencyConfig = code =>
BILLING_CURRENCY_CONFIG[(code || DEFAULT_BILLING_CURRENCY).toLowerCase()] ||
BILLING_CURRENCY_CONFIG[DEFAULT_BILLING_CURRENCY];
export const formatCurrencyAmount = (amount, code, options = {}) => {
const { intlLocale, code: currencyCode } = getCurrencyConfig(code);
return new Intl.NumberFormat(intlLocale, {
style: 'currency',
currency: currencyCode.toUpperCase(),
...options,
}).format(amount);
};
@@ -467,18 +467,7 @@
"TITLE": "Current Plan",
"PLAN_NOTE": "You are currently subscribed to the **{plan}** plan with **{quantity}** licenses",
"SEAT_COUNT": "Number of seats",
"RENEWS_ON": "Renews on",
"CURRENCY": "Currency"
},
"CURRENCY": {
"SELECT": {
"TITLE": "Choose your billing currency",
"DESCRIPTION": "Select the currency you'd like to be billed in. This can't be changed once your subscription is created."
},
"OPTIONS": {
"USD": "US Dollar (USD)",
"BRL": "Brazilian Real (BRL)"
}
"RENEWS_ON": "Renews on"
},
"VIEW_PRICING": "View Pricing",
"MANAGE_SUBSCRIPTION": {
@@ -514,7 +503,6 @@
"PURCHASE": "Purchase Credits",
"LOADING": "Loading options...",
"FETCH_ERROR": "Failed to load credit options. Please try again.",
"RETRY": "Retry",
"PURCHASE_ERROR": "Failed to process purchase. Please try again.",
"PURCHASE_SUCCESS": "Successfully added {credits} credits to your account",
"CONFIRM": {
@@ -15,8 +15,6 @@ import PurchaseCreditsModal from './components/PurchaseCreditsModal.vue';
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
import SettingsLayout from '../SettingsLayout.vue';
import ButtonV4 from 'next/button/Button.vue';
import { getCurrencyConfig } from 'dashboard/constants/billing';
import { useI18n } from 'vue-i18n';
const router = useRouter();
const { currentAccount, isOnChatwootCloud } = useAccount();
@@ -31,7 +29,6 @@ const {
const uiFlags = useMapGetter('accounts/getUIFlags');
const store = useStore();
const { t } = useI18n();
const BILLING_REFRESH_ATTEMPTED = 'billing_refresh_attempted';
@@ -39,10 +36,6 @@ const BILLING_REFRESH_ATTEMPTED = 'billing_refresh_attempted';
const isWaitingForBilling = ref(false);
const purchaseCreditsModalRef = ref(null);
// Currency selection shown to new accounts whose locale supports a non-USD currency.
const currencySelectionRequired = ref(false);
const currencyOptions = ref([]);
const customAttributes = computed(() => {
return currentAccount.value.custom_attributes || {};
});
@@ -68,13 +61,6 @@ const subscribedQuantity = computed(() => {
return customAttributes.value.subscribed_quantity;
});
const billingCurrency = computed(() => {
if (!customAttributes.value.billing_currency) return '';
return t(
getCurrencyConfig(customAttributes.value.billing_currency).i18nLabelKey
);
});
const subscriptionRenewsOn = computed(() => {
if (!customAttributes.value.subscription_ends_on) return '';
const endDate = new Date(customAttributes.value.subscription_ends_on);
@@ -92,9 +78,7 @@ const hasABillingPlan = computed(() => {
const fetchAccountDetails = async () => {
if (!hasABillingPlan.value) {
const data = await store.dispatch('accounts/subscription');
currencySelectionRequired.value = !!data?.currency_selection_required;
currencyOptions.value = data?.currency_options || [];
await store.dispatch('accounts/subscription');
}
// Always fetch limits for billing page to show credit usage
fetchLimits();
@@ -113,9 +97,6 @@ const handleBillingPageLogic = async () => {
// If cloud user, fetch account details first
await fetchAccountDetails();
// Waiting on the user to pick a billing currency — don't auto-refresh.
if (currencySelectionRequired.value) return;
// If still no billing plan after fetch
if (!hasABillingPlan.value) {
// If we haven't attempted refresh yet, do it once
@@ -137,13 +118,6 @@ const handleBillingPageLogic = async () => {
}
};
const onSelectCurrency = async code => {
await store.dispatch('accounts/selectBillingCurrency', code);
currencySelectionRequired.value = false;
// Currency stored and customer creation kicked off — resume the standard wait flow.
await handleBillingPageLogic();
};
const onClickBillingPortal = () => {
store.dispatch('accounts/checkout');
};
@@ -174,9 +148,7 @@ onMounted(handleBillingPageLogic);
? $t('BILLING_SETTINGS.NO_BILLING_USER')
: $t('ATTRIBUTES_MGMT.LOADING')
"
:no-records-found="
!hasABillingPlan && !isWaitingForBilling && !currencySelectionRequired
"
:no-records-found="!hasABillingPlan && !isWaitingForBilling"
:no-records-message="$t('BILLING_SETTINGS.NO_BILLING_USER')"
>
<template #header>
@@ -188,30 +160,7 @@ onMounted(handleBillingPageLogic);
/>
</template>
<template #body>
<section v-if="currencySelectionRequired" class="grid gap-4">
<BillingCard
:title="$t('BILLING_SETTINGS.CURRENCY.SELECT.TITLE')"
:description="$t('BILLING_SETTINGS.CURRENCY.SELECT.DESCRIPTION')"
>
<template #action>
<div class="flex gap-2">
<ButtonV4
v-for="code in currencyOptions"
:key="code"
sm
solid
blue
:is-loading="uiFlags.isCheckoutInProcess"
:disabled="uiFlags.isCheckoutInProcess"
@click="onSelectCurrency(code)"
>
{{ $t(getCurrencyConfig(code).i18nLabelKey) }}
</ButtonV4>
</div>
</template>
</BillingCard>
</section>
<section v-else class="grid gap-4">
<section class="grid gap-4">
<BillingCard
:title="$t('BILLING_SETTINGS.MANAGE_SUBSCRIPTION.TITLE')"
:description="$t('BILLING_SETTINGS.MANAGE_SUBSCRIPTION.DESCRIPTION')"
@@ -239,11 +188,6 @@ onMounted(handleBillingPageLogic);
:label="$t('BILLING_SETTINGS.CURRENT_PLAN.RENEWS_ON')"
:value="subscriptionRenewsOn"
/>
<DetailItem
v-if="billingCurrency"
:label="$t('BILLING_SETTINGS.CURRENT_PLAN.CURRENCY')"
:value="billingCurrency"
/>
</div>
</BillingCard>
<BillingCard
@@ -1,6 +1,4 @@
<script setup>
import { formatCurrencyAmount } from 'dashboard/constants/billing';
defineProps({
credits: {
type: Number,
@@ -35,7 +33,11 @@ const formatCredits = credits => {
};
const formatAmount = (amount, currency) => {
return formatCurrencyAmount(amount, currency, { minimumFractionDigits: 0 });
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency.toUpperCase(),
minimumFractionDigits: 0,
}).format(amount);
};
</script>
@@ -4,18 +4,20 @@ import { useI18n } from 'vue-i18n';
import { useAlert } from 'dashboard/composables';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import CreditPackageCard from './CreditPackageCard.vue';
import EnterpriseAccountAPI from 'dashboard/api/enterprise/account';
import {
formatCurrencyAmount,
DEFAULT_BILLING_CURRENCY,
} from 'dashboard/constants/billing';
const emit = defineEmits(['success']);
const emit = defineEmits(['close', 'success']);
const { t } = useI18n();
const TOPUP_OPTIONS = [
{ credits: 1000, amount: 20.0, currency: 'usd' },
{ credits: 2500, amount: 50.0, currency: 'usd' },
{ credits: 6000, amount: 100.0, currency: 'usd' },
{ credits: 12000, amount: 200.0, currency: 'usd' },
];
const POPULAR_CREDITS_AMOUNT = 6000;
const STEP_SELECT = 'select';
const STEP_CONFIRM = 'confirm';
@@ -25,20 +27,16 @@ const selectedCredits = ref(null);
const isLoading = ref(false);
const currentStep = ref(STEP_SELECT);
// Topup packages come from the backend for the account's billing currency.
const topupOptions = ref([]);
const optionsCurrency = ref(DEFAULT_BILLING_CURRENCY);
const isFetchingOptions = ref(false);
const fetchError = ref(false);
const selectedOption = computed(() => {
return topupOptions.value.find(o => o.credits === selectedCredits.value);
return TOPUP_OPTIONS.find(o => o.credits === selectedCredits.value);
});
const formattedAmount = computed(() => {
if (!selectedOption.value) return '';
const { amount, currency } = selectedOption.value;
return formatCurrencyAmount(amount, currency || optionsCurrency.value);
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: selectedOption.value.currency.toUpperCase(),
}).format(selectedOption.value.amount);
});
const formattedCredits = computed(() => {
@@ -66,44 +64,24 @@ const handlePackageSelect = credits => {
selectedCredits.value = credits;
};
const selectDefaultOption = () => {
const popularOption = topupOptions.value.find(
const open = () => {
const popularOption = TOPUP_OPTIONS.find(
o => o.credits === POPULAR_CREDITS_AMOUNT
);
selectedCredits.value =
popularOption?.credits || topupOptions.value[0]?.credits || null;
};
const fetchOptions = async () => {
isFetchingOptions.value = true;
fetchError.value = false;
try {
const { data } = await EnterpriseAccountAPI.getTopupOptions();
topupOptions.value = data.options ?? [];
optionsCurrency.value = (
data.currency || DEFAULT_BILLING_CURRENCY
).toLowerCase();
selectDefaultOption();
} catch {
fetchError.value = true;
topupOptions.value = [];
} finally {
isFetchingOptions.value = false;
}
};
const open = () => {
selectedCredits.value = popularOption?.credits || TOPUP_OPTIONS[0]?.credits;
currentStep.value = STEP_SELECT;
isLoading.value = false;
selectedCredits.value = null;
dialogRef.value?.open();
fetchOptions();
};
const close = () => {
dialogRef.value?.close();
};
const handleClose = () => {
emit('close');
};
const goToConfirmStep = () => {
if (!selectedOption.value) return;
currentStep.value = STEP_CONFIRM;
@@ -149,58 +127,32 @@ defineExpose({ open, close });
:width="dialogWidth"
:show-confirm-button="false"
:show-cancel-button="false"
@close="handleClose"
>
<!-- Step 1: Select Credits Package -->
<template v-if="currentStep === STEP_SELECT">
<div
v-if="isFetchingOptions"
class="flex items-center justify-center gap-2 py-10"
>
<Spinner />
<span class="text-sm text-n-slate-11">{{
$t('BILLING_SETTINGS.TOPUP.LOADING')
}}</span>
</div>
<div
v-else-if="fetchError"
class="flex flex-col items-center justify-center gap-3 py-10"
>
<p class="text-sm text-n-slate-11">
{{ $t('BILLING_SETTINGS.TOPUP.FETCH_ERROR') }}
</p>
<Button
variant="faded"
color="slate"
:label="$t('BILLING_SETTINGS.TOPUP.RETRY')"
@click="fetchOptions"
<template v-if="currentStep === 'select'">
<div class="grid grid-cols-2 gap-4">
<CreditPackageCard
v-for="option in TOPUP_OPTIONS"
:key="option.credits"
name="credit-package"
:credits="option.credits"
:amount="option.amount"
:currency="option.currency"
:is-popular="option.credits === POPULAR_CREDITS_AMOUNT"
:is-selected="selectedCredits === option.credits"
@select="handlePackageSelect(option.credits)"
/>
</div>
<template v-else>
<div class="grid grid-cols-2 gap-4">
<CreditPackageCard
v-for="option in topupOptions"
:key="option.credits"
name="credit-package"
:credits="option.credits"
:amount="option.amount"
:currency="option.currency"
:is-popular="option.credits === POPULAR_CREDITS_AMOUNT"
:is-selected="selectedCredits === option.credits"
@select="handlePackageSelect(option.credits)"
/>
</div>
<div class="p-4 mt-6 rounded-lg bg-n-solid-2 border border-n-weak">
<p class="text-sm text-n-slate-11">
<span class="font-semibold text-n-slate-12">{{
$t('BILLING_SETTINGS.TOPUP.NOTE_TITLE')
}}</span>
{{ $t('BILLING_SETTINGS.TOPUP.NOTE_DESCRIPTION') }}
</p>
</div>
</template>
<div class="p-4 mt-6 rounded-lg bg-n-solid-2 border border-n-weak">
<p class="text-sm text-n-slate-11">
<span class="font-semibold text-n-slate-12">{{
$t('BILLING_SETTINGS.TOPUP.NOTE_TITLE')
}}</span>
{{ $t('BILLING_SETTINGS.TOPUP.NOTE_DESCRIPTION') }}
</p>
</div>
</template>
<!-- Step 2: Confirm Purchase -->
@@ -226,7 +178,7 @@ defineExpose({ open, close });
<template #footer>
<!-- Step 1 Footer -->
<div
v-if="currentStep === STEP_SELECT"
v-if="currentStep === 'select'"
class="flex items-center justify-between w-full gap-3"
>
<Button
@@ -240,7 +192,7 @@ defineExpose({ open, close });
color="blue"
:label="$t('BILLING_SETTINGS.TOPUP.PURCHASE')"
class="w-full"
:disabled="!selectedCredits || isFetchingOptions || fetchError"
:disabled="!selectedCredits"
@click="goToConfirmStep"
/>
</div>
@@ -144,20 +144,7 @@ export const actions = {
subscription: async ({ commit }) => {
commit(types.default.SET_ACCOUNT_UI_FLAG, { isCheckoutInProcess: true });
try {
const response = await EnterpriseAccountAPI.subscription();
return response.data;
} catch (error) {
throwErrorMessage(error);
return null;
} finally {
commit(types.default.SET_ACCOUNT_UI_FLAG, { isCheckoutInProcess: false });
}
},
selectBillingCurrency: async ({ commit }, currency) => {
commit(types.default.SET_ACCOUNT_UI_FLAG, { isCheckoutInProcess: true });
try {
await EnterpriseAccountAPI.selectBillingCurrency(currency);
await EnterpriseAccountAPI.subscription();
} catch (error) {
throwErrorMessage(error);
} finally {
-8
View File
@@ -23,10 +23,6 @@ class AccountPolicy < ApplicationPolicy
@account_user.administrator?
end
def select_billing_currency?
@account_user.administrator?
end
def checkout?
@account_user.administrator?
end
@@ -38,8 +34,4 @@ class AccountPolicy < ApplicationPolicy
def topup_checkout?
@account_user.administrator?
end
def topup_options?
@account_user.administrator?
end
end
@@ -27,13 +27,18 @@ json.meta do
end
json.id conversation.display_id
if conversation.messages.where(account_id: conversation.account_id).last.blank?
# The dashboard seeds the message thread from this array and then paginates BACKWARD
# by id (before: messages[0].id). Keep the seed as the chronologically latest message,
# but add an id tiebreaker: without it, same-second siblings (e.g. the input_csat survey
# created alongside activity messages during an auto-resolve burst) could resolve to a
# lower-id activity, and backward pagination would then never load the higher-id survey.
last_message = conversation.messages.where(account_id: conversation.account_id)
.includes([{ attachments: [{ file_attachment: [:blob] }] }])
.reorder(created_at: :desc, id: :desc).first
if last_message.blank?
json.messages []
else
json.messages [
conversation.messages.where(account_id: conversation.account_id)
.includes([{ attachments: [{ file_attachment: [:blob] }] }]).last.try(:push_event_data)
]
json.messages [last_message.try(:push_event_data)]
end
json.account_id conversation.account_id
@@ -6,7 +6,6 @@ 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.billing_currency resource.billing_currency if resource.respond_to?(:billing_currency) && Enterprise::Billing::Currencies.enabled?
json.website resource.custom_attributes['website'] if resource.custom_attributes['website'].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?
-11
View File
@@ -253,17 +253,6 @@
display_title: 'Cloud Plans'
value:
description: 'Config to store stripe plans for cloud'
- name: CAPTAIN_TOPUP_OPTIONS
display_title: 'Captain Topup Options'
value: {}
description: 'Currency-keyed AI credit top-up packages, e.g. {"usd":[{"credits":1000,"amount":20.0}],"brl":[{"credits":1000,"amount":100.0}]}'
type: code
- name: ENABLE_MULTI_CURRENCY_BILLING
display_title: 'Enable Multi-currency Billing'
value: false
locked: false
description: 'Bill new accounts in their local currency (e.g. BRL) and show currency-aware credit top-ups; when off, everyone is billed in USD'
type: boolean
- name: MARKETING_CONVERSION_TRACKING_CONFIG
value:
display_title: 'Marketing Conversion Tracking Config'
-3
View File
@@ -173,9 +173,6 @@ en:
invalid_token: Invalid or expired MFA token
invalid_credentials: Invalid credentials or verification code
feature_unavailable: MFA feature is not available. Please configure encryption keys.
billing:
invalid_currency: Invalid billing currency
currency_locked: Billing currency cannot be changed after billing has been set up
topup:
credits_required: Credits amount is required
invalid_credits: Invalid credits amount
-2
View File
@@ -528,11 +528,9 @@ Rails.application.routes.draw do
member do
post :checkout
post :subscription
post :select_billing_currency
get :limits
post :toggle_deletion
post :topup_checkout
get :topup_options
end
end
end
@@ -2,24 +2,13 @@ class Enterprise::Api::V1::AccountsController < Api::BaseController
include BillingHelper
before_action :fetch_account
before_action :check_authorization
before_action :check_cloud_env, only: [:limits, :toggle_deletion, :topup_options]
before_action :check_cloud_env, only: [:limits, :toggle_deletion]
def subscription
return render json: currency_selection_payload if @account.billing_currency_selection_required?
ensure_stripe_customer
head :no_content
end
def select_billing_currency
return render_could_not_create_error(I18n.t('errors.billing.currency_locked')) if currency_locked?
return render_could_not_create_error(I18n.t('errors.billing.invalid_currency')) unless @account.billing_currency_selection_required?
currency = Enterprise::Billing::Currencies.normalize(params[:currency])
return render_could_not_create_error(I18n.t('errors.billing.invalid_currency')) unless Enterprise::Billing::Currencies.supported?(currency)
@account.update!(custom_attributes: @account.custom_attributes.merge('billing_currency' => currency))
ensure_stripe_customer
if stripe_customer_id.blank? && @account.custom_attributes['is_creating_customer'].blank?
@account.update(custom_attributes: { is_creating_customer: true })
Enterprise::CreateStripeCustomerJob.perform_later(@account)
end
head :no_content
end
@@ -82,32 +71,12 @@ class Enterprise::Api::V1::AccountsController < Api::BaseController
render_could_not_create_error(e.message)
end
def topup_options
service = Enterprise::Billing::TopupCheckoutService.new(account: @account)
render json: { id: @account.id, currency: @account.billing_currency, options: service.available_options }
end
private
def check_cloud_env
render json: { error: 'Not found' }, status: :not_found unless ChatwootApp.chatwoot_cloud?
end
def ensure_stripe_customer
return if stripe_customer_id.present? || @account.custom_attributes['is_creating_customer'].present?
@account.update!(custom_attributes: @account.custom_attributes.merge('is_creating_customer' => true))
Enterprise::CreateStripeCustomerJob.perform_later(@account)
end
def currency_selection_payload
{
currency_selection_required: true,
currency_options: Enterprise::Billing::Currencies::SUPPORTED,
suggested_currency: Enterprise::Billing::Currencies.for_locale(@account.locale)
}
end
def default_limits
{
'conversation' => {},
@@ -129,12 +98,6 @@ class Enterprise::Api::V1::AccountsController < Api::BaseController
@account.custom_attributes['stripe_customer_id']
end
# Currency is fixed once a customer exists or creation is already in flight,
# so a second click can't bill a different currency than setup started with.
def currency_locked?
stripe_customer_id.present? || @account.custom_attributes['is_creating_customer'].present?
end
def mark_for_deletion
reason = 'manual_deletion'
@@ -68,30 +68,6 @@ module Enterprise::Account
saml_settings&.saml_enabled? || false
end
def billing_currency
# Feature off => everyone is billed in USD (legacy behaviour).
return Enterprise::Billing::Currencies::DEFAULT unless Enterprise::Billing::Currencies.enabled?
stored = custom_attributes&.dig('billing_currency')
return Enterprise::Billing::Currencies.normalize(stored) if Enterprise::Billing::Currencies.supported?(stored)
# Existing Stripe customers stay on USD (webhook backfills the real currency);
# only brand-new accounts infer from locale, so existing pt_BR users aren't charged BRL.
return Enterprise::Billing::Currencies::DEFAULT if custom_attributes&.dig('stripe_customer_id').present?
Enterprise::Billing::Currencies.for_locale(locale)
end
# New accounts whose locale maps to a non-USD currency get to pick USD or that
# currency before the Stripe customer is created; everyone else proceeds in USD.
def billing_currency_selection_required?
return false unless Enterprise::Billing::Currencies.enabled?
return false if custom_attributes&.dig('stripe_customer_id').present?
return false if Enterprise::Billing::Currencies.supported?(custom_attributes&.dig('billing_currency'))
Enterprise::Billing::Currencies.for_locale(locale) != Enterprise::Billing::Currencies::DEFAULT
end
private
def sync_assignment_features
@@ -1,6 +1,4 @@
class Enterprise::Billing::CreateStripeCustomerService
include BillingHelper
pattr_initialize [:account!]
DEFAULT_QUANTITY = 2
@@ -23,22 +21,13 @@ class Enterprise::Billing::CreateStripeCustomerService
def prepare_customer_id
customer_id = account.custom_attributes['stripe_customer_id']
customer_id = Stripe::Customer.create(customer_params).id if customer_id.blank?
if customer_id.blank?
customer = Stripe::Customer.create({ name: account.name, email: billing_email })
customer_id = customer.id
end
customer_id
end
# Only currencies that need a country override (e.g. BRL/PIX) set address/locale; usd keeps Stripe defaults.
def customer_params
params = { name: account.name, email: billing_email }
country = Enterprise::Billing::Currencies.country_for(account.billing_currency)
return params if country.blank?
params.merge(
address: { country: country },
preferred_locales: [Enterprise::Billing::Currencies.preferred_locale_for(account.billing_currency)]
)
end
def default_quantity
default_plan['default_quantity'] || DEFAULT_QUANTITY
end
@@ -48,11 +37,13 @@ class Enterprise::Billing::CreateStripeCustomerService
end
def default_plan
@default_plan ||= Enterprise::Billing::PlanConfiguration.default_plan
installation_config = InstallationConfig.find_by(name: 'CHATWOOT_CLOUD_PLANS')
@default_plan ||= installation_config.value.first
end
def price_id
Enterprise::Billing::PlanConfiguration.price_id_for(default_plan, account.billing_currency)
price_ids = default_plan['price_ids']
price_ids.first
end
def active_subscription
@@ -69,7 +60,7 @@ class Enterprise::Billing::CreateStripeCustomerService
end
def default_plan_subscription?(subscription)
Enterprise::Billing::PlanConfiguration.plan_contains_product_id?(default_plan, subscription['plan']['product'])
default_plan['price_ids'].include?(subscription['plan']['id'])
end
def build_custom_attributes(customer_id, subscription)
@@ -80,14 +71,14 @@ class Enterprise::Billing::CreateStripeCustomerService
'plan_name' => default_plan['name'],
'subscribed_quantity' => subscription['quantity'],
'subscription_status' => subscription['status'],
'subscription_ends_on' => subscription_ends_on(subscription),
'billing_currency' => billing_currency_for(subscription)
'subscription_ends_on' => subscription_ends_on(subscription)
)
end
# Persist the currency Stripe actually billed, read straight from the price; the
# requested currency may lack a configured price and fall back to usd.
def billing_currency_for(subscription)
Enterprise::Billing::Currencies.to_supported(subscription['plan']['currency'])
def subscription_ends_on(subscription)
period_end = subscription['current_period_end']
return if period_end.blank?
Time.zone.at(period_end)
end
end
@@ -1,55 +0,0 @@
# Supported billing currencies and their Stripe/locale mappings.
module Enterprise::Billing::Currencies
DEFAULT = 'usd'.freeze
SUPPORTED = %w[usd brl].freeze
FEATURE_CONFIG = 'ENABLE_MULTI_CURRENCY_BILLING'.freeze
# Account locale label (e.g. 'pt_BR') => default currency; unlisted falls back to DEFAULT.
LOCALE_DEFAULTS = {
'pt_BR' => 'brl'
}.freeze
# Billing country override per currency; absent currencies (e.g. usd) keep Stripe's default.
COUNTRY_BY_CURRENCY = {
'brl' => 'BR'
}.freeze
# Preferred Stripe/checkout locale per currency; absent currencies keep Stripe's default.
PREFERRED_LOCALE_BY_CURRENCY = {
'brl' => 'pt-BR'
}.freeze
module_function
# Master switch for the whole multi-currency feature; off => everyone is billed in USD.
def enabled?
GlobalConfigService.load(FEATURE_CONFIG, 'false').to_s != 'false'
end
def normalize(code)
code.to_s.strip.downcase.presence
end
def supported?(code)
SUPPORTED.include?(normalize(code))
end
# Map arbitrary input to a supported code, else DEFAULT.
def to_supported(code)
supported?(code) ? normalize(code) : DEFAULT
end
def for_locale(locale)
LOCALE_DEFAULTS.fetch(locale.to_s, DEFAULT)
end
def country_for(code)
COUNTRY_BY_CURRENCY[to_supported(code)]
end
def preferred_locale_for(code)
PREFERRED_LOCALE_BY_CURRENCY[to_supported(code)]
end
end
@@ -1,6 +1,4 @@
class Enterprise::Billing::HandleStripeEventService
include BillingHelper
CLOUD_PLANS_CONFIG = 'CHATWOOT_CLOUD_PLANS'.freeze
CAPTAIN_CLOUD_PLAN_LIMITS = 'CAPTAIN_CLOUD_PLAN_LIMITS'.freeze
@@ -67,19 +65,11 @@ class Enterprise::Billing::HandleStripeEventService
'plan_name' => plan['name'],
'subscribed_quantity' => subscription['quantity'],
'subscription_status' => subscription['status'],
'subscription_ends_on' => subscription_ends_on(subscription),
'billing_currency' => billing_currency_for(subscription, plan)
'subscription_ends_on' => Time.zone.at(subscription['current_period_end'])
)
)
end
# Paid subscriptions define the currency; the free/default plan keeps the stored preference.
def billing_currency_for(subscription, plan)
return account.billing_currency if plan['name'] == Enterprise::Billing::PlanConfiguration.default_plan&.dig('name')
Enterprise::Billing::Currencies.to_supported(subscription['plan']['currency'])
end
def track_marketing_plan_activation(previous_plan_name, current_plan_name)
subscription_plan = subscription['plan']
@@ -171,8 +161,8 @@ class Enterprise::Billing::HandleStripeEventService
@account ||= Account.where("custom_attributes->>'stripe_customer_id' = ?", subscription.customer).first
end
def find_plan(product_id)
Enterprise::Billing::PlanConfiguration.find_plan_by_product_id(product_id)
def find_plan(plan_id)
cloud_plans.find { |config| config['product_id'].include?(plan_id) }
end
def previous_plan_name
@@ -181,4 +171,8 @@ class Enterprise::Billing::HandleStripeEventService
find_plan(stripe_plan['product'])&.dig('name')
end
def cloud_plans
@cloud_plans ||= InstallationConfig.find_by(name: CLOUD_PLANS_CONFIG)&.value || []
end
end
@@ -1,46 +0,0 @@
# Resolves Stripe price ids from CHATWOOT_CLOUD_PLANS per currency.
# A plan's `price_ids` may be a currency-keyed Hash, or a legacy Array (treated as usd).
module Enterprise::Billing::PlanConfiguration
CLOUD_PLANS_CONFIG = 'CHATWOOT_CLOUD_PLANS'.freeze
module_function
def plans
InstallationConfig.find_by(name: CLOUD_PLANS_CONFIG)&.value || []
end
def default_plan
plans.first
end
# Handles both shapes during migration; once all configs are currency-keyed Hashes, drop the Array branch.
def price_ids_by_currency(plan)
raw = plan && plan['price_ids']
case raw
when Hash then raw.transform_keys { |key| Enterprise::Billing::Currencies.normalize(key) }
when Array then { Enterprise::Billing::Currencies::DEFAULT => raw }
else {}
end
end
# Price id for `plan` in `currency`, falling back to usd then any configured price.
# The multi-step fallback is migration-era safety; once configs settle on one format we can simplify this.
def price_id_for(plan, currency)
by_currency = price_ids_by_currency(plan)
code = Enterprise::Billing::Currencies.to_supported(currency)
(by_currency[code].presence ||
by_currency[Enterprise::Billing::Currencies::DEFAULT].presence ||
by_currency.values.flatten.compact).first
end
# Match by product id, not price id: production has prices that aren't enumerated
# in our config but share a product, so product matching still resolves the plan.
def plan_contains_product_id?(plan, product_id)
Array(plan && plan['product_id']).include?(product_id)
end
def find_plan_by_product_id(product_id)
plans.find { |plan| plan_contains_product_id?(plan, product_id) }
end
end
@@ -3,15 +3,15 @@ class Enterprise::Billing::TopupCheckoutService
class Error < StandardError; end
TOPUP_OPTIONS_CONFIG = 'CAPTAIN_TOPUP_OPTIONS'.freeze
TOPUP_OPTIONS = [
{ credits: 1000, amount: 20.0, currency: 'usd' },
{ credits: 2500, amount: 50.0, currency: 'usd' },
{ credits: 6000, amount: 100.0, currency: 'usd' },
{ credits: 12_000, amount: 200.0, currency: 'usd' }
].freeze
pattr_initialize [:account!]
# Topup packages for the account's billing currency (used by the controller).
def available_options
topup_options
end
def create_checkout_session(credits:)
topup_option = validate_and_find_topup_option(credits)
charge_customer(topup_option, credits)
@@ -100,20 +100,6 @@ class Enterprise::Billing::TopupCheckoutService
end
def find_topup_option(credits)
topup_options.find { |opt| opt[:credits] == credits.to_i }
end
def topup_options
# Label rows with the currency they were configured under, so a DEFAULT fallback can't relabel USD amounts and undercharge.
options = configured_options
currency = options[account.billing_currency].present? ? account.billing_currency : Enterprise::Billing::Currencies::DEFAULT
rows = options[currency].presence || []
rows.map { |opt| { credits: opt['credits'].to_i, amount: opt['amount'].to_f, currency: currency } }
end
def configured_options
config = InstallationConfig.find_by(name: TOPUP_OPTIONS_CONFIG)&.value
config = JSON.parse(config) if config.is_a?(String)
config || {}
TOPUP_OPTIONS.find { |opt| opt[:credits] == credits.to_i }
end
end
@@ -2,7 +2,7 @@ require 'rails_helper'
RSpec.describe 'Public Inbox Contacts API', type: :request do
let!(:api_channel) { create(:channel_api) }
let!(:contact) { create(:contact, account: api_channel.account, identifier: 'victim-identifier') }
let!(:contact) { create(:contact) }
let!(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: api_channel.inbox) }
describe 'POST /public/api/v1/inboxes/{identifier}/contact' do
@@ -36,26 +36,6 @@ RSpec.describe 'Public Inbox Contacts API', type: :request do
expect(data['source_id']).to eq contact_inbox.source_id
expect(data['pubsub_token']).to eq contact_inbox.pubsub_token
end
it 'marks the contact inbox verified when the identifier hash matches the selected contact' do
identifier_hash = OpenSSL::HMAC.hexdigest('sha256', api_channel.hmac_token, contact.identifier)
get "/public/api/v1/inboxes/#{api_channel.identifier}/contacts/#{contact_inbox.source_id}",
params: { identifier: contact.identifier, identifier_hash: identifier_hash }
expect(response).to have_http_status(:success)
expect(contact_inbox.reload.hmac_verified).to be(true)
end
it 'does not verify a contact inbox with a hash for a different identifier' do
attacker_hash = OpenSSL::HMAC.hexdigest('sha256', api_channel.hmac_token, 'attacker-identifier')
get "/public/api/v1/inboxes/#{api_channel.identifier}/contacts/#{contact_inbox.source_id}",
params: { identifier: 'attacker-identifier', identifier_hash: attacker_hash }
expect(response).to have_http_status(:internal_server_error)
expect(contact_inbox.reload.hmac_verified).to be(false)
end
end
describe 'PATCH /public/api/v1/inboxes/{identifier}/contact/{source_id}' do
@@ -256,14 +256,6 @@ RSpec.describe 'Enterprise Billing APIs', type: :request do
{ 'name' => 'Hacker', 'product_id' => ['prod_hacker'], 'price_ids' => ['price_hacker'] },
{ 'name' => 'Business', 'product_id' => ['prod_business'], 'price_ids' => ['price_business'] }
])
create(:installation_config, name: 'CAPTAIN_TOPUP_OPTIONS', value: {
'usd' => [
{ 'credits' => 1000, 'amount' => 20.0 },
{ 'credits' => 2500, 'amount' => 50.0 },
{ 'credits' => 6000, 'amount' => 100.0 },
{ 'credits' => 12_000, 'amount' => 200.0 }
]
})
end
it 'returns unauthorized for unauthenticated user' do
@@ -82,8 +82,7 @@ describe Enterprise::Billing::CreateStripeCustomerService do
subscribed_quantity: 2,
plan_name: 'A Plan Name',
subscription_status: 'active',
subscription_ends_on: subscription_ends_on,
billing_currency: 'usd'
subscription_ends_on: subscription_ends_on
}.with_indifferent_access
)
end
@@ -96,9 +95,7 @@ describe Enterprise::Billing::CreateStripeCustomerService do
create_stripe_customer_service.new(account: account).perform
expect(Stripe::Customer).to have_received(:create).with(
{ name: account.name, email: admin1.email }
)
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 }] })
@@ -111,27 +108,10 @@ describe Enterprise::Billing::CreateStripeCustomerService do
subscribed_quantity: 2,
plan_name: 'A Plan Name',
subscription_status: 'active',
subscription_ends_on: subscription_ends_on,
billing_currency: 'usd'
subscription_ends_on: subscription_ends_on
}.with_indifferent_access
)
end
it 'sets the billing country override when the account currency requires it' do
with_modified_env ENABLE_MULTI_CURRENCY_BILLING: 'true' do
account.update!(custom_attributes: { billing_currency: 'brl' })
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(created_subscription)
create_stripe_customer_service.new(account: account).perform
expect(Stripe::Customer).to have_received(:create).with(
{ name: account.name, email: admin1.email, address: { country: 'BR' }, preferred_locales: ['pt-BR'] }
)
end
end
end
describe 'when checking for existing subscriptions' do
@@ -1,36 +0,0 @@
require 'rails_helper'
describe Enterprise::Billing::Currencies do
describe 'Brazilian Real (brl)' do
it 'is a supported currency' do
expect(described_class.supported?('brl')).to be(true)
end
it 'recognizes brl regardless of casing or surrounding whitespace' do
expect(described_class.supported?(' BRL ')).to be(true)
expect(described_class.normalize(' BRL ')).to eq('brl')
end
it 'keeps brl when coercing to a supported code' do
expect(described_class.to_supported('BRL')).to eq('brl')
end
it 'defaults the pt_BR account locale to brl' do
expect(described_class.for_locale('pt_BR')).to eq('brl')
end
it 'maps brl to Brazil and the pt-BR checkout locale' do
expect(described_class.country_for('brl')).to eq('BR')
expect(described_class.preferred_locale_for('brl')).to eq('pt-BR')
end
it 'falls back to the usd default for unsupported input' do
expect(described_class.to_supported('eur')).to eq('usd')
end
it 'does not set a country override for usd customers' do
expect(described_class.country_for('usd')).to be_nil
expect(described_class.preferred_locale_for('usd')).to be_nil
end
end
end
@@ -15,15 +15,6 @@ describe Enterprise::Billing::TopupCheckoutService do
{ 'name' => 'Business', 'product_id' => ['prod_business'], 'price_ids' => ['price_business'] }
])
create(:installation_config, name: 'CAPTAIN_TOPUP_OPTIONS', value: {
'usd' => [
{ 'credits' => 1000, 'amount' => 20.0 },
{ 'credits' => 2500, 'amount' => 50.0 },
{ 'credits' => 6000, 'amount' => 100.0 },
{ 'credits' => 12_000, 'amount' => 200.0 }
]
})
account.update!(
custom_attributes: { plan_name: 'Business', stripe_customer_id: stripe_customer_id },
limits: { 'captain_responses' => 500 }