Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(billing): 修复临时结算与套餐变更展示 (#466)

GaoWei Liud546f0e7ae8f
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index ce10b1d6c9..21ff86eb89 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -78,18 +78,15 @@ const SUPPORTED_SUBSCRIPTION_CAPABILITIES = new Set<BillingPurchaseOption['capab
'PROVIDER_MANAGED_SUBSCRIPTION',
]);
-// 新服务端的“当前订阅”只包含真实生命周期状态,未完成首购不再下发也不阻断重选;
-// INCOMPLETE 仅作为旧服务端兼容防御保留(旧服务端仍会拒绝重复首购)。
+// 未完成首购只属于当前 checkout 会话,不能展示为当前套餐或阻断重新购买。
const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] = [
- 'INCOMPLETE',
'TRIALING',
'ACTIVE',
'PAST_DUE',
'UNPAID',
'PAUSED',
];
-const SUBSCRIPTION_CANCELLABLE_STATUSES: BillingSubscription['status'][] =
- SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.filter((status) => status !== 'INCOMPLETE');
+const SUBSCRIPTION_CANCELLABLE_STATUSES = SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES;
const PLAN_CHANGE_ENTRY_STATUSES: BillingSubscription['status'][] = ['ACTIVE'];
@@ -295,14 +292,23 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
}
}, []);
- const loadSubscription = useCallback(async () => {
+ const loadSubscription = useCallback(async (fallback: BillingSubscription | null = null) => {
setLoadingSubscription(true);
setSubscriptionError(false);
try {
- setCurrentSubscription((await billingApi.getCurrentSubscription()).subscription);
+ const subscription = (await billingApi.getCurrentSubscription()).subscription;
+ setCurrentSubscription(
+ subscription && SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.includes(subscription.status)
+ ? subscription
+ : null,
+ );
} catch {
- setCurrentSubscription(null);
- setSubscriptionError(true);
+ const completedFallback =
+ fallback && SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.includes(fallback.status)
+ ? fallback
+ : null;
+ setCurrentSubscription(completedFallback);
+ setSubscriptionError(completedFallback === null);
} finally {
setLoadingSubscription(false);
}
@@ -328,13 +334,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
void loadBillingState();
}, [loadBillingState]);
- useEffect(() => {
- if (checkout.state.subscription) {
- setCurrentSubscription(checkout.state.subscription);
- setSubscriptionError(false);
- }
- }, [checkout.state.subscription]);
-
const closeCheckout = useCallback(() => {
const abandonedIncomplete = checkout.state.subscription?.status === 'INCOMPLETE';
checkout.close();
@@ -349,8 +348,17 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
previousCheckoutPhaseRef.current = checkout.state.phase;
if (previousPhase !== 'COMPLETED' && checkout.state.phase === 'COMPLETED') {
void loadBalance();
+ if (checkout.state.kind === 'SUBSCRIPTION') {
+ void loadSubscription(checkout.state.subscription);
+ }
}
- }, [checkout.state.phase, loadBalance]);
+ }, [
+ checkout.state.kind,
+ checkout.state.phase,
+ checkout.state.subscription,
+ loadBalance,
+ loadSubscription,
+ ]);
const handlePlanChangeSettled = useCallback(
(kind: PlanChangeSettledKind) => {
@@ -484,6 +492,35 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
SUPPORTED_BILLING_PROVIDERS.has(currentSubscription.provider as SupportedBillingProvider)
? (currentSubscription.provider as SupportedBillingProvider)
: null;
+ const currentPlanCandidate = useMemo<PlanChangeCandidate | null>(() => {
+ if (!currentPlan) return null;
+ const catalogProduct = catalog?.products.find(
+ (product) => product.code === currentPlan.product.code,
+ );
+ return {
+ product: {
+ code: currentPlan.product.code,
+ name: catalogProduct?.name ?? currentPlan.product.code,
+ kind: 'SUBSCRIPTION',
+ level: currentPlan.product.level,
+ sortOrder: catalogProduct?.sortOrder ?? 0,
+ offers: [],
+ },
+ offer: {
+ code: currentPlan.offer.code,
+ interval: currentPlan.offer.interval,
+ currency: currentPlan.terms.currency,
+ amount: currentPlan.terms.amount,
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: currentPlan.terms.creditAmount,
+ rolloverCap: currentPlan.terms.rolloverCap,
+ purchaseOptions: [],
+ },
+ providers: currentProvider ? [currentProvider] : [],
+ direction: null,
+ };
+ }, [catalog, currentPlan, currentProvider]);
const showPlanChangeEntry =
currentPlan !== null &&
currentSubscription !== null &&
@@ -827,6 +864,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
<PlanChangeTargetDialog
open={planChangeTargetOpen}
+ currentPlan={currentPlanCandidate}
candidates={planChangeCandidates}
onClose={() => setPlanChangeTargetOpen(false)}
onSelect={selectPlanChangeTarget}
diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
index 689469739a..b7cf70aa93 100644
--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
@@ -54,17 +54,23 @@ function formatEffectiveDate(iso: string, locale: string): string {
export function PlanChangeTargetDialog({
open,
+ currentPlan,
candidates,
onClose,
onSelect,
}: {
open: boolean;
+ currentPlan: PlanChangeCandidate | null;
candidates: PlanChangeCandidate[];
onClose: () => void;
onSelect: (candidate: PlanChangeCandidate) => void;
}) {
const { t, i18n } = useTranslation();
const billingLocale = i18n.resolvedLanguage ?? i18n.language;
+ const displayedPlans = [
+ ...(currentPlan ? [{ candidate: currentPlan, current: true }] : []),
+ ...candidates.map((candidate) => ({ candidate, current: false })),
+ ];
return (
<Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<Dialog.Portal>
@@ -94,19 +100,9 @@ export function PlanChangeTargetDialog({
</div>
<div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-6 py-4 [scrollbar-gutter:stable]">
- {candidates.length === 0 ? (
- <div className="flex min-h-[184px] flex-col items-center justify-center rounded-xl border border-[var(--border-default)] px-6 text-center">
- <div className="grid size-11 place-items-center rounded-full bg-[var(--surface-chip)]">
- <PackageOpen size={22} />
- </div>
- <p className="mt-4 text-sm font-medium">{t('billing.planChange.emptyTitle')}</p>
- <p className="mt-1 text-12 text-[var(--text-secondary)]">
- {t('billing.planChange.emptyDescription')}
- </p>
- </div>
- ) : (
+ {displayedPlans.length > 0 && (
<div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">
- {candidates.map((candidate) => {
+ {displayedPlans.map(({ candidate, current }) => {
const DirectionIcon =
candidate.direction === 'UPGRADE'
? ArrowUpRight
@@ -114,13 +110,15 @@ export function PlanChangeTargetDialog({
? ArrowDownRight
: null;
const directionLabel =
- candidate.direction === 'UPGRADE'
- ? t('billing.planChange.upgradeBadge')
- : candidate.direction === 'DOWNGRADE'
- ? t('billing.planChange.downgradeBadge')
- : candidate.direction === 'SAME_LEVEL'
- ? t('billing.planChange.sameLevelBadge')
- : null;
+ current
+ ? t('billing.catalog.currentPlan')
+ : candidate.direction === 'UPGRADE'
+ ? t('billing.planChange.upgradeBadge')
+ : candidate.direction === 'DOWNGRADE'
+ ? t('billing.planChange.downgradeBadge')
+ : candidate.direction === 'SAME_LEVEL'
+ ? t('billing.planChange.sameLevelBadge')
+ : null;
const providerLabel = candidate.providers
.map((provider) => t(`billing.providers.${provider}`))
.join(', ');
@@ -128,10 +126,14 @@ export function PlanChangeTargetDialog({
<button
key={candidate.offer.code}
type="button"
- onClick={() => onSelect(candidate)}
+ disabled={current}
+ aria-current={current ? 'true' : undefined}
+ onClick={() => {
+ if (!current) onSelect(candidate);
+ }}
className={cn(
'flex w-full items-center justify-between gap-4 px-4 py-3 text-left',
- 'transition-colors hover:bg-[var(--surface-hover-soft)]',
+ !current && 'transition-colors hover:bg-[var(--surface-hover-soft)]',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',
'focus-visible:ring-[var(--text-primary)]',
)}
@@ -175,6 +177,23 @@ export function PlanChangeTargetDialog({
})}
</div>
)}
+ {candidates.length === 0 && (
+ <div
+ className={cn(
+ 'flex min-h-[184px] flex-col items-center justify-center rounded-xl border',
+ 'border-[var(--border-default)] px-6 text-center',
+ displayedPlans.length > 0 && 'mt-4',
+ )}
+ >
+ <div className="grid size-11 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <PackageOpen size={22} />
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.planChange.emptyTitle')}</p>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('billing.planChange.emptyDescription')}
+ </p>
+ </div>
+ )}
</div>
</Dialog.Content>
</Dialog.Portal>
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index e4511df124..48ddf2d28e 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -838,8 +838,8 @@ describe('BillingPage remote catalog rendering', () => {
expect(checkout.startSubscription).not.toHaveBeenCalled();
});
- it.each(['CANCELED', 'INCOMPLETE_EXPIRED'] as const)(
- 'routes a %s terminal subscription to repurchase',
+ it.each(['INCOMPLETE', 'CANCELED', 'INCOMPLETE_EXPIRED'] as const)(
+ 'does not treat a %s response as the current subscription',
async (status) => {
window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
subscription: {
@@ -856,6 +856,10 @@ describe('BillingPage remote catalog rendering', () => {
}));
render(<BillingPage />);
+ expect(
+ await screen.findByText('billing.settings.subscriptionCard.emptyTitle'),
+ ).toBeTruthy();
+ expect(screen.queryByText(`billing.subscriptionStatus.${status}`)).toBeNull();
fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));
fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);
@@ -1252,7 +1256,11 @@ describe('BillingPage plan change', () => {
observedAt: '2026-07-23T12:00:00.000Z',
})),
getCatalog: vi.fn(async () => subscriptionCatalog),
- getCurrentSubscription: vi.fn(async () => ({ subscription: activeSubscription() })),
+ getCurrentSubscription: vi.fn(
+ async (): Promise<{ subscription: BillingSubscription | null }> => ({
+ subscription: activeSubscription(),
+ }),
+ ),
cancelCurrentSubscription: vi.fn(),
quotePlanChange: vi.fn(),
confirmPlanChange: vi.fn(),
@@ -1314,7 +1322,7 @@ describe('BillingPage plan change', () => {
});
it.each(['INCOMPLETE', 'CANCELED', 'INCOMPLETE_EXPIRED'] as const)(
- 'does not offer renewal cancellation for a %s subscription',
+ 'ignores a non-current %s subscription response',
async (status) => {
const billing = billingMocks();
billing.getCurrentSubscription = vi.fn(async () => ({
@@ -1324,12 +1332,70 @@ describe('BillingPage plan change', () => {
render(<BillingPage />);
- await screen.findByText(`billing.subscriptionStatus.${status}`);
+ await screen.findByText('billing.settings.subscriptionCard.emptyTitle');
+ expect(screen.queryByText(`billing.subscriptionStatus.${status}`)).toBeNull();
expect(screen.queryByText('billing.settings.subscriptionCard.cancelAction')).toBeNull();
expect(billing.cancelCurrentSubscription).not.toHaveBeenCalled();
},
);
+ it('reloads the canonical subscription after checkout instead of keeping a provider-less response', async () => {
+ const billing = billingMocks();
+ const canonical = { ...activeSubscription(), provider: 'alipay' };
+ billing.getCurrentSubscription
+ .mockResolvedValueOnce({ subscription: null })
+ .mockResolvedValueOnce({ subscription: canonical });
+ install(billing);
+ const checkoutSubscription: BillingSubscription = { ...canonical };
+ delete checkoutSubscription.provider;
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'AWAITING_PAYMENT',
+ subscription: checkoutSubscription,
+ });
+
+ const view = render(<BillingPage />);
+ await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(1));
+
+ Object.assign(checkout.state, { phase: 'COMPLETED' });
+ view.rerender(<BillingPage />);
+
+ await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
+ expect(await screen.findByText('Alipay-only Max')).toBeTruthy();
+ expect(screen.queryByText('Max plan')).toBeNull();
+ });
+
+ it('keeps the completed checkout subscription when the canonical reload temporarily fails', async () => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription
+ .mockResolvedValueOnce({ subscription: null })
+ .mockRejectedValueOnce(new Error('temporarily unavailable'));
+ install(billing);
+ const completed = { ...activeSubscription(), provider: 'alipay' };
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'AWAITING_PAYMENT',
+ subscription: { ...completed, status: 'INCOMPLETE' },
+ });
+
+ const view = render(<BillingPage />);
+ await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(1));
+
+ Object.assign(checkout.state, {
+ phase: 'COMPLETED',
+ subscription: completed,
+ });
+ view.rerender(<BillingPage />);
+
+ await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('billing.subscriptionStatus.ACTIVE')).toBeTruthy();
+ expect(screen.queryByText('billing.settings.subscriptionCard.unavailable')).toBeNull();
+ expect(screen.getByText('billing.settings.subscriptionCard.changeAction')).toBeTruthy();
+ });
+
it('locks cancellation before confirmation resolves', async () => {
const billing = install(billingMocks());
let resolveConfirm!: (confirmed: boolean) => void;
@@ -1457,6 +1523,8 @@ describe('BillingPage plan change', () => {
fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
await screen.findByText('billing.planChange.targetTitle');
+ const dialog = screen.getByRole('dialog');
+ const currentPlanButton = within(dialog).getByText('Plus plan').closest('button')!;
const maxButton = screen.getByText('Max plan').closest('button')!;
const sameLevelButton = screen.getByText('Same-level plan').closest('button')!;
const starterButton = screen.getByText('Starter plan').closest('button')!;
@@ -1467,6 +1535,9 @@ describe('BillingPage plan change', () => {
sameLevelButton.compareDocumentPosition(starterButton) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
expect(within(maxButton).getByText('billing.planChange.upgradeBadge')).toBeTruthy();
+ expect(currentPlanButton.hasAttribute('disabled')).toBe(true);
+ expect(currentPlanButton.getAttribute('aria-current')).toBe('true');
+ expect(within(currentPlanButton).getByText('billing.catalog.currentPlan')).toBeTruthy();
expect(within(maxButton).getByText('stripe')).toBeTruthy();
expect(within(sameLevelButton).getByText('billing.planChange.sameLevelBadge')).toBeTruthy();
expect(within(starterButton).getByText('billing.planChange.downgradeBadge')).toBeTruthy();
@@ -1501,6 +1572,36 @@ describe('BillingPage plan change', () => {
expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2);
});
+ it('renders a grandfathered current plan from the captured subscription terms', async () => {
+ const billing = billingMocks();
+ const grandfathered = activeSubscription();
+ grandfathered.effectivePlan = {
+ ...grandfathered.effectivePlan!,
+ offer: { code: 'plus_legacy', interval: 'MONTH' },
+ terms: {
+ amount: '7',
+ currency: 'usd',
+ creditAmount: '80',
+ rolloverCap: '0',
+ },
+ };
+ billing.getCurrentSubscription = vi.fn(async () => ({ subscription: grandfathered }));
+ install(billing);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
+
+ const dialog = await screen.findByRole('dialog');
+ const currentButton = within(dialog)
+ .getByText('billing.catalog.currentPlan')
+ .closest('button')!;
+ expect(within(currentButton).getByText('Plus plan')).toBeTruthy();
+ expect(within(currentButton).getByText('$7.00')).toBeTruthy();
+ expect(
+ within(currentButton).getByText('billing.credits:{"amount":"80"}'),
+ ).toBeTruthy();
+ });
+
it('does not expose plan change for yearly subscriptions while server v1 is monthly-only', async () => {
const billing = billingMocks();
billing.getCurrentSubscription = vi.fn(async () => ({
@@ -1608,6 +1709,10 @@ describe('BillingPage plan change', () => {
});
render(<BillingPage />);
+ await waitFor(() => {
+ expect(screen.getByText('billing.settings.subscriptionCard.emptyTitle')).toBeTruthy();
+ expect(screen.queryByText('billing.subscriptionStatus.INCOMPLETE')).toBeNull();
+ });
fireEvent.click(await screen.findByLabelText('billing.actions.close'));
expect(checkout.close).toHaveBeenCalled();