From 36d2229e389252f211bc56e4e2fa21a3d28aa623 Mon Sep 17 00:00:00 2001 From: brooklyn! Date: Wed, 23 Sep 2026 11:09:01 -0500 Subject: [PATCH] fix(desktop): localize billing shell and state feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adapt billing catalog wiring from #74691 to the current subscription and payment controls. Resolve local display text at the UI boundary while preserving server plan names, notices, price formatting and charge policy. Co-authored-by: Анатолий Лаптев --- .../app/settings/billing/auto-reload-row.tsx | 37 ++- .../app/settings/billing/billing-amounts.ts | 23 +- .../settings/billing/current-plan-card.tsx | 7 +- .../src/app/settings/billing/errors.ts | 99 +++--- .../src/app/settings/billing/index.test.tsx | 49 ++- .../src/app/settings/billing/index.tsx | 42 ++- .../app/settings/billing/inline-feedback.tsx | 17 +- .../src/app/settings/billing/plans-view.tsx | 56 ++-- .../billing/use-billing-state.test.ts | 93 ++++++ .../app/settings/billing/use-billing-state.ts | 293 ++++++++++-------- .../billing/use-charge-poller.test.ts | 2 +- .../app/settings/billing/use-charge-poller.ts | 92 ++++-- .../src/app/settings/billing/use-step-up.ts | 44 +-- apps/desktop/src/i18n/en.ts | 274 ++++++++++++++++ apps/desktop/src/i18n/types.ts | 211 +++++++++++++ apps/desktop/src/i18n/zh-hant.ts | 223 +++++++++++++ apps/desktop/src/i18n/zh.ts | 223 +++++++++++++ 17 files changed, 1504 insertions(+), 281 deletions(-) diff --git a/apps/desktop/src/app/settings/billing/auto-reload-row.tsx b/apps/desktop/src/app/settings/billing/auto-reload-row.tsx index 876e82b890..d430945d1a 100644 --- a/apps/desktop/src/app/settings/billing/auto-reload-row.tsx +++ b/apps/desktop/src/app/settings/billing/auto-reload-row.tsx @@ -3,6 +3,7 @@ import { useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' +import { useI18n } from '@/i18n' import { cn } from '@/lib/utils' import { ListRow, Pill } from '../primitives' @@ -24,6 +25,8 @@ export function AutoReloadRow({ bounds: Pick row: BillingAccountRowView }) { + const { t } = useI18n() + const b = t.settings.billing.autoReload const api = useBillingApi() const queryClient = useQueryClient() const [confirmDisable, setConfirmDisable] = useState(false) @@ -32,7 +35,7 @@ export function AutoReloadRow({ // save — opening Manage on a prefilled (possibly below-min) config must not // flash an error (spec §9). const [showErrors, setShowErrors] = useState(false) - const [message, setMessage] = useState(null) + const [message, setMessage] = useState(null) const [refusal, setRefusal] = useState(null) const [reloadTo, setReloadTo] = useState( @@ -45,7 +48,7 @@ export function AutoReloadRow({ initialAutoReloadAmount(autoReload.threshold_usd, autoReload.threshold_display) ) - const validation = validateAutoReloadInputs(threshold, reloadTo, bounds) + const validation = validateAutoReloadInputs(threshold, reloadTo, bounds, t.settings.billing) const busy = saving const maxBound = bounds.max_usd ?? undefined const minBound = bounds.min_usd ?? undefined @@ -95,7 +98,7 @@ export function AutoReloadRow({ } await queryClient.invalidateQueries({ queryKey: ['billing', 'state'] }) - setMessage({ kind: 'success', text: 'Auto-refill updated.' }) + setMessage({ kind: 'success', text: 'updated' }) setEditing(false) } @@ -125,7 +128,7 @@ export function AutoReloadRow({ } await queryClient.invalidateQueries({ queryKey: ['billing', 'state'] }) - setMessage({ kind: 'success', text: 'Auto-refill turned off.' }) + setMessage({ kind: 'success', text: 'turnedOff' }) setEditing(false) } @@ -142,7 +145,7 @@ export function AutoReloadRow({ ) : null} - {message && {message.text}} + {message && {b[message.text]}} } description={row.description} @@ -178,9 +181,9 @@ export function AutoReloadRow({
@@ -261,15 +264,15 @@ export function AutoReloadRow({ {editing ? ( <> ) : ( )}
diff --git a/apps/desktop/src/app/settings/billing/billing-amounts.ts b/apps/desktop/src/app/settings/billing/billing-amounts.ts index 0b0e5517b9..088a916ae3 100644 --- a/apps/desktop/src/app/settings/billing/billing-amounts.ts +++ b/apps/desktop/src/app/settings/billing/billing-amounts.ts @@ -1,3 +1,6 @@ +import type { Translations } from '@/i18n' +import { en } from '@/i18n/en' + import type { BillingStateResponse } from './types' import { EMPTY_BILLING_VALUE } from './use-billing-state' @@ -49,22 +52,23 @@ export function initialAutoReloadAmount(...candidates: Array + bounds: Pick, + b: Translations['settings']['billing'] = en.settings.billing ): { error?: string; values?: { reloadTo: string; threshold: string } } { - const threshold = validateBillingAmount('Threshold', thresholdRaw, bounds) + const threshold = validateBillingAmount(b.autoReload.threshold, thresholdRaw, bounds, b.amountValidation) if (threshold.error || threshold.amount == null) { return { error: threshold.error } } - const reloadTo = validateBillingAmount('Reload-to', reloadToRaw, bounds) + const reloadTo = validateBillingAmount(b.amountValidation.reloadTo, reloadToRaw, bounds, b.amountValidation) if (reloadTo.error || reloadTo.amount == null) { return { error: reloadTo.error } } if (reloadTo.amount <= threshold.amount) { - return { error: 'Reload-to amount must be greater than the threshold.' } + return { error: b.amountValidation.greaterThanThreshold } } return { @@ -78,30 +82,31 @@ export function validateAutoReloadInputs( export function validateBillingAmount( label: string, raw: string, - bounds: Pick + bounds: Pick, + copy: Translations['settings']['billing']['amountValidation'] = en.settings.billing.amountValidation ): { amount?: number; error?: string } { const cleaned = raw.trim().replace(/^\$/, '').trim() if (!cleaned || !/^\d+(\.\d{1,2})?$/.test(cleaned)) { - return { error: `${label}: enter a dollar amount with at most 2 decimal places.` } + return { error: copy.decimal(label) } } const amount = Number(cleaned) if (!(amount > 0)) { - return { error: `${label}: amount must be greater than $0.` } + return { error: copy.positive(label) } } const min = parseAmount(bounds.min_usd) if (min != null && amount < min) { - return { error: `${label}: minimum is ${formatMoney(min)}.` } + return { error: copy.minimum(label, formatMoney(min)) } } const max = parseAmount(bounds.max_usd) if (max != null && amount > max) { - return { error: `${label}: maximum is ${formatMoney(max)}.` } + return { error: copy.maximum(label, formatMoney(max)) } } return { amount } diff --git a/apps/desktop/src/app/settings/billing/current-plan-card.tsx b/apps/desktop/src/app/settings/billing/current-plan-card.tsx index ce879dfd7c..638aae9748 100644 --- a/apps/desktop/src/app/settings/billing/current-plan-card.tsx +++ b/apps/desktop/src/app/settings/billing/current-plan-card.tsx @@ -1,4 +1,5 @@ import { Button } from '@/components/ui/button' +import { useI18n } from '@/i18n' import { ExternalLink } from '@/lib/icons' import { BillingRefusalInline } from './inline-feedback' @@ -8,6 +9,8 @@ import type { BillingPlanCardView } from './use-billing-state' import { useResumeFlow } from './use-subscription-change' export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void; plan: BillingPlanCardView }) { + const { t } = useI18n() + const b = t.settings.billing const resumeFlow = useResumeFlow() return ( @@ -22,7 +25,7 @@ export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void {plan.price && ( - {plan.price}/mo + {b.perMonth(plan.price)} )} @@ -40,7 +43,7 @@ export function CurrentPlanCard({ onViewPlans, plan }: { onViewPlans: () => void {/* Scheduled downgrade → chargeless undo (subscription.resume), no confirm. */} {plan.pending && ( )} {plan.link && ( diff --git a/apps/desktop/src/app/settings/billing/errors.ts b/apps/desktop/src/app/settings/billing/errors.ts index 0357bf4244..ee82be5499 100644 --- a/apps/desktop/src/app/settings/billing/errors.ts +++ b/apps/desktop/src/app/settings/billing/errors.ts @@ -1,3 +1,6 @@ +import type { Translations } from '@/i18n' +import { en } from '@/i18n/en' + import type { BillingRefusal } from './api' export interface BillingRefusalPresentation { @@ -8,51 +11,52 @@ export interface BillingRefusalPresentation { const portalAction = (url?: string): BillingRefusalPresentation['action'] => ({ type: 'portal', url }) -const retryMessage = (refusal: BillingRefusal): string => { - const mins = refusal.retryAfter ? ` (try again in ~${Math.max(1, Math.round(refusal.retryAfter / 60))} min)` : '' +const retryMessage = (refusal: BillingRefusal, copy: Translations['settings']['billing']['errors']): string => { + const mins = refusal.retryAfter ? Math.max(1, Math.round(refusal.retryAfter / 60)) : 0 - return `🟡 Too many charges right now${mins}. This isn't a payment failure.` + return copy.rateLimited.message(mins) } -const stripeRetryMessage = (refusal: BillingRefusal): string => { - const mins = refusal.retryAfter ? ` (try again in ~${Math.max(1, Math.round(refusal.retryAfter / 60))} min)` : '' +const stripeRetryMessage = (refusal: BillingRefusal, copy: Translations['settings']['billing']['errors']): string => { + const mins = refusal.retryAfter ? Math.max(1, Math.round(refusal.retryAfter / 60)) : 0 - return `Stripe is having trouble — try again shortly${mins}` + return copy.stripeUnavailable.message(mins) } -export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentation => { +export const resolveRefusal = ( + refusal: BillingRefusal, + copy: Translations['settings']['billing']['errors'] = en.settings.billing.errors +): BillingRefusalPresentation => { switch (refusal.kind) { case 'consent_required': return { action: portalAction(refusal.portalUrl), - message: 'Confirm this card for terminal charges in the portal', - title: 'Card confirmation needed' + message: copy.consentRequired.message, + title: copy.consentRequired.title } case 'insufficient_scope': return { action: { type: 'step_up' }, - message: 'This needs Remote Spending allowed. Start a top-up to allow it, then retry.', - title: 'Remote Spending needs approval' + message: copy.insufficientScope.message, + title: copy.insufficientScope.title } case 'remote_spending_revoked': { const who = - refusal.actor === 'admin' - ? 'An admin stopped remote spending for this terminal.' - : 'You stopped remote spending for this terminal.' + refusal.actor === 'admin' ? copy.remoteSpendingRevoked.messageByAdmin : copy.remoteSpendingRevoked.messageBySelf return { action: portalAction(refusal.portalUrl), - message: `${who} Reconnect from Settings → Gateway to re-authorize this device.`, - title: 'Remote spending was stopped' + message: copy.remoteSpendingReconnect(who), + title: copy.remoteSpendingRevoked.title } } case 'session_revoked': return { action: portalAction(refusal.portalUrl), - message: 'Your session was logged out. Sign in again from Settings → Gateway.', - title: 'Session logged out' + message: copy.sessionRevoked.message, + title: copy.sessionRevoked.title } case 'cli_billing_disabled': @@ -60,39 +64,36 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentat case 'remote_spending_disabled': return { action: portalAction(refusal.portalUrl), - message: - "Remote spending is off for this account — a billing admin can turn it on from the portal's Hermes Agent page.", - title: 'Remote spending is off' + message: copy.cliBillingDisabled.message, + title: copy.cliBillingDisabled.title } case 'role_required': return { action: portalAction(refusal.portalUrl), - message: 'Adding funds needs an org admin/owner. Ask an admin, or manage on the portal.', - title: 'Admin role required' + message: copy.roleRequired.message, + title: copy.roleRequired.title } case 'idempotency_conflict': return { action: { type: 'none' }, - message: '🔴 That charge key was already used for a different amount. Start a fresh top-up.', - title: 'Start a fresh top-up' + message: copy.idempotencyConflict.message, + title: copy.idempotencyConflict.title } case 'no_payment_method': return { action: portalAction(refusal.portalUrl), - message: - '💳 No saved card for terminal charges yet. Set one up on the portal ' + - "(one-time credit buys don't save a reusable card).", - title: 'No saved card' + message: copy.noPaymentMethod.message, + title: copy.noPaymentMethod.title } case 'org_access_denied': return { action: { type: 'none' }, - message: "This token isn't bound to an org you can manage", - title: 'Org access denied' + message: copy.orgAccessDenied.message, + title: copy.orgAccessDenied.title } case 'monthly_cap_exceeded': { const remaining = refusal.payload?.remainingUsd @@ -101,9 +102,9 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentat action: portalAction(refusal.portalUrl), message: remaining != null - ? `🔴 Monthly spend cap reached — $${remaining} headroom left.` - : '🔴 Monthly spend cap reached.', - title: 'Monthly spend cap reached' + ? copy.monthlyCapExceeded.messageHeadroom(remaining) + : copy.monthlyCapExceeded.messageReached, + title: copy.monthlyCapExceeded.title } } @@ -112,52 +113,50 @@ export const resolveRefusal = (refusal: BillingRefusal): BillingRefusalPresentat case 'temporarily_unavailable': return { action: { type: 'retry' }, - message: retryMessage(refusal), - title: 'Too many charges right now' + message: retryMessage(refusal, copy), + title: copy.rateLimited.title } case 'stripe_unavailable': return { action: { type: 'retry' }, - message: stripeRetryMessage(refusal), - title: 'Stripe is having trouble' + message: stripeRetryMessage(refusal, copy), + title: copy.stripeUnavailable.title } case 'upgrade_cap_exceeded': return { action: { type: 'none' }, - message: 'Daily plan-change limit reached — try again tomorrow', - title: 'Daily plan-change limit reached' + message: copy.upgradeCapExceeded.message, + title: copy.upgradeCapExceeded.title } case 'endpoint_unavailable': return { action: { type: 'retry' }, - message: - refusal.message || - 'Billing endpoint returned a non-JSON response (it may not be available on this deployment).', - title: 'Billing endpoint unavailable' + message: refusal.message || copy.endpointUnavailable.message, + title: copy.endpointUnavailable.title } case 'timeout': return { action: { type: 'retry' }, - message: refusal.message || 'Billing request timed out.', - title: 'Billing request timed out' + message: refusal.message || copy.timeout.message, + title: copy.timeout.title } case 'transport': return { action: { type: 'retry' }, - message: refusal.message || 'Billing request failed before reaching the gateway.', - title: 'Billing connection failed' + message: refusal.message || copy.transport.message, + title: copy.transport.title } default: return { action: { type: 'none' }, - message: refusal.message || 'Billing request failed.', - title: 'Billing request failed' + message: refusal.message || copy.default.message, + title: copy.default.title } } } diff --git a/apps/desktop/src/app/settings/billing/index.test.tsx b/apps/desktop/src/app/settings/billing/index.test.tsx index 3283c5e429..027d01bc24 100644 --- a/apps/desktop/src/app/settings/billing/index.test.tsx +++ b/apps/desktop/src/app/settings/billing/index.test.tsx @@ -1,9 +1,11 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { ReactNode } from 'react' import { MemoryRouter } from 'react-router' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { type I18nContextValue, I18nProvider, useI18n } from '@/i18n' + import { formatMoney } from './billing-amounts' import { billingDevFixtures, @@ -79,6 +81,51 @@ afterEach(() => { }) describe('BillingSettings', () => { + it('changes billing shell language without losing the credit amount or issuing a charge', async () => { + apiMocks.fetchBillingState.mockResolvedValue(okBilling(postTrainBillingState)) + apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(postTrainSubscriptionState)) + let language!: I18nContextValue + + function Surface() { + language = useI18n() + + return + } + + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + + + + + + ) + await screen.findByText('支付与额度') + expect(screen.getByText('余额')).toBeTruthy() + const input = screen.getByRole('spinbutton', { name: '自定义充值金额' }) as HTMLInputElement + fireEvent.change(input, { target: { value: '37' } }) + await act(() => language.setLocale('zh-hant')) + expect(screen.getByText('支付與額度')).toBeTruthy() + expect(screen.getByText('餘額')).toBeTruthy() + expect((screen.getByRole('spinbutton', { name: '自訂儲值金額' }) as HTMLInputElement).value).toBe('37') + expect(apiMocks.charge).not.toHaveBeenCalled() + apiMocks.charge.mockResolvedValue({ + ok: false, + refusal: { kind: 'stripe_unavailable', message: '', retryAfter: 120 }, + idempotencyKey: 'fixture-charge' + }) + fireEvent.click(screen.getByRole('button', { name: '購買' })) + await screen.findByText(/Stripe 遇到問題/) + await act(() => language.setLocale('zh')) + expect(screen.getByText(/Stripe 遇到问题/)).toBeTruthy() + expect(apiMocks.charge).toHaveBeenCalledTimes(1) + expect(apiMocks.charge).toHaveBeenCalledWith('37', undefined) + expect(screen.getAllByText(postTrainSubscriptionState.current!.tier_name!).length).toBeGreaterThan(0) + client.clear() + }) + it('renders the post-train payload with enabled buy controls and card provenance', async () => { apiMocks.fetchBillingState.mockResolvedValue(okBilling(postTrainBillingState)) apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(postTrainSubscriptionState)) diff --git a/apps/desktop/src/app/settings/billing/index.tsx b/apps/desktop/src/app/settings/billing/index.tsx index e1f57882a1..c97130dd43 100644 --- a/apps/desktop/src/app/settings/billing/index.tsx +++ b/apps/desktop/src/app/settings/billing/index.tsx @@ -163,6 +163,9 @@ function AccountRow({ billing, row }: { billing?: BillingStateResponse; row: Bil } function BuyCreditsRow({ billing, row }: { billing: BillingStateResponse; row: BillingAccountRowView }) { + const { t } = useI18n() + const b = t.settings.billing + const presets = useMemo( () => billing.charge_presets.map((amount, index) => ({ @@ -200,7 +203,7 @@ function BuyCreditsRow({ billing, row }: { billing: BillingStateResponse; row: B value={amount} /> } @@ -258,12 +261,14 @@ function BuyCreditsOutcome({ onRetry: () => void outcome: ReturnType['outcome'] }) { + const { t } = useI18n() + const b = t.settings.billing const stepUp = useStepUpFlow() if (busy) { return (
- Processing… checking settlement + {b.buyCredits.processing}
) } @@ -275,7 +280,7 @@ function BuyCreditsOutcome({ if (outcome.kind === 'success') { return (
- {formatMoney(outcome.amountUsd ?? amount)} added. Balance is refreshing. + {b.buyCredits.added(formatMoney(outcome.amountUsd ?? amount))}
) } @@ -288,7 +293,7 @@ function BuyCreditsOutcome({ {outcome.portalUrl && ( )} @@ -305,13 +310,13 @@ function BuyCreditsOutcome({ {outcome.action?.type === 'retry' && ( )} {outcome.action?.type === 'step_up' && } {portalUrl && ( )} @@ -320,8 +325,10 @@ function BuyCreditsOutcome({ } function UsageBar({ bar, fallbackLabel }: { bar?: BillingUsageRowView['bar']; fallbackLabel: string }) { + const { t } = useI18n() + const resolvedBar = bar ?? { - label: `${fallbackLabel} usage`, + label: t.settings.billing.usageLabel(fallbackLabel), state: 'neutral', tone: 'topup', value: 0 @@ -383,10 +390,13 @@ function BillingFixtureSelect({ onValueChange: (value: BillingFixtureSelection) => void value: BillingFixtureSelection }) { + const { t } = useI18n() + const b = t.settings.billing + return (
- preview + {b.preview}