Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 按商品分组展示订阅套餐 (#1474)
GaoWei Liudb4eafc2c2c3
diff --git a/apps/desktop/src/main/billing/__tests__/projection.test.ts b/apps/desktop/src/main/billing/__tests__/projection.test.tsindex 644734a614..dc552c701e 100644--- a/apps/desktop/src/main/billing/__tests__/projection.test.ts+++ b/apps/desktop/src/main/billing/__tests__/projection.test.ts@@ -326,6 +326,7 @@ describe('billing response projection', () => {offers: [{code: 'credit_topup_20',+ name: '20 credits',interval: null,currency: 'cny',amount: '20',@@ -386,6 +387,7 @@ describe('billing response projection', () => {offers: [{code: 'credit_topup_20',+ name: '20 credits',interval: null,currency: 'cny',amount: '20',@@ -420,6 +422,7 @@ describe('billing response projection', () => {offers: [{code: 'coming_soon',+ name: null,salesState: 'COMING_SOON',purchasable: false,unavailableReason: 'OFFER_COMING_SOON',@@ -434,6 +437,7 @@ describe('billing response projection', () => {},{code: 'no_available_channel',+ name: '',salesState: 'AVAILABLE',purchasable: false,unavailableReason: 'NO_AVAILABLE_PAYMENT_CHANNEL',@@ -448,6 +452,7 @@ describe('billing response projection', () => {},{code: 'available',+ name: 'x'.repeat(129),salesState: 'AVAILABLE',purchasable: true,unavailableReason: null,@@ -514,6 +519,9 @@ describe('billing response projection', () => {],}),]);+ expect(projected.products[0]?.offers[0]).not.toHaveProperty('name');+ expect(projected.products[0]?.offers[1]).not.toHaveProperty('name');+ expect(projected.products[0]?.offers[2]).not.toHaveProperty('name');});it('enforces the server contract that offer codes are globally unique', () => {diff --git a/apps/desktop/src/main/billing/projection.ts b/apps/desktop/src/main/billing/projection.tsindex 2e65ccd0bc..1d319969fd 100644--- a/apps/desktop/src/main/billing/projection.ts+++ b/apps/desktop/src/main/billing/projection.ts@@ -403,6 +403,7 @@ function projectOffer(): BillingCatalogOffer | null {if (!isRecord(value) || !Array.isArray(value.purchaseOptions)) return null;const offerCode = code(value.code);+ const offerName = boundedString(value.name, 128) ?? undefined;const offerCurrency = currency(value.currency);const amount = nullable(value.amount, decimal);const minAmount = nullable(value.minAmount, decimal);@@ -516,6 +517,7 @@ function projectOffer(}return {code: offerCode,+ ...(offerName ? { name: offerName } : {}),...availability,interval: isSubscription ? interval : null,currency: offerCurrency,diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex 8fd37ccea0..288dfd0264 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -1,9 +1,11 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import {ArrowRight,Check,ChevronDown,+ ChevronRight,+ ChevronUp,CircleDollarSign,CreditCard,ExternalLink,@@ -61,6 +63,12 @@ type CatalogOfferEntry = {purchaseOptions: SupportedPurchaseOption[];};+type SubscriptionProductEntry = {+ product: BillingCatalogProduct;+ offers: CatalogOfferEntry[];+ defaultOffer: CatalogOfferEntry;+};+type SupportedBillingProvider = 'alipay' | 'stripe';type SupportedPurchaseOption = BillingPurchaseOption & {provider: SupportedBillingProvider;@@ -223,6 +231,34 @@ function isCatalogOfferPurchasable(entry: CatalogOfferEntry): boolean {return entry.offer.purchasable === true && entry.purchaseOptions.length > 0;}+function isSubscriptionOfferSelectable(+ entry: CatalogOfferEntry,+ currentSubscriptionOfferCode: string | null,+): boolean {+ return isCatalogOfferPurchasable(entry) && entry.offer.code !== currentSubscriptionOfferCode;+}++function groupSubscriptionProducts(+ entries: CatalogOfferEntry[],+ currentSubscriptionOfferCode: string | null,+): SubscriptionProductEntry[] {+ const groups = new Map<string, { product: BillingCatalogProduct; offers: CatalogOfferEntry[] }>();+ for (const entry of entries) {+ const group = groups.get(entry.product.code);+ if (group) {+ group.offers.push(entry);+ } else {+ groups.set(entry.product.code, { product: entry.product, offers: [entry] });+ }+ }+ return Array.from(groups.values()).flatMap(({ product, offers }) => {+ const defaultOffer =+ offers.find((entry) => isSubscriptionOfferSelectable(entry, currentSubscriptionOfferCode)) ??+ offers[0];+ return defaultOffer ? [{ product, offers, defaultOffer }] : [];+ });+}+function catalogOfferUnavailableReason(entry: CatalogOfferEntry,): BillingCatalogOfferUnavailableReason | null {@@ -296,6 +332,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst [subscriptionDialogOpen, setSubscriptionDialogOpen] = useState(false);const [topupDialogOpen, setTopupDialogOpen] = useState(false);const [planChangeTargetOpen, setPlanChangeTargetOpen] = useState(false);+ const [selectedProductCode, setSelectedProductCode] = useState<string | null>(null);const [selectedOfferCode, setSelectedOfferCode] = useState<string | null>(null);const [selectedPurchaseOptionId, setSelectedPurchaseOptionId] = useState<string | null>(null);const [customAmount, setCustomAmount] = useState('');@@ -327,6 +364,11 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetCustomAmount('');}, []);+ const resetSubscriptionSelection = useCallback(() => {+ setSelectedProductCode(null);+ resetSelection();+ }, [resetSelection]);+/*** 深链 `?tab=billing&intent=topup` —— 别处(供应商设置页的账户资产模块)想触发* 充值时唯一的入口。充值弹窗依赖本 section 的目录 / 选项 / checkout 会话状态,@@ -528,37 +570,75 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst currentSubscriptionOfferCode = subscriptionPurchaseBlocked? (currentSubscription.effectivePlan?.offer.code ?? null): null;- const selected = useMemo(- () =>- offers.find(- (entry) =>- entry.offer.code === selectedOfferCode &&- isCatalogOfferPurchasable(entry) &&- !(- entry.product.kind === 'SUBSCRIPTION' &&- entry.offer.code === currentSubscriptionOfferCode- ),- ) ?? null,- [currentSubscriptionOfferCode, offers, selectedOfferCode],+ const subscriptionProducts = useMemo(+ () => groupSubscriptionProducts(subscriptionOffers, currentSubscriptionOfferCode),+ [currentSubscriptionOfferCode, subscriptionOffers],);+ const selected = useMemo(() => {+ const entry = offers.find((candidate) => candidate.offer.code === selectedOfferCode) ?? null;+ if (!entry) return null;+ if (entry.product.kind === 'SUBSCRIPTION') {+ return entry.product.code === selectedProductCode ? entry : null;+ }+ return isCatalogOfferPurchasable(entry) ? entry : null;+ }, [offers, selectedOfferCode, selectedProductCode]);const selectedOption = useMemo(() =>selected?.purchaseOptions.find((option) => option.id === selectedPurchaseOptionId) ?? null,[selected, selectedPurchaseOptionId],);+ const selectSubscriptionOffer = useCallback((entry: CatalogOfferEntry) => {+ setSelectedOfferCode(entry.offer.code);+ setSelectedPurchaseOptionId((currentOptionId) =>+ entry.purchaseOptions.some((option) => option.id === currentOptionId)+ ? currentOptionId+ : (entry.purchaseOptions[0]?.id ?? null),+ );+ setCustomAmount('');+ }, []);+useEffect(() => {+ if (selectedProductCode) {+ const selectedProduct = subscriptionProducts.find(+ (product) => product.product.code === selectedProductCode,+ );+ if (!selectedProduct) {+ resetSubscriptionSelection();+ return;+ }+ const selectedEntry = selectedProduct.offers.find(+ (entry) => entry.offer.code === selectedOfferCode,+ );+ if (+ !selectedEntry ||+ (!isSubscriptionOfferSelectable(selectedEntry, currentSubscriptionOfferCode) &&+ selectedEntry.offer.code !== selectedProduct.defaultOffer.offer.code)+ ) {+ selectSubscriptionOffer(selectedProduct.defaultOffer);+ }+ return;+ }+if (!selectedOfferCode) return;const selectedEntry = offers.find(({ offer }) => offer.code === selectedOfferCode);if (!selectedEntry ||- !isCatalogOfferPurchasable(selectedEntry) ||- (selectedEntry.product.kind === 'SUBSCRIPTION' &&- selectedEntry.offer.code === currentSubscriptionOfferCode)+ selectedEntry.product.kind !== 'CREDIT_TOPUP' ||+ !isCatalogOfferPurchasable(selectedEntry)) {resetSelection();}- }, [currentSubscriptionOfferCode, offers, resetSelection, selectedOfferCode]);+ }, [+ currentSubscriptionOfferCode,+ offers,+ resetSelection,+ resetSubscriptionSelection,+ selectSubscriptionOffer,+ selectedOfferCode,+ selectedProductCode,+ subscriptionProducts,+ ]);useEffect(() => {if (!selectedPurchaseOptionId) return;@@ -595,6 +675,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst canCheckout =selected !== null &&+ isCatalogOfferPurchasable(selected) &&selectedOption !== null &&!(selected.product.kind === 'SUBSCRIPTION' &&@@ -750,11 +831,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null// targets.const planChangeCandidates = useMemo<PlanChangeCandidate[]>(() => {if (!showPlanChangeEntry || !currentPlan || !currentProvider) return [];- const directionRank: Record<Exclude<PlanChangeCandidate['direction'], null>, number> = {- UPGRADE: 0,- SAME_LEVEL: 1,- DOWNGRADE: 2,- };return subscriptionOffers.filter((entry) =>@@ -775,21 +851,25 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null: product.level < currentPlan.product.level? ('DOWNGRADE' as const): ('SAME_LEVEL' as const),- }))- .sort(- (left, right) =>- (left.direction === null ? 3 : directionRank[left.direction]) -- (right.direction === null ? 3 : directionRank[right.direction]) ||- left.product.sortOrder - right.product.sortOrder ||- left.offer.code.localeCompare(right.offer.code),- );+ }));}, [subscriptionOffers, showPlanChangeEntry, currentPlan, currentProvider]);const openPurchaseDialog = (kind: PurchaseKind) => {resetSelection();if (kind === 'SUBSCRIPTION') {+ const defaultProduct =+ subscriptionProducts.find((product) =>+ isSubscriptionOfferSelectable(product.defaultOffer, currentSubscriptionOfferCode),+ ) ??+ subscriptionProducts[0] ??+ null;+ setSelectedProductCode(defaultProduct?.product.code ?? null);+ if (defaultProduct) {+ selectSubscriptionOffer(defaultProduct.defaultOffer);+ }setSubscriptionDialogOpen(true);} else {+ setSelectedProductCode(null);setTopupDialogOpen(true);}};@@ -797,13 +877,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst selectOffer = (offerCode: string) => {if (selectedOfferCode === offerCode) return;const entry = offers.find(({ offer }) => offer.code === offerCode);- if (- !entry ||- !isCatalogOfferPurchasable(entry) ||- (entry.product.kind === 'SUBSCRIPTION' && entry.offer.code === currentSubscriptionOfferCode)- ) {+ if (!entry) return;+ if (entry.product.kind === 'SUBSCRIPTION') {+ if (entry.product.code !== selectedProductCode) return;+ selectSubscriptionOffer(entry);return;}+ if (!isCatalogOfferPurchasable(entry)) return;setSelectedOfferCode(offerCode);// 只有一种支付方式时默认选中,免去一次多余点击。setSelectedPurchaseOptionId(@@ -812,6 +892,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetCustomAmount('');};+ const selectSubscriptionProduct = (productCode: string) => {+ const product = subscriptionProducts.find((entry) => entry.product.code === productCode);+ if (!product) return;+ setSelectedProductCode(productCode);+ selectSubscriptionOffer(product.defaultOffer);+ };+const submit = () => {if (!selected || !selectedOption || !canCheckout) return;setSubscriptionDialogOpen(false);@@ -832,7 +919,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst closeSubscriptionDialog = () => {setSubscriptionDialogOpen(false);- resetSelection();+ resetSubscriptionSelection();};const closeTopupDialog = () => {setTopupDialogOpen(false);@@ -992,6 +1079,8 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullopen={subscriptionDialogOpen}kind="SUBSCRIPTION"offers={subscriptionOffers}+ subscriptionProducts={subscriptionProducts}+ selectedProductCode={selectedProductCode}loading={loadingCatalog}catalogError={catalogError}selected={selected?.product.kind === 'SUBSCRIPTION' ? selected : null}@@ -1003,6 +1092,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcanCheckout={canCheckout}onClose={closeSubscriptionDialog}onRetry={() => void loadBillingState()}+ onSelectProduct={selectSubscriptionProduct}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}@@ -1013,6 +1103,8 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullopen={topupDialogOpen}kind="CREDIT_TOPUP"offers={topupOffers}+ subscriptionProducts={[]}+ selectedProductCode={null}loading={loadingCatalog}catalogError={catalogError}selected={selected?.product.kind === 'CREDIT_TOPUP' ? selected : null}@@ -1024,6 +1116,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcanCheckout={canCheckout}onClose={closeTopupDialog}onRetry={() => void loadBillingState()}+ onSelectProduct={() => undefined}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}@@ -1671,6 +1764,8 @@ function BillingOfferDialog({open,kind,offers,+ subscriptionProducts,+ selectedProductCode,loading,catalogError,selected,@@ -1682,6 +1777,7 @@ function BillingOfferDialog({canCheckout,onClose,onRetry,+ onSelectProduct,onSelectOffer,onSelectPurchaseOption,onCustomAmountChange,@@ -1690,6 +1786,8 @@ function BillingOfferDialog({open: boolean;kind: PurchaseKind;offers: CatalogOfferEntry[];+ subscriptionProducts: SubscriptionProductEntry[];+ selectedProductCode: string | null;loading: boolean;catalogError: boolean;selected: CatalogOfferEntry | null;@@ -1701,6 +1799,7 @@ function BillingOfferDialog({canCheckout: boolean;onClose: () => void;onRetry: () => void;+ onSelectProduct: (productCode: string) => void;onSelectOffer: (offerCode: string) => void;onSelectPurchaseOption: (optionId: string) => void;onCustomAmountChange: (amount: string) => void;@@ -1712,6 +1811,22 @@ function BillingOfferDialog({kind === 'SUBSCRIPTION'? t('billing.dialogs.subscription.title'): t('billing.dialogs.topup.title');+ const selectedSubscriptionProduct =+ kind === 'SUBSCRIPTION'+ ? (subscriptionProducts.find((product) => product.product.code === selectedProductCode) ??+ null)+ : null;+ const displayedOffers = selectedSubscriptionProduct?.offers ?? offers;+ const initialTopupOfferCode =+ kind === 'CREDIT_TOPUP'+ ? (displayedOffers.find(isCatalogOfferPurchasable)?.offer.code ?? null)+ : null;+ const selectedOfferCanChooseChannel =+ selected !== null &&+ isCatalogOfferPurchasable(selected) &&+ !(kind === 'SUBSCRIPTION' && selected.offer.code === currentSubscriptionOfferCode);+ const primaryFocusRef = useRef<HTMLButtonElement>(null);+ const closeButtonRef = useRef<HTMLButtonElement>(null);return (<Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>@@ -1725,11 +1840,18 @@ function BillingOfferDialog({'overflow-hidden rounded-xl border border-[var(--border-default)]','bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',)}+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ (primaryFocusRef.current ?? closeButtonRef.current)?.focus();+ }}><div className="flex items-center justify-between gap-4 px-6 pb-4 pt-5">- <Dialog.Title className="text-16 font-medium tracking-[-0.01em]">{title}</Dialog.Title>+ <Dialog.Title className="truncate text-16 font-medium tracking-[-0.01em]">+ {title}+ </Dialog.Title><Dialog.Close asChild><button+ ref={closeButtonRef}type="button"className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"aria-label={t('billing.actions.close')}@@ -1749,6 +1871,7 @@ function BillingOfferDialog({description={t('billing.catalog.errorDescription')}action={<button+ ref={primaryFocusRef}type="button"onClick={onRetry}className="mt-4 h-9 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium hover:bg-[var(--surface-hover-soft)]"@@ -1758,167 +1881,186 @@ function BillingOfferDialog({}/>) : offers.length === 0 ? (- <StateCard- icon={<PackageOpen size={22} />}- title={t('billing.catalog.emptyTitle')}- />+ <StateCard icon={<PackageOpen size={22} />} title={t('billing.catalog.emptyTitle')} />) : (<>- <div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">- {offers.map((entry) => {- const { product, offer } = entry;- const active = selected?.offer.code === offer.code;- const unavailableReason = catalogOfferUnavailableReason(entry);- const currentPlan =- kind === 'SUBSCRIPTION' && offer.code === currentSubscriptionOfferCode;- return (- <button- key={offer.code}- type="button"- onClick={() => onSelectOffer(offer.code)}- disabled={currentPlan || unavailableReason !== null}- aria-pressed={active}- aria-current={currentPlan ? 'true' : undefined}- className={cn(- 'flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--text-primary)]',- 'disabled:cursor-not-allowed disabled:hover:bg-transparent',- currentPlan- ? 'bg-[var(--surface-chip)]'- : unavailableReason- ? 'opacity-55'- : active- ? 'bg-[var(--surface-chip)]'- : 'hover:bg-[var(--surface-hover-soft)]',- )}- >- <div className="min-w-0 flex-1">- <div+ {kind === 'SUBSCRIPTION' && (+ <SubscriptionProductAccordion+ products={subscriptionProducts}+ selectedProductCode={selectedProductCode}+ selectedOfferCode={selected?.offer.code ?? null}+ currentSubscriptionOfferCode={currentSubscriptionOfferCode}+ billingLocale={billingLocale}+ initialFocusRef={primaryFocusRef}+ onSelectProduct={onSelectProduct}+ onSelectOffer={onSelectOffer}+ />+ )}++ <div className={kind === 'SUBSCRIPTION' ? 'mt-4' : undefined}>+ {kind !== 'SUBSCRIPTION' && (+ <div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">+ {displayedOffers.map((entry) => {+ const { product, offer } = entry;+ const active = selected?.offer.code === offer.code;+ const unavailableReason = catalogOfferUnavailableReason(entry);+ const currentPlan = false;+ return (+ <button+ key={offer.code}+ ref={+ offer.code === initialTopupOfferCode ? primaryFocusRef : undefined+ }+ type="button"+ onClick={() => onSelectOffer(offer.code)}+ disabled={currentPlan || unavailableReason !== null}+ aria-pressed={active}+ aria-current={currentPlan ? 'true' : undefined}className={cn(- 'grid items-center gap-2',- currentPlan || unavailableReason- ? 'grid-cols-[6rem_minmax(0,1fr)]'- : 'grid-cols-[minmax(0,1fr)]',+ 'flex min-h-[52px] w-full items-center justify-between gap-4 px-4 py-3',+ 'text-left transition-colors',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',+ 'focus-visible:ring-[var(--focus-ring)]',+ 'disabled:cursor-not-allowed disabled:hover:bg-transparent',+ currentPlan+ ? 'bg-[var(--surface-chip)]'+ : unavailableReason+ ? 'bg-[var(--surface-elevated)] opacity-55'+ : active+ ? 'bg-[var(--surface-hover-soft)]'+ : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',)}>- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {product.name}- </p>- {(currentPlan || unavailableReason) && (- <div className="min-w-0">- {currentPlan && (- <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {t('billing.catalog.currentPlan')}- </span>+ <div className="min-w-0 flex-1">+ <div+ className={cn(+ 'grid items-center gap-2',+ currentPlan || unavailableReason+ ? 'grid-cols-[6rem_minmax(0,1fr)]'+ : 'grid-cols-[minmax(0,1fr)]',)}- {unavailableReason && (- <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {t(`billing.catalog.unavailableReasons.${unavailableReason}`)}- </span>+ >+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">+ {product.name}+ </p>+ {(currentPlan || unavailableReason) && (+ <div className="min-w-0">+ {currentPlan && (+ <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {t('billing.catalog.currentPlan')}+ </span>+ )}+ {unavailableReason && (+ <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {t(+ `billing.catalog.unavailableReasons.${unavailableReason}`,+ )}+ </span>+ )}+ </div>)}</div>- )}- </div>- </div>- <div className="flex shrink-0 items-center gap-3">- <div className="text-right">- <p className="text-13 font-medium tabular-nums text-[var(--text-primary)]">- {offer.amount- ? formatMoney(offer.amount, offer.currency, billingLocale)- : t('billing.amount.custom')}- {offer.interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {t(`billing.intervals.${offer.interval}`)}- </span>+ </div>+ <div className="flex shrink-0 items-center gap-3">+ <div className="text-right">+ <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {offer.amount+ ? formatMoney(offer.amount, offer.currency, billingLocale)+ : t('billing.amount.custom')}+ {offer.interval && (+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">+ / {t(`billing.intervals.${offer.interval}`)}+ </span>+ )}+ </p>+ {offer.creditAmount && (+ <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">+ {t('billing.credits', {+ amount: formatMoney(+ offer.creditAmount,+ offer.currency,+ billingLocale,+ ),+ })}+ </p>+ )}+ </div>+ {!currentPlan && unavailableReason === null && (+ <SelectionMark active={active} />)}- </p>- {offer.creditAmount && (- <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">- {t('billing.credits', {- amount: formatMoney(- offer.creditAmount,- offer.currency,- billingLocale,- ),- })}- </p>- )}- </div>- {!currentPlan && unavailableReason === null && (- <SelectionMark active={active} />- )}- </div>- </button>- );- })}- </div>-- {selected && (- <div className="mt-5">- <h3 className="text-13 font-medium text-[var(--text-primary)]">- {t('billing.steps.channel.title')}- </h3>- <div className="mt-3 divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">- {selected.purchaseOptions.map((option) => (- <PaymentOptionRow- key={option.id}- option={option}- active={selectedPurchaseOptionId === option.id}- onSelect={() => onSelectPurchaseOption(option.id)}- />- ))}+ </div>+ </button>+ );+ })}</div>+ )}- {kind === 'CREDIT_TOPUP' && isCustomTopup(selected.offer) && (- <label className="mt-5 block">- <span className="text-13 font-medium text-[var(--text-primary)]">- {t('billing.amount.label')}- </span>- <div className="mt-2 flex h-10 items-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-4 focus-within:border-[var(--text-primary)]">- <span className="mr-2 text-13 text-[var(--text-tertiary)]">- {selected.offer.currency.toUpperCase()}- </span>- <input- value={customAmount}- onChange={(event) => onCustomAmountChange(event.target.value)}- inputMode="decimal"- placeholder={t('billing.amount.placeholder')}- className="min-w-0 flex-1 bg-transparent text-13 outline-none placeholder:text-[var(--text-placeholder)]"+ {selectedOfferCanChooseChannel && (+ <div className="mt-5">+ <h3 className="text-13 font-medium text-[var(--text-primary)]">+ {t('billing.steps.channel.title')}+ </h3>+ <div className="mt-3 divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">+ {selected!.purchaseOptions.map((option) => (+ <PaymentOptionRow+ key={option.id}+ option={option}+ active={selectedPurchaseOptionId === option.id}+ onSelect={() => onSelectPurchaseOption(option.id)}/>- </div>- <p- className={cn(- 'mt-2 text-11',- amountError- ? 'text-[var(--text-primary)]'- : 'text-[var(--text-tertiary)]',- )}- >- {amountError ??- t('billing.amount.rangeHint', {- min: formatMoney(- selected.offer.minAmount!,- selected.offer.currency,- billingLocale,- ),- max: formatMoney(- selected.offer.maxAmount!,- selected.offer.currency,- billingLocale,- ),- })}- </p>- </label>- )}+ ))}+ </div>- {kind === 'SUBSCRIPTION' && subscriptionPurchaseBlocked && (- <p className="mt-4 text-12 leading-5 text-[var(--text-secondary)]">- {t('billing.currentSubscription.purchaseBlocked')}- </p>- )}- </div>- )}+ {kind === 'CREDIT_TOPUP' && isCustomTopup(selected!.offer) && (+ <label className="mt-5 block">+ <span className="text-13 font-medium text-[var(--text-primary)]">+ {t('billing.amount.label')}+ </span>+ <div className="mt-2 flex h-10 items-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-4 focus-within:border-[var(--text-primary)]">+ <span className="mr-2 text-13 text-[var(--text-tertiary)]">+ {selected!.offer.currency.toUpperCase()}+ </span>+ <input+ value={customAmount}+ onChange={(event) => onCustomAmountChange(event.target.value)}+ inputMode="decimal"+ placeholder={t('billing.amount.placeholder')}+ className="min-w-0 flex-1 bg-transparent text-13 outline-none placeholder:text-[var(--text-placeholder)]"+ />+ </div>+ <p+ className={cn(+ 'mt-2 text-11',+ amountError+ ? 'text-[var(--text-primary)]'+ : 'text-[var(--text-tertiary)]',+ )}+ >+ {amountError ??+ t('billing.amount.rangeHint', {+ min: formatMoney(+ selected!.offer.minAmount!,+ selected!.offer.currency,+ billingLocale,+ ),+ max: formatMoney(+ selected!.offer.maxAmount!,+ selected!.offer.currency,+ billingLocale,+ ),+ })}+ </p>+ </label>+ )}+ </div>+ )}++ {kind === 'SUBSCRIPTION' && selected && subscriptionPurchaseBlocked && (+ <p className="mt-4 text-12 leading-5 text-[var(--text-secondary)]">+ {t('billing.currentSubscription.purchaseBlocked')}+ </p>+ )}+ </div></>)}</div>@@ -1928,7 +2070,7 @@ function BillingOfferDialog({type="button"onClick={onSubmit}disabled={!canCheckout}- className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-13 font-medium text-[var(--surface)] transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] disabled:cursor-not-allowed disabled:opacity-35"+ className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--accent-cta-bg)] px-5 text-13 font-medium text-[var(--accent-pure-cta-fg)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-35 disabled:active:scale-100">{t('billing.actions.pay')}<ArrowRight size={15} />@@ -1940,6 +2082,266 @@ function BillingOfferDialog({);}+function SubscriptionProductAccordion({+ products,+ selectedProductCode,+ selectedOfferCode,+ currentSubscriptionOfferCode,+ billingLocale,+ initialFocusRef,+ onSelectProduct,+ onSelectOffer,+}: {+ products: SubscriptionProductEntry[];+ selectedProductCode: string | null;+ selectedOfferCode: string | null;+ currentSubscriptionOfferCode: string | null;+ billingLocale: string;+ initialFocusRef: RefObject<HTMLButtonElement | null>;+ onSelectProduct: (productCode: string) => void;+ onSelectOffer: (offerCode: string) => void;+}) {+ const { t } = useTranslation();++ return (+ <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">+ {products.map((productEntry, productIndex) => {+ const productActive = productEntry.product.code === selectedProductCode;+ const offerRegionId = `billing-product-${productEntry.product.code}-offers`;+ const singleOfferEntry = productEntry.offers.length === 1 ? productEntry.offers[0] : null;+ const singleOfferCurrentPlan =+ singleOfferEntry?.offer.code === currentSubscriptionOfferCode;+ const singleOfferUnavailableReason = singleOfferEntry+ ? catalogOfferUnavailableReason(singleOfferEntry)+ : null;+ const priceOffer = productEntry.defaultOffer.offer;+ const price = priceOffer.amount+ ? formatMoney(priceOffer.amount, priceOffer.currency, billingLocale)+ : t('billing.amount.custom');+ const interval = priceOffer.interval ? t(`billing.intervals.${priceOffer.interval}`) : null;+ return (+ <section+ key={productEntry.product.code}+ className={cn(productIndex > 0 && 'border-t border-[var(--border-default)]')}+ >+ {singleOfferEntry ? (+ <button+ ref={+ productActive &&+ !singleOfferCurrentPlan &&+ singleOfferUnavailableReason === null+ ? initialFocusRef+ : undefined+ }+ type="button"+ onClick={() => onSelectProduct(productEntry.product.code)}+ disabled={singleOfferCurrentPlan || singleOfferUnavailableReason !== null}+ aria-pressed={productActive}+ aria-current={singleOfferCurrentPlan ? 'true' : undefined}+ className={cn(+ 'flex min-h-[72px] w-full items-center justify-between gap-5 px-4 py-3 text-left transition-colors',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',+ 'focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed',+ singleOfferCurrentPlan+ ? 'bg-[var(--surface-chip)]'+ : singleOfferUnavailableReason !== null+ ? 'bg-[var(--surface-elevated)] opacity-55'+ : productActive+ ? 'bg-[var(--surface-hover-soft)]'+ : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',+ )}+ >+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-13 font-medium text-[var(--text-primary)]">+ {productEntry.product.name}+ </span>+ {(singleOfferCurrentPlan || singleOfferUnavailableReason !== null) && (+ <span className="shrink-0 rounded-full bg-[var(--surface-elevated)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {singleOfferCurrentPlan+ ? t('billing.catalog.currentPlan')+ : t(`billing.catalog.unavailableReasons.${singleOfferUnavailableReason}`)}+ </span>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-3">+ <div className="flex flex-col items-end gap-0.5">+ <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {price}+ {interval && (+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">+ / {interval}+ </span>+ )}+ </p>+ {priceOffer.creditAmount && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t('billing.credits', {+ amount: formatMoney(+ priceOffer.creditAmount,+ priceOffer.currency,+ billingLocale,+ ),+ })}+ </p>+ )}+ </div>+ {!singleOfferCurrentPlan && singleOfferUnavailableReason === null ? (+ <SelectionMark active={productActive} />+ ) : (+ <span className="size-5 shrink-0" aria-hidden />+ )}+ </div>+ </button>+ ) : (+ <button+ type="button"+ onClick={() => onSelectProduct(productEntry.product.code)}+ aria-pressed={productActive}+ aria-expanded={productActive}+ aria-controls={offerRegionId}+ className={cn(+ 'flex min-h-[52px] w-full items-center justify-between gap-3 px-4 text-left transition-colors',+ 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',+ 'focus-visible:ring-[var(--focus-ring)]',+ )}+ >+ <div className="flex min-w-0 items-center gap-2">+ {productActive ? (+ <ChevronUp size={16} className="shrink-0 text-[var(--text-secondary)]" />+ ) : (+ <ChevronRight size={16} className="shrink-0 text-[var(--text-tertiary)]" />+ )}+ <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">+ {productEntry.product.name}+ </span>+ </div>+ {!productActive && (+ <div className="flex flex-col items-end gap-0.5">+ <p className="text-right text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {price}+ {interval && (+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">+ / {interval}+ </span>+ )}+ </p>+ {priceOffer.creditAmount && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t('billing.credits', {+ amount: formatMoney(+ priceOffer.creditAmount,+ priceOffer.currency,+ billingLocale,+ ),+ })}+ </p>+ )}+ </div>+ )}+ </button>+ )}++ {!singleOfferEntry && productActive && (+ <div+ id={offerRegionId}+ className="divide-y divide-[var(--border-default)] border-t border-[var(--border-default)]"+ >+ {productEntry.offers.map((entry) => {+ const { offer } = entry;+ const offerName = offer.name?.trim();+ const unavailableReason = catalogOfferUnavailableReason(entry);+ const currentPlan = offer.code === currentSubscriptionOfferCode;+ const unavailable = unavailableReason !== null;+ const offerActive = offer.code === selectedOfferCode;+ return (+ <button+ key={offer.code}+ ref={+ offerActive && !currentPlan && !unavailable+ ? initialFocusRef+ : undefined+ }+ type="button"+ onClick={() => onSelectOffer(offer.code)}+ disabled={currentPlan || unavailable}+ aria-pressed={offerActive}+ aria-current={currentPlan ? 'true' : undefined}+ className={cn(+ 'flex min-h-[72px] w-full items-center justify-between gap-5 py-3 pl-10 pr-4 text-left transition-colors',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',+ 'focus-visible:ring-[var(--focus-ring)]',+ 'disabled:cursor-not-allowed disabled:hover:bg-transparent',+ currentPlan+ ? 'bg-[var(--surface-chip)]'+ : unavailable+ ? 'bg-[var(--surface-elevated)] opacity-55'+ : offerActive+ ? 'bg-[var(--surface-hover-soft)]'+ : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',+ )}+ >+ <div className="flex min-w-0 items-center">+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-2">+ {offerName && (+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">+ {offerName}+ </p>+ )}+ {(currentPlan || unavailable) && (+ <span className="shrink-0 rounded-full bg-[var(--surface-elevated)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {currentPlan+ ? t('billing.catalog.currentPlan')+ : t(`billing.catalog.unavailableReasons.${unavailableReason}`)}+ </span>+ )}+ </div>+ </div>+ </div>++ <div className="flex shrink-0 items-center gap-3">+ <div className="flex flex-col items-end gap-0.5">+ <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {offer.amount+ ? formatMoney(offer.amount, offer.currency, billingLocale)+ : t('billing.amount.custom')}+ {offer.interval && (+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">+ / {t(`billing.intervals.${offer.interval}`)}+ </span>+ )}+ </p>+ <p className="text-12 text-[var(--text-secondary)]">+ {offer.creditAmount+ ? t('billing.credits', {+ amount: formatMoney(+ offer.creditAmount,+ offer.currency,+ billingLocale,+ ),+ })+ : null}+ </p>+ </div>+ {!currentPlan && !unavailable ? (+ <SelectionMark active={offerActive} />+ ) : (+ <span className="size-5 shrink-0" aria-hidden />+ )}+ </div>+ </button>+ );+ })}+ </div>+ )}+ </section>+ );+ })}+ </div>+ );+}+function CatalogSkeleton() {return (<div@@ -1998,8 +2400,10 @@ function PaymentOptionRow({className={cn('flex w-full items-center gap-3 px-4 py-3 text-left transition-colors','focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--text-primary)]',- active ? 'bg-[var(--surface-chip)]' : 'hover:bg-[var(--surface-hover-soft)]',+ 'focus-visible:ring-[var(--focus-ring)]',+ active+ ? 'bg-[var(--surface-hover-soft)]'+ : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',)}>{option.provider === 'alipay' ? (diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsxindex 1428d5a464..2d00d54817 100644--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx@@ -2,7 +2,9 @@ import { useEffect, useMemo, useRef, useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import * as QRCode from 'qrcode';import {+ ArrowLeft,ArrowDownRight,+ ArrowRight,ArrowUpRight,Check,CircleAlert,@@ -40,6 +42,35 @@ export type PlanChangeCandidate = {direction: 'UPGRADE' | 'SAME_LEVEL' | 'DOWNGRADE' | null;};+type PlanChangeProductGroup = {+ product: BillingCatalogProduct;+ candidates: PlanChangeCandidate[];+ defaultCandidate: PlanChangeCandidate;+};++function groupPlanChangeCandidates(candidates: PlanChangeCandidate[]): PlanChangeProductGroup[] {+ const groups = new Map<+ string,+ { product: BillingCatalogProduct; candidates: PlanChangeCandidate[] }+ >();+ for (const candidate of candidates) {+ const group = groups.get(candidate.product.code);+ if (group) {+ group.candidates.push(candidate);+ } else {+ groups.set(candidate.product.code, {+ product: candidate.product,+ candidates: [candidate],+ });+ }+ }+ return Array.from(groups.values()).map(({ product, candidates }) => ({+ product,+ candidates,+ defaultCandidate: candidates[0],+ }));+}+function formatEffectiveDate(iso: string, locale: string): string {const timestamp = Date.parse(iso);if (!Number.isFinite(timestamp)) return iso;@@ -68,10 +99,70 @@ export function PlanChangeTargetDialog({}) {const { t, i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;- const displayedPlans = [- ...(currentPlan ? [{ candidate: currentPlan, current: true }] : []),- ...candidates.map((candidate) => ({ candidate, current: false })),- ];+ const groups = useMemo(() => groupPlanChangeCandidates(candidates), [candidates]);+ const [selectedProductCode, setSelectedProductCode] = useState<string | null>(null);+ const [selectedOfferCode, setSelectedOfferCode] = useState<string | null>(null);+ const selectedGroup = groups.find((group) => group.product.code === selectedProductCode) ?? null;+ const selectedCandidate =+ selectedGroup?.candidates.find((candidate) => candidate.offer.code === selectedOfferCode) ??+ selectedGroup?.defaultCandidate ??+ null;++ useEffect(() => {+ if (!open) {+ setSelectedProductCode(null);+ setSelectedOfferCode(null);+ return;+ }+ if (!selectedProductCode) return;+ if (!selectedGroup) {+ setSelectedProductCode(null);+ setSelectedOfferCode(null);+ return;+ }+ if (!selectedGroup.candidates.some((candidate) => candidate.offer.code === selectedOfferCode)) {+ setSelectedOfferCode(selectedGroup.defaultCandidate.offer.code);+ }+ }, [open, selectedGroup, selectedOfferCode, selectedProductCode]);++ const selectProduct = (productCode: string) => {+ const group = groups.find((candidate) => candidate.product.code === productCode);+ if (!group) return;+ setSelectedProductCode(productCode);+ setSelectedOfferCode(group.defaultCandidate.offer.code);+ };++ const backToProducts = () => {+ setSelectedProductCode(null);+ setSelectedOfferCode(null);+ };++ const renderAmount = (candidate: PlanChangeCandidate) => (+ <div className="shrink-0 text-right">+ <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">+ {candidate.offer.amount+ ? formatMoney(candidate.offer.amount, candidate.offer.currency, billingLocale)+ : '—'}+ {candidate.offer.interval && (+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">+ / {t(`billing.intervals.${candidate.offer.interval}`)}+ </span>+ )}+ </p>+ {candidate.offer.creditAmount && (+ <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">+ {t('billing.credits', {+ amount: formatMoney(+ candidate.offer.creditAmount,+ candidate.offer.currency,+ billingLocale,+ ),+ })}+ </p>+ )}+ </div>+ );+return (<Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}><Dialog.Portal>@@ -86,9 +177,11 @@ export function PlanChangeTargetDialog({)}><div className="flex items-center justify-between gap-4 px-6 pb-4 pt-5">- <Dialog.Title className="text-16 font-medium tracking-[-0.01em]">- {t('billing.planChange.targetTitle')}- </Dialog.Title>+ <div className="flex min-w-0 items-center gap-2">+ <Dialog.Title className="truncate text-16 font-medium tracking-[-0.01em]">+ {selectedGroup?.product.name ?? t('billing.planChange.targetTitle')}+ </Dialog.Title>+ </div><Dialog.Close asChild><buttontype="button"@@ -101,107 +194,184 @@ 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]">- {displayedPlans.length > 0 && (+ {selectedGroup ? (<div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">- {displayedPlans.map(({ candidate, current }) => {- const DirectionIcon =- candidate.direction === 'UPGRADE'- ? ArrowUpRight- : candidate.direction === 'DOWNGRADE'- ? ArrowDownRight- : null;- const directionLabel =- 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(', ');+ {selectedGroup.candidates.map((candidate) => {+ const active = selectedCandidate?.offer.code === candidate.offer.code;+ const offerName = candidate.offer.name?.trim();return (<buttonkey={candidate.offer.code}type="button"- disabled={current}- aria-current={current ? 'true' : undefined}- onClick={() => {- if (!current) onSelect(candidate);- }}+ aria-pressed={active}+ onClick={() => setSelectedOfferCode(candidate.offer.code)}className={cn(- 'flex w-full items-center justify-between gap-4 px-4 py-3 text-left',- !current && 'transition-colors hover:bg-[var(--surface-hover-soft)]',+ 'flex min-h-[72px] w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors','focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--text-primary)]',+ 'focus-visible:ring-[var(--focus-ring)]',+ active+ ? 'bg-[var(--surface-hover-soft)]'+ : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',)}><div className="min-w-0 flex-1">- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {candidate.product.name}- </p>- {(directionLabel || providerLabel) && (- <p className="mt-0.5 flex min-h-4 items-center gap-1 text-11 text-[var(--text-tertiary)]">- {DirectionIcon && <DirectionIcon size={12} />}- {directionLabel && <span>{directionLabel}</span>}- {directionLabel && providerLabel && <span aria-hidden>·</span>}- {providerLabel && <span>{providerLabel}</span>}+ {offerName && (+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">+ {offerName}</p>)}</div>- <div className="shrink-0 text-right">- <p className="text-13 font-medium tabular-nums text-[var(--text-primary)]">- {candidate.offer.amount- ? formatMoney(- candidate.offer.amount,- candidate.offer.currency,- billingLocale,- )- : '—'}- {candidate.offer.interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {t(`billing.intervals.${candidate.offer.interval}`)}- </span>+ <div className="flex shrink-0 items-center gap-3">+ {renderAmount(candidate)}+ <span+ className={cn(+ 'grid size-5 shrink-0 place-items-center rounded-full border',+ active+ ? 'border-[var(--text-primary)] bg-[var(--text-primary)] text-[var(--surface)]'+ : 'border-[var(--border-default)]',)}- </p>- {candidate.offer.creditAmount && (- <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">- {t('billing.credits', {- amount: formatMoney(- candidate.offer.creditAmount,- candidate.offer.currency,- billingLocale,- ),- })}- </p>- )}+ >+ {active && <Check size={12} strokeWidth={2.5} />}+ </span></div></button>);})}</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',+ ) : (+ <>+ {currentPlan && (+ <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">+ <div className="flex w-full items-center justify-between gap-4 bg-[var(--surface-chip)] px-4 py-3 text-left">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">+ {currentPlan.product.name}+ </p>+ <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {t('billing.catalog.currentPlan')}+ </span>+ </div>+ </div>+ {renderAmount(currentPlan)}+ </div>+ </div>)}- >- <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>++ {groups.length > 0 && (+ <div+ className={cn(+ 'divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]',+ currentPlan && 'mt-4',+ )}+ >+ {groups.map((group) => {+ const candidate = group.defaultCandidate;+ const hasMultipleOffers = group.candidates.length > 1;+ const DirectionIcon =+ candidate.direction === 'UPGRADE'+ ? ArrowUpRight+ : candidate.direction === 'DOWNGRADE'+ ? 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;+ const providerLabel = candidate.providers+ .map((provider) => t(`billing.providers.${provider}`))+ .join(', ');+ return (+ <button+ key={group.product.code}+ type="button"+ onClick={() => {+ if (hasMultipleOffers) {+ selectProduct(group.product.code);+ } else {+ 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)] focus-visible:outline-none',+ 'focus-visible:ring-2 focus-visible:ring-inset',+ 'focus-visible:ring-[var(--focus-ring)]',+ )}+ >+ <div className="min-w-0 flex-1">+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">+ {group.product.name}+ </p>+ {(DirectionIcon || directionLabel || providerLabel) && (+ <p className="mt-0.5 flex min-h-4 items-center gap-1 text-11 text-[var(--text-tertiary)]">+ {DirectionIcon && <DirectionIcon size={12} />}+ {directionLabel && <span>{directionLabel}</span>}+ {directionLabel && providerLabel && <span aria-hidden>·</span>}+ {providerLabel && <span>{providerLabel}</span>}+ </p>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-3">+ {renderAmount(candidate)}+ {hasMultipleOffers && (+ <ArrowRight size={16} className="text-[var(--text-tertiary)]" />+ )}+ </div>+ </button>+ );+ })}+ </div>+ )}++ {groups.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',+ currentPlan && '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>++ {selectedGroup && (+ <div className="flex min-h-16 items-center justify-between gap-4 border-t border-[var(--border-default)] px-6 py-3">+ <button+ type="button"+ onClick={backToProducts}+ className="inline-flex h-9 items-center gap-1.5 rounded-md px-1 text-13 font-medium text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <ArrowLeft size={15} />+ {t('billing.planChange.back')}+ </button>+ <button+ type="button"+ disabled={selectedCandidate === null}+ onClick={() => {+ if (selectedCandidate) onSelect(selectedCandidate);+ }}+ className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--accent-cta-bg)] px-5 text-13 font-medium text-[var(--accent-pure-cta-fg)] transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] disabled:cursor-not-allowed disabled:opacity-35"+ >+ {t('billing.settings.subscriptionCard.changeAction')}+ <ArrowUpRight size={15} />+ </button>+ </div>+ )}</Dialog.Content></Dialog.Portal></Dialog.Root>@@ -430,7 +600,11 @@ export function PlanChangeStatusDialog({>{qrDataUrl ? (<>- <img src={qrDataUrl} className="size-full" alt={t('billing.checkout.qrAlt')} />+ <img+ src={qrDataUrl}+ className="size-full"+ alt={t('billing.checkout.qrAlt')}+ /><spanaria-hidden="true"className="pointer-events-none absolute grid size-10 place-items-center rounded-lg bg-white p-1"diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex cd53fc423d..3326447ec3 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -112,10 +112,7 @@ beforeEach(() => {async function openSubscriptionManagementMenu() {const trigger = await screen.findByText('billing.settings.subscriptionCard.manageAction');- fireEvent.pointerDown(- trigger.closest('button')!,- { button: 0, ctrlKey: false },- );+ fireEvent.pointerDown(trigger.closest('button')!, { button: 0, ctrlKey: false });await screen.findByRole('menu');}@@ -556,6 +553,11 @@ describe('BillingPage remote catalog rendering', () => {}).format(100);expect(offerButtons[0].textContent).toContain(twenty);expect(offerButtons[1].textContent).toContain(hundred);+ expect(offerButtons[0].parentElement?.className).toContain('divide-y');+ expect(offerButtons[0].parentElement?.className).toContain('rounded-xl');+ expect(+ within(offerButtons[0]).getByText(`billing.credits:{"amount":"${twenty}"}`),+ ).toBeTruthy();});it('shows an end date for period-end cancellation and omits invalid dates', async () => {@@ -894,12 +896,18 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.queryByText('alipay')).toBeNull();expect(screen.queryByText('stripe')).toBeNull();- fireEvent.click(screen.getByText('Configured top-up').closest('button')!);+ const configuredTopup = screen.getByText('Configured top-up').closest('button')!;+ fireEvent.click(configuredTopup);+ expect(configuredTopup.getAttribute('aria-pressed')).toBe('true');+ expect(configuredTopup.className).not.toContain('shadow-[inset');expect(await screen.findByText('alipay')).toBeTruthy();expect(screen.queryByText('unknown_provider')).toBeNull();expect(screen.queryByText('stripe')).toBeNull();- fireEvent.click(screen.getByText('alipay').closest('button')!);+ const alipayOption = screen.getByText('alipay').closest('button')!;+ fireEvent.click(alipayOption);+ expect(alipayOption.getAttribute('aria-pressed')).toBe('true');+ expect(alipayOption.className).not.toContain('shadow-[inset');fireEvent.change(screen.getByPlaceholderText('billing.amount.placeholder'), {target: { value: '1.001' },});@@ -951,7 +959,56 @@ describe('BillingPage remote catalog rendering', () => {expect(checkout.startSubscription).not.toHaveBeenCalled();});- it('marks the current subscription offer and prevents selecting it again', async () => {+ it('keeps a Product enterable when its current Offer has another Offer', async () => {+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ code: 'plus',+ name: 'Configured subscription',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [+ {+ code: 'plus_month',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '9',+ minAmount: null,+ maxAmount: null,+ creditAmount: '100',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'plus_month_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ {+ code: 'plus_month_more',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '20',+ minAmount: null,+ maxAmount: null,+ creditAmount: '250',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'plus_month_more_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ ],+ },+ ],+ }));window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({subscription: {subscriptionId: 'subscription_fixture',@@ -981,17 +1038,291 @@ describe('BillingPage remote catalog rendering', () => {await selectSubscriptionManagementAction('billing.settings.subscriptionCard.action');const dialog = await screen.findByRole('dialog');- const currentPlan = within(dialog).getByRole('button', { name: /Configured subscription/ });+ const product = within(dialog).getByRole('button', { name: /Configured subscription/ });+ expect(product).toHaveProperty('disabled', false);+ const currentPlan = within(dialog).getByText('billing.catalog.currentPlan').closest('button')!;+ const alternativeOffer = within(dialog).getByText('$20.00').closest('button')!;+ const alternativeCredits = new Intl.NumberFormat('en', {+ style: 'currency',+ currency: 'USD',+ }).format(250);+ expect(+ within(alternativeOffer).getByText(+ `billing.credits:{"amount":"${alternativeCredits}"}`,+ ).className,+ ).toContain('text-12');+ expect(within(dialog).queryByText('plus_month_more')).toBeNull();expect(currentPlan).toHaveProperty('disabled', true);expect(currentPlan.getAttribute('aria-current')).toBe('true');- expect(within(dialog).getByText('billing.catalog.currentPlan')).toBeTruthy();- expect(within(dialog).queryByText('billing.steps.channel.title')).toBeNull();- expect(within(dialog).queryByText('stripe')).toBeNull();+ expect(alternativeOffer).toHaveProperty('disabled', false);+ expect(alternativeOffer.getAttribute('aria-pressed')).toBe('true');+ expect(alternativeOffer.className).not.toContain('shadow-[inset');+ expect(within(dialog).getByText('billing.steps.channel.title')).toBeTruthy();+ expect(within(dialog).getByText('stripe')).toBeTruthy();- fireEvent.click(currentPlan);expect(checkout.startSubscription).not.toHaveBeenCalled();});+ it('defaults within a Product and keeps unavailable state at the Offer level', async () => {+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ code: 'pro',+ name: 'Pro',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [+ {+ code: 'pro_month_current',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '9',+ minAmount: null,+ maxAmount: null,+ creditAmount: '100',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'pro_current_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ {+ code: 'pro_month_more',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '20',+ minAmount: null,+ maxAmount: null,+ creditAmount: '250',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'pro_more_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ ],+ },+ {+ code: 'future',+ name: 'Coming Soon',+ kind: 'SUBSCRIPTION' as const,+ level: 2,+ sortOrder: 2,+ offers: [+ {+ code: 'future_month',+ salesState: 'COMING_SOON' as const,+ purchasable: false,+ unavailableReason: 'OFFER_COMING_SOON' as const,+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '30',+ minAmount: null,+ maxAmount: null,+ creditAmount: '500',+ rolloverCap: '0',+ purchaseOptions: [],+ },+ ],+ },+ ],+ }));+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({ subscription: null }));++ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));++ const dialog = await screen.findByRole('dialog');+ const defaultOffer = within(dialog).getByText('$9.00').closest('button')!;+ await waitFor(() =>+ expect(document.activeElement).toBe(defaultOffer),+ );+ const proProduct = within(dialog).getByRole('button', { name: /Pro/ });+ const futureProduct = within(dialog).getByRole('button', { name: /Coming Soon/ });+ expect(proProduct).toHaveProperty('disabled', false);+ expect(proProduct.closest('section')?.parentElement?.className).toContain('rounded-xl');+ expect(proProduct.closest('section')?.className).not.toContain('border-[var(--text-primary)]');+ expect(futureProduct).toHaveProperty('disabled', true);+ expect(+ within(futureProduct).getByText('billing.catalog.unavailableReasons.OFFER_COMING_SOON'),+ ).toBeTruthy();++ const secondOffer = within(dialog).getByText('$20.00').closest('button')!;+ const defaultCredits = new Intl.NumberFormat('en', {+ style: 'currency',+ currency: 'USD',+ }).format(100);+ expect(+ within(defaultOffer).getByText(`billing.credits:{"amount":"${defaultCredits}"}`),+ ).toBeTruthy();+ expect(within(dialog).queryByText('pro_month_current')).toBeNull();+ expect(within(dialog).queryByText('pro_month_more')).toBeNull();+ expect(defaultOffer).toHaveProperty('disabled', false);+ expect(defaultOffer.getAttribute('aria-pressed')).toBe('true');+ expect(defaultOffer.firstElementChild?.querySelector('svg')).toBeNull();+ expect(defaultOffer.lastElementChild?.querySelector('svg')).toBeTruthy();+ expect(secondOffer.getAttribute('aria-pressed')).toBe('false');++ fireEvent.click(secondOffer);+ expect(secondOffer.getAttribute('aria-pressed')).toBe('true');+ expect(secondOffer.className).not.toContain('shadow-[inset');+ });++ it('shows the server-default Offer price when a Product is collapsed', async () => {+ const offer = (code: string, amount: string) => ({+ code,+ interval: 'MONTH' as const,+ currency: 'usd',+ amount,+ minAmount: null,+ maxAmount: null,+ creditAmount: amount,+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: `${code}_stripe`,+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ });+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ code: 'pro',+ name: 'Pro',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [offer('pro_default', '20'), offer('pro_cheaper', '9')],+ },+ {+ code: 'basic',+ name: 'Basic',+ kind: 'SUBSCRIPTION' as const,+ level: 0,+ sortOrder: 2,+ offers: [offer('basic_default', '5')],+ },+ ],+ }));+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({ subscription: null }));++ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));++ const dialog = await screen.findByRole('dialog');+ const defaultOffer = within(dialog).getByText('$20.00').closest('button')!;+ expect(defaultOffer.getAttribute('aria-pressed')).toBe('true');++ fireEvent.click(within(dialog).getByRole('button', { name: /Basic/ }));+ const collapsedProduct = within(dialog).getByRole('button', { name: /Pro/ });+ expect(within(collapsedProduct).getByText('$20.00')).toBeTruthy();+ expect(within(collapsedProduct).queryByText('$9.00')).toBeNull();+ expect(within(collapsedProduct).queryByText(/billing\.amount\.startingAt/)).toBeNull();+ });++ it('reselects the first valid Offer in the same Product after a catalog refresh', async () => {+ const firstOffer = {+ code: 'pro_month',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '9',+ minAmount: null,+ maxAmount: null,+ creditAmount: '100',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'pro_month_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ };+ const secondOffer = {+ ...firstOffer,+ code: 'pro_month_more',+ amount: '20',+ creditAmount: '250',+ purchaseOptions: [+ {+ ...firstOffer.purchaseOptions[0],+ id: 'pro_month_more_stripe',+ },+ ],+ };+ const product = {+ code: 'pro',+ name: 'Pro',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [firstOffer, secondOffer],+ };+ const otherProduct = {+ code: 'basic',+ name: 'Basic',+ kind: 'SUBSCRIPTION' as const,+ level: 0,+ sortOrder: 2,+ offers: [+ {+ ...firstOffer,+ code: 'basic_month',+ amount: '5',+ creditAmount: '50',+ purchaseOptions: [+ {+ ...firstOffer.purchaseOptions[0],+ id: 'basic_month_stripe',+ },+ ],+ },+ ],+ };+ window.electronAPI.billing.getCatalog = vi+ .fn()+ .mockResolvedValueOnce({ products: [product, otherProduct] })+ .mockResolvedValueOnce({ products: [{ ...product, offers: [firstOffer] }, otherProduct] })+ .mockResolvedValueOnce({ products: [otherProduct] });+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({ subscription: null }));++ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));++ const dialog = await screen.findByRole('dialog');+ fireEvent.click(within(dialog).getByRole('button', { name: /Pro/ }));+ const secondOfferButton = within(dialog).getByText('$20.00').closest('button')!;+ fireEvent.click(secondOfferButton);+ expect(secondOfferButton.getAttribute('aria-pressed')).toBe('true');++ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ await waitFor(() =>+ expect(+ within(dialog).getByText('$9.00').closest('button')?.getAttribute('aria-pressed'),+ ).toBe('true'),+ );+ expect(within(dialog).queryByText('pro_month')).toBeNull();+ expect(within(dialog).queryByText('$20.00')).toBeNull();++ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ await waitFor(() => expect(within(dialog).getByRole('button', { name: /Basic/ })).toBeTruthy());+ expect(within(dialog).queryByLabelText('settings.back')).toBeNull();+ expect(within(dialog).queryByText('$9.00')).toBeNull();+ });+it.each(['INCOMPLETE', 'CANCELED', 'INCOMPLETE_EXPIRED'] as const)('does not treat a %s response as the current subscription',async (status) => {@@ -1010,9 +1341,7 @@ describe('BillingPage remote catalog rendering', () => {}));render(<BillingPage />);- expect(- await screen.findByText('billing.settings.subscriptionCard.emptyTitle'),- ).toBeTruthy();+ 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'));@@ -1093,7 +1422,7 @@ describe('BillingPage remote catalog rendering', () => {).toHaveProperty('disabled', true);});- it('renders multiple remote subscription offers as independent choices', async () => {+ it('renders single-Offer subscription Products as direct rows', async () => {window.electronAPI.billing.getCatalog = vi.fn(async () => ({products: (['alipay', 'stripe', 'alipay'] as const).map((provider, index) => ({code: `plan_${index + 1}`,@@ -1134,13 +1463,41 @@ describe('BillingPage remote catalog rendering', () => {const planButtons = await screen.findAllByRole('button', { name: /Remote plan/ });expect(planButtons).toHaveLength(3);expect(planButtons.map((button) => button.getAttribute('aria-pressed'))).toEqual([+ 'true','false','false',- 'false',]);+ expect(planButtons.map((button) => button.getAttribute('aria-expanded'))).toEqual([+ null,+ null,+ null,+ ]);+ expect(within(planButtons[0]).getByText(/1\.00/)).toBeTruthy();+ expect(within(planButtons[0]).queryByText(/billing\.amount\.startingAt/)).toBeNull();+ const firstPlanCredits = new Intl.NumberFormat('en', {+ style: 'currency',+ currency: 'CNY',+ }).format(100);+ expect(+ within(planButtons[0]).getByText(`billing.credits:{"amount":"${firstPlanCredits}"}`),+ ).toBeTruthy();+ expect(screen.queryByText('plan_1_month')).toBeNull();+ expect(screen.getByText('alipay')).toBeTruthy();+ expect(screen.queryByText('stripe')).toBeNull();fireEvent.click(planButtons[1]);- expect(planButtons[1].getAttribute('aria-pressed')).toBe('true');+ expect(screen.queryByText('plan_1_month')).toBeNull();+ expect(+ (await screen.findAllByRole('button', { name: /Remote plan/ })).map((button) =>+ button.getAttribute('aria-pressed'),+ ),+ ).toEqual(['false', 'true', 'false']);+ expect(+ screen+ .getAllByRole('button', { name: /Remote plan/ })+ .map((button) => button.getAttribute('aria-expanded')),+ ).toEqual([null, null, null]);+ expect(screen.queryByText('plan_2_month')).toBeNull();expect(await screen.findByText('stripe')).toBeTruthy();expect(screen.queryByText('alipay')).toBeNull();});@@ -1453,9 +1810,10 @@ describe('BillingPage plan change', () => {const billing = install(billingMocks());let resolvePortal!: (result: BillingSubscriptionPortalResult) => void;billing.openSubscriptionPortal.mockImplementation(- () => new Promise<BillingSubscriptionPortalResult>((resolve) => {- resolvePortal = resolve;- }),+ () =>+ new Promise<BillingSubscriptionPortalResult>((resolve) => {+ resolvePortal = resolve;+ }),);render(<BillingPage />);@@ -1502,7 +1860,9 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.portalAction');await waitFor(() => {- expect(uiMocks.toastError).toHaveBeenCalledWith('billing.settings.subscriptionCard.portalFailed');+ expect(uiMocks.toastError).toHaveBeenCalledWith(+ 'billing.settings.subscriptionCard.portalFailed',+ );});const catalogCalls = billing.getCatalog.mock.calls.length;@@ -1758,7 +2118,7 @@ describe('BillingPage plan change', () => {).toBeTruthy();});- it('offers same-provider monthly plans in upgrade, same-tier, downgrade order', async () => {+ it('offers same-provider monthly Products in Catalog order', async () => {const billing = install(billingMocks());billing.quotePlanChange.mockResolvedValue({planChangeId: 'plan_change_1',@@ -1776,7 +2136,6 @@ describe('BillingPage plan change', () => {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')!;@@ -1787,9 +2146,7 @@ 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(dialog).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();@@ -1824,6 +2181,87 @@ describe('BillingPage plan change', () => {expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2);});+ it('quotes the selected same-Product monthly Offer', async () => {+ const billing = billingMocks();+ billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ code: 'plus',+ name: 'Plus plan',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [+ {+ code: 'plus_month',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '9',+ minAmount: null,+ maxAmount: null,+ creditAmount: '100',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'listing_plus_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ {+ code: 'plus_month_more',+ interval: 'MONTH' as const,+ currency: 'usd',+ amount: '20',+ minAmount: null,+ maxAmount: null,+ creditAmount: '250',+ rolloverCap: '0',+ purchaseOptions: [+ {+ id: 'listing_plus_more_stripe',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ ],+ },+ ],+ }));+ billing.quotePlanChange.mockResolvedValue({+ planChangeId: 'plan_change_1',+ changeType: 'UPGRADE',+ status: 'QUOTED',+ quotedAmountMinor: 1100,+ quotedCurrency: 'usd',+ quoteExpiresAt: '2099-01-01T00:00:00.000Z',+ effectiveAt: '2026-07-24T00:00:00.000Z',+ paymentAction: null,+ });+ install(billing);++ render(<BillingPage />);+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');++ const productButton = screen+ .getAllByText('Plus plan')+ .map((element) => element.closest('button'))+ .find((button): button is HTMLButtonElement => button !== null)!;+ expect(productButton).toHaveProperty('disabled', false);+ fireEvent.click(productButton);++ await waitFor(() =>+ expect(billing.quotePlanChange).toHaveBeenCalledWith({+ targetOfferCode: 'plus_month_more',+ idempotencyKey: 'desktop:plan-change:00000000-0000-4000-8000-000000000042',+ }),+ );+ });+it('opens a Stripe plan-change redirect automatically once and keeps the manual fallback', async () => {const billing = install(billingMocks());const url = 'https://checkout.stripe.com/c/pay/plan_change_fixture';@@ -1884,14 +2322,9 @@ describe('BillingPage plan change', () => {await selectSubscriptionManagementAction('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.00"}'),- ).toBeTruthy();+ expect(within(dialog).getByText('billing.catalog.currentPlan')).toBeTruthy();+ expect(within(dialog).getByText('$7.00')).toBeTruthy();+ expect(within(dialog).getByText('billing.credits:{"amount":"$80.00"}')).toBeTruthy();});it('does not expose plan change for yearly subscriptions while server v1 is monthly-only', async () => {@@ -1973,9 +2406,9 @@ describe('BillingPage plan change', () => {it('keeps new selection enabled when no current subscription exists (no INCOMPLETE task)', async () => {// 服务端不再把未支付的首购作为“当前订阅”下发;页面必须允许正常重新选择。const billing = billingMocks();- billing.getCurrentSubscription = vi.fn(- async () => ({ subscription: null }),- ) as unknown as typeof billing.getCurrentSubscription;+ billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: null,+ })) as unknown as typeof billing.getCurrentSubscription;install(billing);render(<BillingPage />);@@ -1994,9 +2427,9 @@ describe('BillingPage plan change', () => {it('stops treating the abandoned checkout subscription as current when the dialog closes', async () => {const billing = billingMocks();- billing.getCurrentSubscription = vi.fn(- async () => ({ subscription: null }),- ) as unknown as typeof billing.getCurrentSubscription;+ billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: null,+ })) as unknown as typeof billing.getCurrentSubscription;install(billing);Object.assign(checkout.state, {open: true,@@ -2023,7 +2456,9 @@ describe('BillingPage plan change', () => {fireEvent.click(await screen.findByLabelText('billing.actions.close'));expect(checkout.close).toHaveBeenCalled();- await waitFor(() => expect(billing.getCurrentSubscription.mock.calls.length).toBeGreaterThan(1));+ await waitFor(() =>+ expect(billing.getCurrentSubscription.mock.calls.length).toBeGreaterThan(1),+ );fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);fireEvent.click(screen.getByText('stripe').closest('button')!);diff --git a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsxindex 29657cb057..f6aad2a2a7 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx@@ -14,8 +14,12 @@ vi.mock('qrcode', () => ({toDataURL: vi.fn(async () => 'data:image/png;base64,fixture'),}));-import { PlanChangeStatusDialog } from '../PlanChangeDialog';import * as QRCode from 'qrcode';+import {+ PlanChangeStatusDialog,+ PlanChangeTargetDialog,+ type PlanChangeCandidate,+} from '../PlanChangeDialog';import type { PlanChangeState } from '../usePlanChange';function quoteReadyState(overrides: Partial<PlanChangeState> = {}): PlanChangeState {@@ -164,3 +168,175 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {expect(onReselect).toHaveBeenCalledTimes(1);});});++describe('PlanChangeTargetDialog product-first selection', () => {+ const currentPlan: PlanChangeCandidate = {+ product: {+ code: 'pro',+ name: 'Pro',+ kind: 'SUBSCRIPTION',+ level: 1,+ sortOrder: 1,+ offers: [],+ },+ offer: {+ code: 'pro_month',+ interval: 'MONTH',+ currency: 'usd',+ amount: '9',+ minAmount: null,+ maxAmount: null,+ creditAmount: '100',+ rolloverCap: '0',+ purchaseOptions: [],+ },+ providers: ['stripe'],+ direction: null,+ };++ const candidates: PlanChangeCandidate[] = [+ {+ ...currentPlan,+ offer: {+ ...currentPlan.offer,+ code: 'pro_month_more',+ amount: '20',+ creditAmount: '250',+ },+ direction: 'SAME_LEVEL',+ },+ {+ product: {+ code: 'max',+ name: 'Max',+ kind: 'SUBSCRIPTION',+ level: 2,+ sortOrder: 2,+ offers: [],+ },+ offer: {+ code: 'max_month',+ interval: 'MONTH',+ currency: 'usd',+ amount: '20',+ minAmount: null,+ maxAmount: null,+ creditAmount: '250',+ rolloverCap: '0',+ purchaseOptions: [],+ },+ providers: ['stripe'],+ direction: 'UPGRADE',+ },+ {+ product: {+ code: 'max',+ name: 'Max',+ kind: 'SUBSCRIPTION',+ level: 2,+ sortOrder: 2,+ offers: [],+ },+ offer: {+ code: 'max_month_more',+ interval: 'MONTH',+ currency: 'usd',+ amount: '200',+ minAmount: null,+ maxAmount: null,+ creditAmount: '3000',+ rolloverCap: '0',+ purchaseOptions: [],+ },+ providers: ['stripe'],+ direction: 'UPGRADE',+ },+ ];++ it('submits a Product with one alternative Offer directly', () => {+ const onSelect = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={candidates}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );++ const proProduct = screen+ .getAllByText('Pro')+ .map((element) => element.closest('button'))+ .find((button): button is HTMLButtonElement => button !== null)!;+ expect(proProduct).toHaveProperty('disabled', false);+ fireEvent.click(proProduct);+ expect(onSelect).toHaveBeenCalledWith(candidates[0]);+ });++ it('defaults to the first Offer in server order and lets the user switch before submitting', () => {+ const onSelect = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={candidates}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );++ fireEvent.click(screen.getByText('Max').closest('button')!);++ const firstOffer = screen.getByText('$20.00').closest('button')!;+ const secondOffer = screen.getByText('$200.00').closest('button')!;+ expect(screen.queryByText('max_month')).toBeNull();+ expect(screen.queryByText('max_month_more')).toBeNull();+ expect(firstOffer.getAttribute('aria-pressed')).toBe('true');+ expect(secondOffer.getAttribute('aria-pressed')).toBe('false');+ expect(screen.getByText('billing.planChange.back').closest('button')).toBeTruthy();++ const submitButton = screen+ .getByText('billing.settings.subscriptionCard.changeAction')+ .closest('button')!;+ expect(submitButton.className).toContain('bg-[var(--accent-cta-bg)]');+ expect(submitButton.className).toContain('text-[var(--accent-pure-cta-fg)]');++ fireEvent.click(secondOffer);+ fireEvent.click(submitButton);+ expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ });++ it('returns to the Product list when the selected Product disappears', async () => {+ const view = render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={candidates}+ onClose={vi.fn()}+ onSelect={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText('Max').closest('button')!);+ expect(screen.getByText('$200.00')).toBeTruthy();++ view.rerender(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[candidates[0]]}+ onClose={vi.fn()}+ onSelect={vi.fn()}+ />,+ );++ expect(await screen.findByText('billing.planChange.targetTitle')).toBeTruthy();+ const proProduct = screen+ .getAllByText('Pro')+ .map((element) => element.closest('button'))+ .find((button): button is HTMLButtonElement => button !== null)!;+ expect(proProduct).toHaveProperty('disabled', false);+ expect(screen.queryByLabelText('settings.back')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7993bc56c9..b59bf1b42e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8721,7 +8721,7 @@},"catalog": {"errorTitle": "Plans are temporarily unavailable",- "errorDescription": "Check your connection and retry. Local fallback plans will not be used.",+ "errorDescription": "Check your connection and try again.","emptyTitle": "Coming soon. Stay tuned.","currentPlan": "Current Plan","unavailableReasons": {@@ -8785,7 +8785,7 @@"openPayment": "Open payment page","refreshingAction": "Loading payment instructions…","paymentCompleted": "Your payment was completed.",- "requestFailed": "The request failed. Retry safely; an uncertain create result keeps the original idempotency key.",+ "requestFailed": "The request failed. Try again later.","expiredBody": "This payment link expired. Create a new payment to continue.","actionExpiredBody": "This code expired. Close this window and choose again to generate a new one.","canceledBody": "This payment was canceled.",@@ -8793,16 +8793,17 @@},"planChange": {"targetTitle": "Change subscription plan",+ "back": "Back","upgradeBadge": "Upgrade","sameLevelBadge": "Same tier","downgradeBadge": "Downgrade","emptyTitle": "No plans available to switch to",- "emptyDescription": "The server has not configured another plan for your current payment method.",+ "emptyDescription": "There are no other plans available to switch to.","quotingTitle": "Preparing plan change",- "quotingBody": "Fetching the price and effective time from the server…",+ "quotingBody": "Confirming the price and effective time…","quoteTitle": "Confirm plan change","confirmingTitle": "Submitting plan change",- "confirmingBody": "Submitting your plan change to the server…",+ "confirmingBody": "Submitting your plan change…","pendingProviderTitle": "Processing plan change","pendingProviderBody": "The payment provider is processing this change. Cindy will keep checking the result…","awaitingTitle": "Pay the difference",@@ -8819,7 +8820,7 @@"requestFailed": "The plan change request couldn’t be completed. Refresh your subscription status and try again.","quoteRejected": "This plan isn’t available for your current subscription. Choose another plan.","chooseAnotherPlan": "Choose Another Plan",- "resyncHint": "The confirmation result could not be verified. Syncing the latest status from the server…",+ "resyncHint": "The result could not be confirmed yet. Checking the latest status again…","upgradeDueNow": "Pay {{amount}} now for the remainder of this period","upgradeNoAmount": "The upgrade takes effect immediately after confirmation.","upgradeHint": "The upgrade takes effect immediately after payment. The renewal price becomes the new plan price.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 79496e5b59..7c21f63c5b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8652,7 +8652,7 @@"remaining": "残り","progressLabel": "{{label}}の使用量","noPlanCredits": "有効なサブスクリプションがないため、プラン残高はありません。",- "historyUnavailable": "使用履歴が完全ではないため、残高のみ表示しています。",+ "historyUnavailable": "使用履歴が完全ではないため、残りの残高のみ表示しています。","detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。","promotionalDetails": {"title": "特典残高明細",@@ -8708,7 +8708,7 @@},"catalog": {"errorTitle": "プランを取得できません",- "errorDescription": "接続を確認して再試行してください。ローカルの代替プランは表示しません。",+ "errorDescription": "接続を確認して、もう一度お試しください。","emptyTitle": "近日公開予定です。お楽しみに。","currentPlan": "現在のプラン","unavailableReasons": {@@ -8772,7 +8772,7 @@"openPayment": "支払いページを開く","refreshingAction": "支払い情報を取得中…","paymentCompleted": "支払いが完了しました。",- "requestFailed": "リクエストに失敗しました。不明な作成結果では同じ冪等キーで安全に再試行します。",+ "requestFailed": "リクエストに失敗しました。しばらくしてからもう一度お試しください。","expiredBody": "支払いリンクの期限が切れました。新しい支払いを作成してください。","actionExpiredBody": "コードの有効期限が切れました。閉じてから再度選択し、新しい支払いを作成してください。","canceledBody": "この支払いはキャンセルされました。",@@ -8780,16 +8780,17 @@},"planChange": {"targetTitle": "サブスクリプションプランの変更",+ "back": "戻る","upgradeBadge": "アップグレード","sameLevelBadge": "同じレベル","downgradeBadge": "ダウングレード","emptyTitle": "切り替え可能なプランがありません",- "emptyDescription": "現在の支払い方法で切り替え可能なプランがまだ設定されていません。",+ "emptyDescription": "現在、切り替え可能な他のプランはありません。","quotingTitle": "プラン変更を準備中",- "quotingBody": "サーバーから金額と適用時期を取得しています…",+ "quotingBody": "金額と適用時期を確認しています…","quoteTitle": "プラン変更の確認","confirmingTitle": "変更を送信中",- "confirmingBody": "プラン変更をサーバーに送信しています…",+ "confirmingBody": "プラン変更を送信しています…","pendingProviderTitle": "プラン変更を処理中","pendingProviderBody": "決済プロバイダーが変更を処理しています。Cindy が結果を確認し続けます…","awaitingTitle": "差額のお支払い",@@ -8806,7 +8807,7 @@"requestFailed": "プラン変更リクエストを完了できませんでした。サブスクリプションの状態を更新して、もう一度お試しください。","quoteRejected": "現在のサブスクリプションではこのプランに変更できません。別のプランを選択してください。","chooseAnotherPlan": "別のプランを選択",- "resyncHint": "確認結果を検証できませんでした。サーバーから最新の状態を同期しています…",+ "resyncHint": "結果をまだ確認できません。最新の状態をもう一度確認しています…","upgradeDueNow": "今期の差額 {{amount}} をお支払いください","upgradeNoAmount": "確認後、アップグレードは即時適用されます。","upgradeHint": "お支払い完了後にアップグレードが即時適用され、以降は新プランの価格で更新されます。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 86680755d4..7d05fbabd4 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8652,7 +8652,7 @@"remaining": "잔여","progressLabel": "{{label}} 사용량","noPlanCredits": "활성 구독이 없어 요금제 잔액이 없습니다.",- "historyUnavailable": "사용 기록이 완전하지 않아 남은 잔액만 표시합니다.",+ "historyUnavailable": "사용 기록이 완전하지 않아 잔여 잔액만 표시합니다.","detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.","promotionalDetails": {"title": "프로모션 잔액 상세",@@ -8708,7 +8708,7 @@},"catalog": {"errorTitle": "요금제를 불러올 수 없습니다",- "errorDescription": "네트워크를 확인하고 다시 시도하세요. 로컬 대체 요금제는 표시하지 않습니다.",+ "errorDescription": "네트워크를 확인한 후 다시 시도하세요.","emptyTitle": "곧 출시됩니다. 기대해 주세요.","currentPlan": "현재 요금제","unavailableReasons": {@@ -8772,7 +8772,7 @@"openPayment": "결제 페이지 열기","refreshingAction": "결제 정보를 불러오는 중…","paymentCompleted": "결제가 완료되었습니다.",- "requestFailed": "요청에 실패했습니다. 결과가 불확실한 생성 요청은 같은 멱등성 키로 안전하게 재시도합니다.",+ "requestFailed": "요청에 실패했습니다. 잠시 후 다시 시도하세요.","expiredBody": "결제 링크가 만료되었습니다. 새 결제를 생성하세요.","actionExpiredBody": "코드가 만료되었습니다. 창을 닫고 다시 선택하여 새 결제를 생성하세요.","canceledBody": "이 결제가 취소되었습니다.",@@ -8780,16 +8780,17 @@},"planChange": {"targetTitle": "구독 플랜 변경",+ "back": "이전","upgradeBadge": "업그레이드","sameLevelBadge": "동일 등급","downgradeBadge": "다운그레이드","emptyTitle": "전환 가능한 플랜이 없습니다",- "emptyDescription": "현재 결제 수단으로 전환할 수 있는 다른 플랜이 아직 설정되지 않았습니다.",+ "emptyDescription": "현재 전환할 수 있는 다른 요금제가 없습니다.","quotingTitle": "플랜 변경 준비 중",- "quotingBody": "서버에서 금액과 적용 시점을 가져오는 중…",+ "quotingBody": "금액과 적용 시점을 확인하는 중…","quoteTitle": "플랜 변경 확인","confirmingTitle": "변경 제출 중",- "confirmingBody": "플랜 변경을 서버에 제출하는 중…",+ "confirmingBody": "요금제 변경을 제출하는 중…","pendingProviderTitle": "요금제 변경 처리 중","pendingProviderBody": "결제 제공자에서 변경을 처리하고 있습니다. Cindy가 결과를 계속 확인합니다…","awaitingTitle": "차액 결제",@@ -8806,7 +8807,7 @@"requestFailed": "플랜 변경 요청을 완료하지 못했습니다. 구독 상태를 새로고침한 후 다시 시도하세요.","quoteRejected": "현재 구독에서는 이 플랜으로 변경할 수 없습니다. 다른 플랜을 선택하세요.","chooseAnotherPlan": "다른 플랜 선택",- "resyncHint": "확인 결과를 검증할 수 없습니다. 서버에서 최신 상태를 동기화하는 중…",+ "resyncHint": "결과를 아직 확인할 수 없습니다. 최신 상태를 다시 확인하는 중…","upgradeDueNow": "이번 기간 차액 {{amount}}을(를) 결제하세요","upgradeNoAmount": "확인 후 업그레이드가 즉시 적용됩니다.","upgradeHint": "결제 완료 후 업그레이드가 즉시 적용되며 이후 새 플랜 가격으로 갱신됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 5492f65493..1134a90353 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8708,7 +8708,7 @@},"catalog": {"errorTitle": "暂时无法获取套餐",- "errorDescription": "请检查网络后重试。不会使用本地套餐替代。",+ "errorDescription": "请检查网络后重试。","emptyTitle": "即将上线,敬请期待","currentPlan": "当前套餐","unavailableReasons": {@@ -8772,7 +8772,7 @@"openPayment": "打开支付页面","refreshingAction": "正在获取支付方式…","paymentCompleted": "支付已完成。",- "requestFailed": "请求失败。可以重试;结果不确定时会继续复用原幂等请求。",+ "requestFailed": "请求失败,请稍后重试。","expiredBody": "支付链接已过期,请重新创建支付。","actionExpiredBody": "二维码已过期,请关闭后重新选择以生成新的支付。","canceledBody": "本次支付已取消。",@@ -8780,16 +8780,17 @@},"planChange": {"targetTitle": "更改订阅套餐",+ "back": "上一步","upgradeBadge": "升级","sameLevelBadge": "同等级","downgradeBadge": "降级","emptyTitle": "暂无可切换的套餐",- "emptyDescription": "服务端尚未为当前支付方式配置其他可切换套餐。",+ "emptyDescription": "当前没有其他可切换的套餐。","quotingTitle": "正在准备套餐变更",- "quotingBody": "正在向服务端获取价格与生效时间…",+ "quotingBody": "正在确认价格与生效时间…","quoteTitle": "确认套餐变更","confirmingTitle": "正在提交变更",- "confirmingBody": "正在向服务端提交套餐变更…",+ "confirmingBody": "正在提交套餐变更…","pendingProviderTitle": "正在处理套餐变更","pendingProviderBody": "支付渠道正在处理本次变更,Cindy 会持续确认最新结果…","awaitingTitle": "支付差价",@@ -8806,7 +8807,7 @@"requestFailed": "套餐变更请求未完成,请刷新订阅状态后重试。","quoteRejected": "当前订阅无法切换到这个套餐,请选择其他套餐。","chooseAnotherPlan": "选择其他套餐",- "resyncHint": "确认结果暂时无法核实,正在从服务端同步最新状态…",+ "resyncHint": "确认结果暂时无法核实,正在重新确认最新状态…","upgradeDueNow": "本期需支付差价 {{amount}}","upgradeNoAmount": "确认后升级立即生效。","upgradeHint": "支付完成后升级立即生效,后续按新套餐价格续费。",diff --git a/apps/desktop/src/shared/billing.ts b/apps/desktop/src/shared/billing.tsindex f9b8320750..202296ee7f 100644--- a/apps/desktop/src/shared/billing.ts+++ b/apps/desktop/src/shared/billing.ts@@ -52,6 +52,11 @@ export type BillingCatalogOfferUnavailableReason =export type BillingCatalogOffer = {code: string;+ /**+ * Operator-managed display name from the server. When omitted, Desktop does+ * not render an offer name or fall back to the internal offer code.+ */+ name?: string;/*** Optional only while Desktop remains compatible with older Model Access* servers. New servers always send the three availability fields together.