CodingPlanBillingDiscount.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import type {
  2. CodingPlanBillingDiscountConfig,
  3. CodingPlanBillingDiscountLocaleCopy,
  4. Locale,
  5. } from "@zcode/shared";
  6. import type { ICodingPlanSubscriptionService } from "@zcode/services";
  7. import { InfoIcon, SparklesIcon, TrendingUpIcon } from "lucide-react";
  8. import { useCallback, useEffect, useState } from "react";
  9. import { cn } from "@/components/lib/utils.js";
  10. import { MessageResponse } from "@/components/ai-elements/message.js";
  11. import {
  12. Dialog,
  13. DialogContent,
  14. DialogTrigger,
  15. } from "@/components/ui/dialog.js";
  16. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  17. import { useOptionalServices } from "@/hooks/useServices.js";
  18. import { useZCodeStoreWithDefault } from "@/store/StoreProvider.js";
  19. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  20. import { logger } from "@/logger.js";
  21. const BILLING_DISCOUNT_CACHE_TTL_MS = 60 * 60 * 1000;
  22. export const CODING_PLAN_BILLING_DISCOUNT_DIALOG_CONTENT_CLASS =
  23. "max-h-[min(82vh,640px)] max-w-lg grid-rows-[auto_minmax(0,1fr)] overflow-hidden";
  24. export const CODING_PLAN_BILLING_DISCOUNT_DIALOG_BODY_CLASS = "p-3 !space-y-3";
  25. let billingDiscountCache: {
  26. value: CodingPlanBillingDiscountConfig | undefined;
  27. expiresAt: number;
  28. } | null = null;
  29. let billingDiscountRequest: Promise<
  30. CodingPlanBillingDiscountConfig | undefined
  31. > | null = null;
  32. export function useCodingPlanBillingDiscount(): {
  33. active: boolean;
  34. config: CodingPlanBillingDiscountConfig | undefined;
  35. loading: boolean;
  36. refresh: () => Promise<void>;
  37. } {
  38. const services = useOptionalServices();
  39. return useCodingPlanBillingDiscountFromService(
  40. services?.codingPlanSubscriptionService,
  41. );
  42. }
  43. export function useCodingPlanBillingDiscountFromService(
  44. service:
  45. | Pick<ICodingPlanSubscriptionService, "getBillingDiscount">
  46. | undefined,
  47. ): {
  48. active: boolean;
  49. config: CodingPlanBillingDiscountConfig | undefined;
  50. loading: boolean;
  51. refresh: () => Promise<void>;
  52. } {
  53. const { locale } = useZCodeIntl();
  54. const [state, setState] = useState({
  55. active: hasLocaleCopy(billingDiscountCache?.value, locale, ["badgeBody"]),
  56. config: billingDiscountCache?.value,
  57. loading: Boolean(service) && !billingDiscountCache,
  58. });
  59. const refresh = useCallback(async () => {
  60. if (!service || typeof service.getBillingDiscount !== "function") {
  61. setState({ active: false, config: undefined, loading: false });
  62. return;
  63. }
  64. setState((current) => ({ ...current, loading: true }));
  65. try {
  66. const discount = await loadCodingPlanBillingDiscount(service);
  67. setState({
  68. active: hasLocaleCopy(discount, locale, ["badgeBody"]),
  69. config: discount,
  70. loading: false,
  71. });
  72. } catch (error) {
  73. logger.warn("[CodingPlanBillingDiscount] 读取 Coding Plan 活动配置失败", {
  74. error: error instanceof Error ? error.message : String(error),
  75. });
  76. setState({ active: false, config: undefined, loading: false });
  77. }
  78. }, [locale, service]);
  79. useEffect(() => {
  80. void refresh();
  81. }, [refresh]);
  82. return {
  83. active: state.active,
  84. config: state.config,
  85. loading: state.loading,
  86. refresh,
  87. };
  88. }
  89. export function resolveCodingPlanBillingDiscountCopy(
  90. config: CodingPlanBillingDiscountConfig | undefined,
  91. locale: Locale,
  92. ): CodingPlanBillingDiscountLocaleCopy {
  93. const copy = config?.[locale];
  94. if (!copy || typeof copy !== "object") {
  95. return {};
  96. }
  97. return {
  98. badgeBody: readNonEmptyString(copy.badgeBody),
  99. cardTitle: readNonEmptyString(copy.cardTitle),
  100. cardBody: readNonEmptyString(copy.cardBody),
  101. infoTitle: readNonEmptyString(copy.infoTitle),
  102. infoBody: readNonEmptyString(copy.infoBody),
  103. };
  104. }
  105. function hasLocaleCopy(
  106. config: CodingPlanBillingDiscountConfig | undefined,
  107. locale: Locale,
  108. keys: Array<keyof CodingPlanBillingDiscountLocaleCopy>,
  109. ): boolean {
  110. const copy = resolveCodingPlanBillingDiscountCopy(config, locale);
  111. return keys.every((key) => Boolean(copy[key]));
  112. }
  113. type CodingPlanBillingDiscountBadgePillProps = {
  114. config?: CodingPlanBillingDiscountConfig;
  115. iconVisible?: boolean;
  116. size?: "default" | "compact";
  117. variant?: "gradient" | "surface" | "tag";
  118. };
  119. export function CodingPlanBillingDiscountBadgePill({
  120. config,
  121. iconVisible = true,
  122. size = "default",
  123. variant = "gradient",
  124. }: CodingPlanBillingDiscountBadgePillProps) {
  125. const { locale } = useZCodeIntl();
  126. const copy = resolveCodingPlanBillingDiscountCopy(config, locale);
  127. if (!copy.badgeBody) {
  128. return null;
  129. }
  130. return (
  131. <div
  132. className={cn(
  133. // Bugfix: 活动徽标文案来自服务端多语言配置,英文可能需要保留 Title Case。
  134. // 不能用 uppercase 强制转写,否则 "150% Quota" 会被渲染成 "150% QUOTA"。
  135. "inline-flex items-center py-0.5 whitespace-nowrap",
  136. size === "compact"
  137. ? "gap-0.5 px-1.5 text-ui-xs leading-none"
  138. : "gap-1 px-2 text-ui-xs",
  139. variant === "surface"
  140. ? "rounded-full bg-white text-[#191A1D]"
  141. : variant === "tag"
  142. ? "rounded-full bg-tag text-foreground"
  143. : "rounded-full text-white button-gradient dark:bg-[#484A58]",
  144. )}
  145. >
  146. {iconVisible ? (
  147. <TrendingUpIcon
  148. className={size === "compact" ? "size-2.5" : "size-3"}
  149. />
  150. ) : null}
  151. {copy.badgeBody}
  152. </div>
  153. );
  154. }
  155. export function CodingPlanBillingDiscountBadge(
  156. props: CodingPlanBillingDiscountBadgePillProps,
  157. ) {
  158. const { locale } = useZCodeIntl();
  159. const copy = resolveCodingPlanBillingDiscountCopy(props.config, locale);
  160. if (!copy.badgeBody) {
  161. return null;
  162. }
  163. const badge = <CodingPlanBillingDiscountBadgePill {...props} />;
  164. return (
  165. <>
  166. {badge}
  167. <CodingPlanBillingDiscountInfoDialog
  168. config={props.config}
  169. tone={props.variant === "surface" ? "onGradient" : "default"}
  170. />
  171. </>
  172. );
  173. }
  174. export function CodingPlanBillingDiscountBanner({
  175. config,
  176. }: {
  177. config?: CodingPlanBillingDiscountConfig;
  178. }) {
  179. const { locale } = useZCodeIntl();
  180. const copy = resolveCodingPlanBillingDiscountCopy(config, locale);
  181. if (!copy.cardTitle || !copy.cardBody) {
  182. return null;
  183. }
  184. return (
  185. <div className="rounded-xl border border-transparent button-gradient px-3 py-2.5 text-white dark:bg-[#484A58]">
  186. <div className="flex min-w-0 items-center justify-between gap-3">
  187. <div className="flex min-w-0 items-start gap-2">
  188. <div className="flex h-6 shrink-0 items-center">
  189. <SparklesIcon className="size-4 text-white" />
  190. </div>
  191. <div className="min-w-0">
  192. <div className="text-ui-lg font-medium leading-6 text-white">
  193. {copy.cardTitle}
  194. </div>
  195. <div className="mt-0.5 text-ui-base leading-5 text-white/80">
  196. {copy.cardBody}
  197. </div>
  198. </div>
  199. </div>
  200. <div className="flex shrink-0 items-center gap-1">
  201. <CodingPlanBillingDiscountBadge config={config} variant="surface" />
  202. </div>
  203. </div>
  204. </div>
  205. );
  206. }
  207. export function CodingPlanBillingDiscountInfoDialog({
  208. config,
  209. tone = "default",
  210. }: {
  211. config?: CodingPlanBillingDiscountConfig;
  212. tone?: "default" | "onGradient";
  213. }) {
  214. const { intl, locale } = useZCodeIntl();
  215. const copy = resolveCodingPlanBillingDiscountCopy(config, locale);
  216. // M5②.5 store 耦合剥离:MessageResponse 不再自取 store,主题/代码预览设置由调用方传入。
  217. const theme = useZCodeStoreWithDefault((state) => state.theme, "system");
  218. const codePreviewSettings = useZCodeStoreWithDefault(
  219. (state) => state.codePreviewSettings,
  220. DEFAULT_CODE_PREVIEW_SETTINGS,
  221. );
  222. const openLabel = intl.formatMessage({
  223. id: "settings.modelProvider.codingPlan.billingDiscountInfo.open",
  224. });
  225. // 活动规则会随服务端运营配置变化,必须整体使用远端标题和 Markdown 正文,
  226. // 缺失时隐藏入口,避免本地旧规则与当前活动不一致。
  227. if (!copy.infoTitle || !copy.infoBody) {
  228. return null;
  229. }
  230. const markdown = `## ${copy.infoTitle}\n\n${copy.infoBody}`;
  231. return (
  232. <Dialog>
  233. <DialogTrigger asChild>
  234. <InfoIcon
  235. role="button"
  236. tabIndex={0}
  237. aria-label={openLabel}
  238. className={cn(
  239. "size-3.5 shrink-0 cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
  240. tone === "onGradient"
  241. ? "text-white/90 hover:text-white"
  242. : "text-foreground-subtle hover:text-foreground",
  243. )}
  244. />
  245. </DialogTrigger>
  246. <DialogContent
  247. className={cn(
  248. CODING_PLAN_BILLING_DISCOUNT_DIALOG_CONTENT_CLASS,
  249. "block",
  250. )}
  251. >
  252. <div className={CODING_PLAN_BILLING_DISCOUNT_DIALOG_BODY_CLASS}>
  253. <MessageResponse
  254. className="min-h-0 overflow-y-auto pr-1 text-foreground"
  255. theme={theme}
  256. codePreviewSettings={codePreviewSettings}
  257. >
  258. {markdown}
  259. </MessageResponse>
  260. </div>
  261. </DialogContent>
  262. </Dialog>
  263. );
  264. }
  265. export function clearCodingPlanBillingDiscountCacheForTest() {
  266. billingDiscountCache = null;
  267. billingDiscountRequest = null;
  268. }
  269. export function primeCodingPlanBillingDiscountCacheForTest(
  270. config: CodingPlanBillingDiscountConfig | undefined,
  271. ) {
  272. billingDiscountCache = {
  273. value: config,
  274. expiresAt: Date.now() + BILLING_DISCOUNT_CACHE_TTL_MS,
  275. };
  276. billingDiscountRequest = null;
  277. }
  278. async function loadCodingPlanBillingDiscount(
  279. service: Pick<ICodingPlanSubscriptionService, "getBillingDiscount">,
  280. ): Promise<CodingPlanBillingDiscountConfig | undefined> {
  281. const now = Date.now();
  282. if (billingDiscountCache && billingDiscountCache.expiresAt > now) {
  283. return billingDiscountCache.value;
  284. }
  285. if (billingDiscountRequest) {
  286. return billingDiscountRequest;
  287. }
  288. const request = service.getBillingDiscount();
  289. billingDiscountRequest = request;
  290. try {
  291. const discount = await request;
  292. billingDiscountCache = {
  293. value: discount,
  294. expiresAt: now + BILLING_DISCOUNT_CACHE_TTL_MS,
  295. };
  296. return discount;
  297. } finally {
  298. if (billingDiscountRequest === request) {
  299. billingDiscountRequest = null;
  300. }
  301. }
  302. }
  303. function readNonEmptyString(value: unknown): string | undefined {
  304. if (typeof value !== "string") {
  305. return undefined;
  306. }
  307. const trimmed = value.trim();
  308. return trimmed.length > 0 ? trimmed : undefined;
  309. }