Payments.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { useState, useEffect, useCallback } from "react";
  2. import type { Spec } from "@json-render/react";
  3. import {
  4. Box,
  5. ContextView,
  6. Button,
  7. TextField,
  8. Spinner,
  9. } from "@stripe/ui-extension-sdk/ui";
  10. import type { ExtensionContextValue } from "@stripe/ui-extension-sdk/context";
  11. import BrandIcon from "./brand_icon.svg";
  12. import { API_GENERATE_URL } from "../lib/config";
  13. import { stripeCatalog, StripeRenderer } from "../lib/render";
  14. import { executeAction } from "../lib/render/catalog/actions";
  15. // =============================================================================
  16. // Dynamic Spec Creation
  17. // =============================================================================
  18. function createPaymentsSpec(data: Record<string, unknown>): Spec {
  19. const payments = data.payments as
  20. | {
  21. data?: Array<{
  22. id: string;
  23. formattedAmount: string;
  24. status: string;
  25. description: string;
  26. created: string;
  27. }>;
  28. total?: number;
  29. totalVolume?: string;
  30. successRate?: string;
  31. hasMore?: boolean;
  32. }
  33. | undefined;
  34. const paymentsList = payments?.data ?? [];
  35. const elements: Spec["elements"] = {
  36. root: {
  37. type: "Stack",
  38. props: { direction: "vertical", gap: "large" },
  39. children: ["heading", "metrics", "filters", "list", "pagination"],
  40. },
  41. heading: {
  42. type: "Heading",
  43. props: { text: "Payments", size: "xlarge" },
  44. children: [],
  45. },
  46. metrics: {
  47. type: "Stack",
  48. props: { direction: "horizontal", gap: "medium" },
  49. children: ["volumeMetric", "rateMetric", "countMetric"],
  50. },
  51. volumeMetric: {
  52. type: "Metric",
  53. props: {
  54. label: "Total Volume",
  55. value: payments?.totalVolume ?? "$0",
  56. changeType: "positive",
  57. },
  58. children: [],
  59. },
  60. rateMetric: {
  61. type: "Metric",
  62. props: {
  63. label: "Success Rate",
  64. value: payments?.successRate ?? "0%",
  65. changeType: "positive",
  66. },
  67. children: [],
  68. },
  69. countMetric: {
  70. type: "Metric",
  71. props: {
  72. label: "Total Payments",
  73. value: String(payments?.total ?? 0),
  74. changeType: "neutral",
  75. },
  76. children: [],
  77. },
  78. filters: {
  79. type: "Stack",
  80. props: { direction: "horizontal", gap: "small" },
  81. children: ["refreshBtn", "exportBtn"],
  82. },
  83. refreshBtn: {
  84. type: "Button",
  85. props: { label: "Refresh", action: "refreshPayments", type: "secondary" },
  86. children: [],
  87. },
  88. exportBtn: {
  89. type: "Button",
  90. props: {
  91. label: "Export CSV",
  92. action: "exportData",
  93. actionParams: { format: "csv", dataType: "payments" },
  94. type: "secondary",
  95. },
  96. children: [],
  97. },
  98. list: {
  99. type: "Stack",
  100. props: { direction: "vertical", gap: "small" },
  101. children: paymentsList.slice(0, 10).map((_, i) => `payment${i}`),
  102. },
  103. pagination: {
  104. type: "Stack",
  105. props: { direction: "horizontal", gap: "small" },
  106. children: payments?.hasMore ? ["loadMore"] : [],
  107. },
  108. loadMore: {
  109. type: "Button",
  110. props: {
  111. label: "Load More",
  112. action: "fetchPayments",
  113. actionParams: {
  114. limit: 10,
  115. startingAfter: paymentsList[paymentsList.length - 1]?.id,
  116. },
  117. type: "secondary",
  118. },
  119. children: [],
  120. },
  121. };
  122. paymentsList.slice(0, 10).forEach((p, i) => {
  123. elements[`payment${i}`] = {
  124. type: "PaymentCard",
  125. props: {
  126. amount: 0,
  127. currency: "usd",
  128. status: p.status as "succeeded" | "pending" | "failed" | "canceled",
  129. description: `${p.formattedAmount} - ${p.description}`,
  130. paymentId: p.id,
  131. },
  132. children: [],
  133. };
  134. });
  135. return { root: "root", elements };
  136. }
  137. // =============================================================================
  138. // Component
  139. // =============================================================================
  140. const Payments = (_props: ExtensionContextValue) => {
  141. const [data, setState] = useState<Record<string, unknown>>({});
  142. const [spec, setSpec] = useState<Spec | null>(null);
  143. const [loading, setLoading] = useState(true);
  144. const [prompt, setPrompt] = useState("");
  145. const [generating, setGenerating] = useState(false);
  146. const handleSetState = useCallback(
  147. (updater: (prev: Record<string, unknown>) => Record<string, unknown>) => {
  148. setState((prev) => updater(prev));
  149. },
  150. [],
  151. );
  152. useEffect(() => {
  153. const loadData = async () => {
  154. setLoading(true);
  155. await executeAction("fetchPayments", { limit: 10 }, handleSetState, {});
  156. setLoading(false);
  157. };
  158. loadData();
  159. }, [handleSetState]);
  160. useEffect(() => {
  161. if (!loading && Object.keys(data).length > 0) {
  162. setSpec(createPaymentsSpec(data));
  163. }
  164. }, [data, loading]);
  165. const handleGenerate = async () => {
  166. if (!prompt.trim()) return;
  167. setGenerating(true);
  168. const systemPrompt = stripeCatalog.prompt();
  169. try {
  170. const response = await fetch(API_GENERATE_URL, {
  171. method: "POST",
  172. headers: { "Content-Type": "application/json" },
  173. body: JSON.stringify({ prompt, systemPrompt }),
  174. });
  175. const result = await response.json();
  176. if (result.spec) {
  177. setSpec(result.spec);
  178. }
  179. } catch (error) {
  180. console.error("Generation error:", error);
  181. setSpec(createPaymentsSpec(data));
  182. }
  183. setGenerating(false);
  184. };
  185. if (loading) {
  186. return (
  187. <ContextView title="Payments" brandColor="#635BFF" brandIcon={BrandIcon}>
  188. <Box
  189. css={{
  190. stack: "y",
  191. gap: "medium",
  192. alignX: "center",
  193. paddingY: "xlarge",
  194. }}
  195. >
  196. <Spinner size="large" />
  197. <Box css={{ color: "secondary" }}>Loading payments...</Box>
  198. </Box>
  199. </ContextView>
  200. );
  201. }
  202. return (
  203. <ContextView
  204. title="Payments"
  205. brandColor="#635BFF"
  206. brandIcon={BrandIcon}
  207. actions={
  208. <Button
  209. type="primary"
  210. onPress={() =>
  211. executeAction(
  212. "openDashboard",
  213. { page: "payments" },
  214. handleSetState,
  215. data,
  216. )
  217. }
  218. >
  219. Open in Dashboard
  220. </Button>
  221. }
  222. >
  223. <Box css={{ stack: "y", gap: "medium" }}>
  224. <Box css={{ stack: "x", gap: "small" }}>
  225. <Box css={{ width: "fill" }}>
  226. <TextField
  227. label=""
  228. placeholder="Describe the payments view you want..."
  229. value={prompt}
  230. onChange={(e) => setPrompt(e.target.value)}
  231. />
  232. </Box>
  233. <Box css={{ alignSelfY: "center" }}>
  234. <Button
  235. type="primary"
  236. onPress={handleGenerate}
  237. disabled={generating || !prompt.trim()}
  238. >
  239. {generating ? "Generating..." : "Generate"}
  240. </Button>
  241. </Box>
  242. </Box>
  243. {spec && (
  244. <StripeRenderer
  245. spec={spec}
  246. data={data}
  247. setData={handleSetState}
  248. loading={generating}
  249. />
  250. )}
  251. </Box>
  252. </ContextView>
  253. );
  254. };
  255. export default Payments;