payment-kit 1.13.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/.eslintrc.js +15 -0
  2. package/README.md +3 -0
  3. package/api/dev.ts +6 -0
  4. package/api/hooks/pre-start.js +12 -0
  5. package/api/src/hooks/pre-start.ts +21 -0
  6. package/api/src/index.ts +92 -0
  7. package/api/src/jobs/event.ts +72 -0
  8. package/api/src/jobs/invoice.ts +148 -0
  9. package/api/src/jobs/payment.ts +208 -0
  10. package/api/src/jobs/subscription.ts +301 -0
  11. package/api/src/jobs/webhook.ts +113 -0
  12. package/api/src/libs/audit.ts +73 -0
  13. package/api/src/libs/auth.ts +40 -0
  14. package/api/src/libs/chain/arcblock.ts +13 -0
  15. package/api/src/libs/dayjs.ts +17 -0
  16. package/api/src/libs/env.ts +5 -0
  17. package/api/src/libs/hooks.ts +42 -0
  18. package/api/src/libs/logger.ts +27 -0
  19. package/api/src/libs/middleware.ts +12 -0
  20. package/api/src/libs/payment.ts +53 -0
  21. package/api/src/libs/queue/index.ts +263 -0
  22. package/api/src/libs/queue/store.ts +47 -0
  23. package/api/src/libs/security.ts +95 -0
  24. package/api/src/libs/session.ts +164 -0
  25. package/api/src/libs/util.ts +93 -0
  26. package/api/src/locales/en.ts +3 -0
  27. package/api/src/locales/index.ts +37 -0
  28. package/api/src/locales/zh.ts +3 -0
  29. package/api/src/routes/checkout-sessions.ts +536 -0
  30. package/api/src/routes/connect/collect.ts +109 -0
  31. package/api/src/routes/connect/pay.ts +116 -0
  32. package/api/src/routes/connect/setup.ts +121 -0
  33. package/api/src/routes/connect/shared.ts +410 -0
  34. package/api/src/routes/connect/subscribe.ts +128 -0
  35. package/api/src/routes/customers.ts +70 -0
  36. package/api/src/routes/events.ts +76 -0
  37. package/api/src/routes/index.ts +59 -0
  38. package/api/src/routes/invoices.ts +126 -0
  39. package/api/src/routes/payment-currencies.ts +38 -0
  40. package/api/src/routes/payment-intents.ts +122 -0
  41. package/api/src/routes/payment-links.ts +221 -0
  42. package/api/src/routes/payment-methods.ts +39 -0
  43. package/api/src/routes/prices.ts +134 -0
  44. package/api/src/routes/products.ts +191 -0
  45. package/api/src/routes/settings.ts +33 -0
  46. package/api/src/routes/subscription-items.ts +148 -0
  47. package/api/src/routes/subscriptions.ts +254 -0
  48. package/api/src/routes/usage-records.ts +120 -0
  49. package/api/src/routes/webhook-attempts.ts +57 -0
  50. package/api/src/routes/webhook-endpoints.ts +105 -0
  51. package/api/src/store/migrate.ts +16 -0
  52. package/api/src/store/migrations/20230905-genesis.ts +52 -0
  53. package/api/src/store/migrations/20230911-seeding.ts +145 -0
  54. package/api/src/store/models/checkout-session.ts +395 -0
  55. package/api/src/store/models/coupon.ts +137 -0
  56. package/api/src/store/models/customer.ts +199 -0
  57. package/api/src/store/models/discount.ts +116 -0
  58. package/api/src/store/models/event.ts +111 -0
  59. package/api/src/store/models/index.ts +165 -0
  60. package/api/src/store/models/invoice-item.ts +185 -0
  61. package/api/src/store/models/invoice.ts +492 -0
  62. package/api/src/store/models/job.ts +75 -0
  63. package/api/src/store/models/payment-currency.ts +139 -0
  64. package/api/src/store/models/payment-intent.ts +282 -0
  65. package/api/src/store/models/payment-link.ts +219 -0
  66. package/api/src/store/models/payment-method.ts +169 -0
  67. package/api/src/store/models/price.ts +266 -0
  68. package/api/src/store/models/product.ts +162 -0
  69. package/api/src/store/models/promotion-code.ts +112 -0
  70. package/api/src/store/models/setup-intent.ts +206 -0
  71. package/api/src/store/models/subscription-item.ts +103 -0
  72. package/api/src/store/models/subscription-schedule.ts +157 -0
  73. package/api/src/store/models/subscription.ts +307 -0
  74. package/api/src/store/models/types.ts +406 -0
  75. package/api/src/store/models/usage-record.ts +132 -0
  76. package/api/src/store/models/webhook-attempt.ts +96 -0
  77. package/api/src/store/models/webhook-endpoint.ts +96 -0
  78. package/api/src/store/sequelize.ts +15 -0
  79. package/api/third.d.ts +28 -0
  80. package/blocklet.md +3 -0
  81. package/blocklet.yml +89 -0
  82. package/index.html +14 -0
  83. package/logo.png +0 -0
  84. package/package.json +133 -0
  85. package/public/.gitkeep +0 -0
  86. package/screenshots/.gitkeep +0 -0
  87. package/screenshots/1-subscription.png +0 -0
  88. package/screenshots/2-customer-1.png +0 -0
  89. package/screenshots/3-customer-2.png +0 -0
  90. package/screenshots/4-admin-3.png +0 -0
  91. package/screenshots/5-admin-4.png +0 -0
  92. package/scripts/build-clean.js +6 -0
  93. package/scripts/bump-version.mjs +35 -0
  94. package/src/app.tsx +68 -0
  95. package/src/components/actions.tsx +85 -0
  96. package/src/components/blockchain/tx.tsx +29 -0
  97. package/src/components/checkout/amount.tsx +24 -0
  98. package/src/components/checkout/error.tsx +30 -0
  99. package/src/components/checkout/footer.tsx +12 -0
  100. package/src/components/checkout/form/address.tsx +38 -0
  101. package/src/components/checkout/form/index.tsx +295 -0
  102. package/src/components/checkout/header.tsx +23 -0
  103. package/src/components/checkout/pay.tsx +222 -0
  104. package/src/components/checkout/product-card.tsx +56 -0
  105. package/src/components/checkout/product-item.tsx +37 -0
  106. package/src/components/checkout/skeleton/overview.tsx +21 -0
  107. package/src/components/checkout/skeleton/payment.tsx +35 -0
  108. package/src/components/checkout/success.tsx +183 -0
  109. package/src/components/checkout/summary.tsx +34 -0
  110. package/src/components/collapse.tsx +50 -0
  111. package/src/components/confirm.tsx +55 -0
  112. package/src/components/copyable.tsx +38 -0
  113. package/src/components/currency.tsx +15 -0
  114. package/src/components/customer/actions.tsx +73 -0
  115. package/src/components/data.tsx +20 -0
  116. package/src/components/drawer-form.tsx +77 -0
  117. package/src/components/error-fallback.tsx +7 -0
  118. package/src/components/error.tsx +39 -0
  119. package/src/components/event/list.tsx +217 -0
  120. package/src/components/info-card.tsx +40 -0
  121. package/src/components/info-metric.tsx +35 -0
  122. package/src/components/info-row.tsx +28 -0
  123. package/src/components/input.tsx +40 -0
  124. package/src/components/invoice/action.tsx +94 -0
  125. package/src/components/invoice/list.tsx +225 -0
  126. package/src/components/invoice/table.tsx +110 -0
  127. package/src/components/layout.tsx +70 -0
  128. package/src/components/livemode.tsx +23 -0
  129. package/src/components/metadata/editor.tsx +57 -0
  130. package/src/components/metadata/form.tsx +45 -0
  131. package/src/components/payment-intent/actions.tsx +81 -0
  132. package/src/components/payment-intent/list.tsx +204 -0
  133. package/src/components/payment-link/actions.tsx +114 -0
  134. package/src/components/payment-link/after-pay.tsx +87 -0
  135. package/src/components/payment-link/before-pay.tsx +175 -0
  136. package/src/components/payment-link/item.tsx +135 -0
  137. package/src/components/payment-link/product-select.tsx +66 -0
  138. package/src/components/payment-link/rename.tsx +64 -0
  139. package/src/components/portal/invoice/list.tsx +110 -0
  140. package/src/components/portal/subscription/cancel.tsx +83 -0
  141. package/src/components/portal/subscription/list.tsx +232 -0
  142. package/src/components/price/actions.tsx +21 -0
  143. package/src/components/price/form.tsx +292 -0
  144. package/src/components/product/actions.tsx +125 -0
  145. package/src/components/product/add-price.tsx +59 -0
  146. package/src/components/product/create.tsx +97 -0
  147. package/src/components/product/edit-price.tsx +75 -0
  148. package/src/components/product/edit.tsx +67 -0
  149. package/src/components/product/features.tsx +32 -0
  150. package/src/components/product/form.tsx +76 -0
  151. package/src/components/relative-time.tsx +41 -0
  152. package/src/components/section/header.tsx +29 -0
  153. package/src/components/status.tsx +12 -0
  154. package/src/components/subscription/actions/cancel.tsx +66 -0
  155. package/src/components/subscription/actions/index.tsx +172 -0
  156. package/src/components/subscription/actions/pause.tsx +83 -0
  157. package/src/components/subscription/items/actions.tsx +31 -0
  158. package/src/components/subscription/items/index.tsx +107 -0
  159. package/src/components/subscription/list.tsx +200 -0
  160. package/src/components/switch.tsx +48 -0
  161. package/src/components/table.tsx +66 -0
  162. package/src/components/uploader.tsx +81 -0
  163. package/src/components/webhook/attempts.tsx +149 -0
  164. package/src/contexts/products.tsx +42 -0
  165. package/src/contexts/session.ts +10 -0
  166. package/src/contexts/settings.tsx +54 -0
  167. package/src/env.d.ts +17 -0
  168. package/src/global.css +97 -0
  169. package/src/hooks/mobile.ts +15 -0
  170. package/src/index.tsx +6 -0
  171. package/src/libs/api.ts +19 -0
  172. package/src/libs/dayjs.ts +17 -0
  173. package/src/libs/util.ts +474 -0
  174. package/src/locales/en.tsx +395 -0
  175. package/src/locales/index.tsx +8 -0
  176. package/src/locales/zh.tsx +389 -0
  177. package/src/pages/admin/billing/index.tsx +56 -0
  178. package/src/pages/admin/billing/invoices/detail.tsx +215 -0
  179. package/src/pages/admin/billing/invoices/index.tsx +5 -0
  180. package/src/pages/admin/billing/subscriptions/detail.tsx +237 -0
  181. package/src/pages/admin/billing/subscriptions/index.tsx +5 -0
  182. package/src/pages/admin/customers/customers/detail.tsx +209 -0
  183. package/src/pages/admin/customers/customers/index.tsx +109 -0
  184. package/src/pages/admin/customers/index.tsx +47 -0
  185. package/src/pages/admin/developers/events/detail.tsx +77 -0
  186. package/src/pages/admin/developers/events/index.tsx +5 -0
  187. package/src/pages/admin/developers/index.tsx +60 -0
  188. package/src/pages/admin/developers/logs.tsx +3 -0
  189. package/src/pages/admin/developers/overview.tsx +3 -0
  190. package/src/pages/admin/developers/webhooks/detail.tsx +109 -0
  191. package/src/pages/admin/developers/webhooks/index.tsx +102 -0
  192. package/src/pages/admin/index.tsx +120 -0
  193. package/src/pages/admin/overview.tsx +3 -0
  194. package/src/pages/admin/payments/index.tsx +65 -0
  195. package/src/pages/admin/payments/intents/detail.tsx +205 -0
  196. package/src/pages/admin/payments/intents/index.tsx +5 -0
  197. package/src/pages/admin/payments/links/create.tsx +141 -0
  198. package/src/pages/admin/payments/links/detail.tsx +318 -0
  199. package/src/pages/admin/payments/links/index.tsx +167 -0
  200. package/src/pages/admin/products/coupons/index.tsx +3 -0
  201. package/src/pages/admin/products/index.tsx +81 -0
  202. package/src/pages/admin/products/prices/actions.tsx +151 -0
  203. package/src/pages/admin/products/prices/detail.tsx +203 -0
  204. package/src/pages/admin/products/prices/list.tsx +95 -0
  205. package/src/pages/admin/products/pricing-tables.tsx +3 -0
  206. package/src/pages/admin/products/products/create.tsx +105 -0
  207. package/src/pages/admin/products/products/detail.tsx +246 -0
  208. package/src/pages/admin/products/products/index.tsx +154 -0
  209. package/src/pages/admin/settings/branding.tsx +3 -0
  210. package/src/pages/admin/settings/business.tsx +3 -0
  211. package/src/pages/admin/settings/index.tsx +47 -0
  212. package/src/pages/admin/settings/payment-methods.tsx +80 -0
  213. package/src/pages/checkout/index.tsx +38 -0
  214. package/src/pages/checkout/pay.tsx +89 -0
  215. package/src/pages/customer/index.tsx +93 -0
  216. package/src/pages/customer/invoice.tsx +147 -0
  217. package/src/pages/home.tsx +9 -0
  218. package/tsconfig.api.json +9 -0
  219. package/tsconfig.eslint.json +7 -0
  220. package/tsconfig.json +99 -0
  221. package/tsconfig.types.json +11 -0
  222. package/vite.config.ts +19 -0
@@ -0,0 +1,80 @@
1
+ import type { TPaymentMethodExpanded } from '@did-pay/types';
2
+ import { Alert, Box, CircularProgress, Grid, Typography } from '@mui/material';
3
+ import { useRequest } from 'ahooks';
4
+
5
+ import IconCollapse from '../../../components/collapse';
6
+ import InfoCard from '../../../components/info-card';
7
+ import InfoRow from '../../../components/info-row';
8
+ import Switch from '../../../components/switch';
9
+ import api from '../../../libs/api';
10
+
11
+ const getMethods = (params: Record<string, any> = {}): Promise<TPaymentMethodExpanded[]> => {
12
+ const search = new URLSearchParams();
13
+ Object.keys(params).forEach((key) => {
14
+ search.set(key, String(params[key]));
15
+ });
16
+ return api.get(`/api/payment-methods?${search.toString()}`).then((res) => res.data);
17
+ };
18
+
19
+ const groupByType = (methods: TPaymentMethodExpanded[]) => {
20
+ const groups: Record<string, TPaymentMethodExpanded[]> = {};
21
+ methods.forEach((x) => {
22
+ groups[x.type] = groups[x.type] || [];
23
+ (groups[x.type] as any).push(x);
24
+ });
25
+
26
+ return groups;
27
+ };
28
+
29
+ export default function PaymentMethods() {
30
+ const { loading, error, data } = useRequest(() => getMethods({}));
31
+
32
+ if (error) {
33
+ return <Alert severity="error">{error.message}</Alert>;
34
+ }
35
+
36
+ if (loading || !data) {
37
+ return <CircularProgress />;
38
+ }
39
+
40
+ const groups = groupByType(data);
41
+
42
+ // FIXME: i18n
43
+ return (
44
+ <>
45
+ {Object.keys(groups).map((x) => (
46
+ <Box key={x} mt={3}>
47
+ <Typography variant="h6" sx={{ mb: 1, textTransform: 'uppercase' }}>
48
+ {x}
49
+ </Typography>
50
+ {(groups[x] as TPaymentMethodExpanded[]).map((method) => (
51
+ <IconCollapse
52
+ key={method.id}
53
+ trigger={<InfoCard {...method} />}
54
+ addons={<Switch checked={method.active} />}
55
+ style={{
56
+ py: 1,
57
+ borderTop: '1px solid #eee',
58
+ borderBottom: '1px solid #eee',
59
+ '& :hover': { color: 'text.primary' },
60
+ }}>
61
+ <Grid container spacing={2} mt={0}>
62
+ <Grid item xs={12} md={6}>
63
+ <InfoRow label="Type" value={method.type} />
64
+ <InfoRow label="Confirmation" value={method.confirmation.type} />
65
+ <InfoRow label="Recurring payments" value={method.features.recurring ? 'Yes' : 'No'} />
66
+ <InfoRow label="Refund support" value={method.features.refund ? 'Yes' : 'No'} />
67
+ <InfoRow label="Dispute support" value={method.features.dispute ? 'Yes' : 'No'} />
68
+ <InfoRow
69
+ label="Currencies"
70
+ value={method.payment_currencies.map((currency) => currency.symbol).join(', ')}
71
+ />
72
+ </Grid>
73
+ </Grid>
74
+ </IconCollapse>
75
+ ))}
76
+ </Box>
77
+ ))}
78
+ </>
79
+ );
80
+ }
@@ -0,0 +1,38 @@
1
+ import Center from '@arcblock/ux/lib/Center';
2
+ import { Box, CircularProgress } from '@mui/material';
3
+ import React, { Suspense } from 'react';
4
+ import { useParams } from 'react-router-dom';
5
+
6
+ import { SettingsProvider } from '../../contexts/settings';
7
+
8
+ const pages = {
9
+ pay: React.lazy(() => import('./pay')),
10
+ };
11
+
12
+ function Checkout() {
13
+ const { action, id } = useParams<{ action: 'pay'; id: string }>();
14
+
15
+ // @ts-ignore
16
+ const TabComponent = pages[action];
17
+
18
+ return (
19
+ <Box>
20
+ <Suspense
21
+ fallback={
22
+ <Center relative="parent">
23
+ <CircularProgress />
24
+ </Center>
25
+ }>
26
+ <TabComponent id={id} />
27
+ </Suspense>
28
+ </Box>
29
+ );
30
+ }
31
+
32
+ export default function WrappedAdmin() {
33
+ return (
34
+ <SettingsProvider>
35
+ <Checkout />
36
+ </SettingsProvider>
37
+ );
38
+ }
@@ -0,0 +1,89 @@
1
+ import type {
2
+ TCheckoutSessionExpanded,
3
+ TCustomer,
4
+ TPaymentIntent,
5
+ TPaymentLink,
6
+ TPaymentMethodExpanded,
7
+ } from '@did-pay/types';
8
+ import { useRequest, useSetState } from 'ahooks';
9
+ import { useEffect } from 'react';
10
+ import { useNavigate, useSearchParams } from 'react-router-dom';
11
+
12
+ import CheckoutPay from '../../components/checkout/pay';
13
+ import api from '../../libs/api';
14
+
15
+ type Props = {
16
+ id: string;
17
+ };
18
+
19
+ type PageData = {
20
+ checkoutSession: TCheckoutSessionExpanded;
21
+ paymentMethods: TPaymentMethodExpanded[];
22
+ paymentLink?: TPaymentLink;
23
+ paymentIntent?: TPaymentIntent;
24
+ customer?: TCustomer;
25
+ };
26
+
27
+ const startFromPaymentLink = async (id: string, preview: string): Promise<PageData> => {
28
+ const { data } = await api.post(`/api/checkout-sessions/start/${id}?preview=${preview}`);
29
+ return data;
30
+ };
31
+
32
+ const fetchCheckoutSession = async (id: string): Promise<PageData> => {
33
+ const { data } = await api.get(`/api/checkout-sessions/retrieve/${id}`);
34
+ return data;
35
+ };
36
+
37
+ export default function Payment({ id }: Props) {
38
+ const type = id.startsWith('plink_') ? 'paymentLink' : 'checkoutSession';
39
+
40
+ const navigate = useNavigate();
41
+ const [params] = useSearchParams();
42
+ const [state, setState] = useSetState({ completed: false, appError: null });
43
+
44
+ const { error: apiError, data } = useRequest(() =>
45
+ type === 'paymentLink' ? startFromPaymentLink(id, params.get('preview') || '') : fetchCheckoutSession(id)
46
+ );
47
+
48
+ useEffect(() => {
49
+ if (data && type === 'paymentLink') {
50
+ navigate(`/checkout/pay/${data.checkoutSession.id}`, { replace: true });
51
+ }
52
+ }, [type, data, navigate]);
53
+
54
+ const onPaid = () => {
55
+ setState({ completed: true });
56
+ if (data?.paymentLink) {
57
+ if (data.paymentLink.after_completion?.type === 'redirect' && data.paymentLink.after_completion?.redirect?.url) {
58
+ setTimeout(() => {
59
+ // @ts-ignore
60
+ window.location.href = data.paymentLink?.after_completion?.redirect?.url;
61
+ }, 1000);
62
+ }
63
+ } else if (data?.checkoutSession?.success_url) {
64
+ setTimeout(() => {
65
+ // @ts-ignore
66
+ window.location.href = data?.checkoutSession?.success_url;
67
+ }, 1000);
68
+ }
69
+ };
70
+
71
+ const onError = (err: any) => {
72
+ setState({ appError: err });
73
+ console.error(err);
74
+ };
75
+
76
+ return (
77
+ <CheckoutPay
78
+ checkoutSession={data?.checkoutSession}
79
+ paymentMethods={data?.paymentMethods}
80
+ paymentIntent={data?.paymentIntent}
81
+ paymentLink={data?.paymentLink}
82
+ customer={data?.customer}
83
+ completed={state.completed}
84
+ error={apiError || state.appError}
85
+ onPaid={onPaid}
86
+ onError={onError}
87
+ />
88
+ );
89
+ }
@@ -0,0 +1,93 @@
1
+ import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
2
+ import type { TCustomerExpanded } from '@did-pay/types';
3
+ import { Edit } from '@mui/icons-material';
4
+ import { Alert, Box, Button, CircularProgress, Grid, Stack } from '@mui/material';
5
+ import { styled } from '@mui/system';
6
+ import { useRequest, useSetState } from 'ahooks';
7
+
8
+ import InfoRow from '../../components/info-row';
9
+ import Layout from '../../components/layout';
10
+ import CustomerInvoiceList from '../../components/portal/invoice/list';
11
+ import CurrentSubscriptions from '../../components/portal/subscription/list';
12
+ import SectionHeader from '../../components/section/header';
13
+ import api from '../../libs/api';
14
+ import { formatError } from '../../libs/util';
15
+
16
+ const fetchData = (): Promise<TCustomerExpanded> => {
17
+ return api.get('/api/customers/me').then((res) => res.data);
18
+ };
19
+
20
+ export default function CustomerHome() {
21
+ const { t } = useLocaleContext();
22
+ const [state, setState] = useSetState({
23
+ editing: false,
24
+ loading: false,
25
+ });
26
+
27
+ const { loading, error, data, runAsync } = useRequest(fetchData);
28
+
29
+ if (error) {
30
+ return <Alert severity="error">{formatError(error)}</Alert>;
31
+ }
32
+
33
+ if (loading || !data) {
34
+ return <CircularProgress />;
35
+ }
36
+
37
+ return (
38
+ <Layout>
39
+ <Grid container spacing={5}>
40
+ <Grid item xs={12} md={8}>
41
+ <Root direction="column" spacing={3} sx={{ my: 2 }}>
42
+ <Box className="section">
43
+ <SectionHeader title={t('customer.subscriptions')} mb={0} />
44
+ <Box className="section-body">
45
+ <CurrentSubscriptions id={data.id} onChange={runAsync} />
46
+ </Box>
47
+ </Box>
48
+ <Box className="section">
49
+ <SectionHeader title={t('customer.invoices')} mb={0} />
50
+ <Box className="section-body">
51
+ <CustomerInvoiceList customer_id={data.id} />
52
+ </Box>
53
+ </Box>
54
+ </Root>
55
+ </Grid>
56
+ <Grid item xs={12} md={4}>
57
+ <Root direction="column" spacing={4} sx={{ my: 2 }}>
58
+ <Box className="section">
59
+ <SectionHeader title={t('customer.details')}>
60
+ <Button
61
+ variant="outlined"
62
+ color="inherit"
63
+ size="small"
64
+ disabled={state.editing || state.loading}
65
+ onClick={() => setState({ editing: true })}>
66
+ <Edit fontSize="small" sx={{ mr: 0.5 }} />
67
+ {t('customer.update')}
68
+ </Button>
69
+ </SectionHeader>
70
+ <Stack>
71
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.name')} value={data.name} />
72
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.phone')} value={data.phone} />
73
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.email')} value={data.email} />
74
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.address.country')} value={data.address?.country} />
75
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.address.state')} value={data.address?.state} />
76
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.address.city')} value={data.address?.city} />
77
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.address.line1')} value={data.address?.line1} />
78
+ <InfoRow sizes={[1, 2]} label={t('admin.customer.address.line2')} value={data.address?.line2} />
79
+ <InfoRow
80
+ sizes={[1, 2]}
81
+ label={t('admin.customer.address.postal_code')}
82
+ value={data.address?.postal_code}
83
+ />
84
+ </Stack>
85
+ </Box>
86
+ </Root>
87
+ </Grid>
88
+ </Grid>
89
+ </Layout>
90
+ );
91
+ }
92
+
93
+ const Root = styled(Stack)``;
@@ -0,0 +1,147 @@
1
+ import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
2
+ import Toast from '@arcblock/ux/lib/Toast';
3
+ import type { TInvoiceExpanded } from '@did-pay/types';
4
+ import { ArrowBackOutlined } from '@mui/icons-material';
5
+ import { Alert, Box, Button, CircularProgress, Grid, Stack, Typography } from '@mui/material';
6
+ import { fromUnitToToken } from '@ocap/util';
7
+ import { useRequest, useSetState } from 'ahooks';
8
+ import { Link, useParams } from 'react-router-dom';
9
+
10
+ import Currency from '../../components/currency';
11
+ import InfoRow from '../../components/info-row';
12
+ import InvoiceTable from '../../components/invoice/table';
13
+ import Layout from '../../components/layout';
14
+ import SectionHeader from '../../components/section/header';
15
+ import Status from '../../components/status';
16
+ import { useSessionContext } from '../../contexts/session';
17
+ import api from '../../libs/api';
18
+ import { formatError, formatTime, getInvoiceStatusColor } from '../../libs/util';
19
+
20
+ const fetchData = (id: string): Promise<TInvoiceExpanded> => {
21
+ return api.get(`/api/invoices/${id}`).then((res) => res.data);
22
+ };
23
+
24
+ // TODO: download feature using: https://react-pdf.org/
25
+ export default function CustomerHome() {
26
+ const { t } = useLocaleContext();
27
+ const { connectApi } = useSessionContext();
28
+ const params = useParams<{ id: string }>();
29
+ const [state, setState] = useSetState({
30
+ downloading: false,
31
+ paying: false,
32
+ });
33
+
34
+ const { loading, error, data, runAsync } = useRequest(() => fetchData(params.id as string));
35
+
36
+ const onPay = () => {
37
+ try {
38
+ setState({ paying: true });
39
+ connectApi.open({
40
+ action: 'collect',
41
+ timeout: 5 * 60 * 1000,
42
+ extraParams: { invoiceId: params.id },
43
+ onSuccess: async () => {
44
+ connectApi.close();
45
+ await runAsync();
46
+ },
47
+ onClose: () => {
48
+ connectApi.close();
49
+ setState({ paying: false });
50
+ },
51
+ onError: (err: any) => {
52
+ setState({ paying: false });
53
+ Toast.error(formatError(err));
54
+ },
55
+ });
56
+ } catch (err) {
57
+ Toast.error(formatError(err));
58
+ } finally {
59
+ setState({ paying: false });
60
+ }
61
+ };
62
+
63
+ if (error) {
64
+ return <Alert severity="error">{formatError(error)}</Alert>;
65
+ }
66
+
67
+ if (loading || !data) {
68
+ return <CircularProgress />;
69
+ }
70
+
71
+ return (
72
+ <Layout>
73
+ <Grid container spacing={3} sx={{ mt: 1 }}>
74
+ <Grid item xs={12} md={12}>
75
+ <Link to="/customer">
76
+ <Stack direction="row" alignItems="center" sx={{ fontWeight: 'normal' }}>
77
+ <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
78
+ <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
79
+ {t('admin.invoices')}
80
+ </Typography>
81
+ </Stack>
82
+ </Link>
83
+ </Grid>
84
+ <Grid item xs={12} md={5}>
85
+ <Box>
86
+ <SectionHeader title={t('customer.invoice.summary')} mb={0} />
87
+ <Stack sx={{ mt: 1 }}>
88
+ <InfoRow label={t('admin.invoice.number')} value={data.number} />
89
+ <InfoRow label={t('admin.invoice.from')} value={data.statement_descriptor || blocklet.appName} />
90
+ <InfoRow label={t('admin.invoice.customer')} value={data.customer.name} />
91
+ <InfoRow
92
+ label={t('common.status')}
93
+ value={<Status label={data.status} color={getInvoiceStatusColor(data.status)} />}
94
+ />
95
+ <InfoRow
96
+ label={t('admin.subscription.currentPeriod')}
97
+ value={
98
+ data.period_start && data.period_end
99
+ ? [formatTime(data.period_start * 1000), formatTime(data.period_end * 1000)].join(' ~ ')
100
+ : ''
101
+ }
102
+ />
103
+ {data.status_transitions?.paid_at && (
104
+ <InfoRow label={t('admin.invoice.paidAt')} value={formatTime(data.status_transitions.paid_at * 1000)} />
105
+ )}
106
+ <InfoRow
107
+ label={t('admin.paymentCurrency.name')}
108
+ value={<Currency logo={data.paymentCurrency.logo} name={data.paymentCurrency.symbol} />}
109
+ />
110
+ <InfoRow
111
+ label={t('common.total')}
112
+ value={
113
+ <Typography component="span" fontWeight="bold">
114
+ {fromUnitToToken(data.total, data.paymentCurrency.decimal)}&nbsp;
115
+ {data.paymentCurrency.symbol}
116
+ </Typography>
117
+ }
118
+ />
119
+ </Stack>
120
+ </Box>
121
+ </Grid>
122
+ <Grid item xs={12} md={7}>
123
+ <SectionHeader title={t('customer.invoice.details')} mb={0}>
124
+ {['open'].includes(data.status) && (
125
+ <Button
126
+ variant="contained"
127
+ color="primary"
128
+ size="small"
129
+ disabled={state.downloading}
130
+ onClick={() => setState({ downloading: true })}>
131
+ {t('customer.invoice.download')}
132
+ </Button>
133
+ )}
134
+ </SectionHeader>
135
+ <InvoiceTable invoice={data} simple />
136
+ <Stack direction="row" justifyContent="flex-end" alignItems="center" mt={2}>
137
+ {['open', 'uncollectible'].includes(data.status) && (
138
+ <Button variant="contained" color="primary" disabled={state.paying} onClick={onPay}>
139
+ {t('customer.invoice.pay')}
140
+ </Button>
141
+ )}
142
+ </Stack>
143
+ </Grid>
144
+ </Grid>
145
+ </Layout>
146
+ );
147
+ }
@@ -0,0 +1,9 @@
1
+ function Home() {
2
+ return (
3
+ <pre style={{ textAlign: 'left' }}>
4
+ <code>window.blocklet = {JSON.stringify(window.blocklet, null, 2)}</code>
5
+ </pre>
6
+ );
7
+ }
8
+
9
+ export default Home;
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig",
3
+ "compilerOptions": {
4
+ "outDir": "api/dist",
5
+ "noEmit": false,
6
+ "noEmitOnError": true
7
+ },
8
+ "include": ["api/*.d.ts", "api/src"]
9
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig",
3
+ "compilerOptions": {
4
+ "noEmit": true
5
+ },
6
+ "include": [".eslintrc.js"]
7
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "ts-node": {
3
+ "files": true
4
+ },
5
+ "compilerOptions": {
6
+ /* Visit https://aka.ms/tsconfig to read more about this file */
7
+ /* Projects */
8
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
9
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
10
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
11
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
12
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
13
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
14
+ /* Language and Environment */
15
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
16
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
17
+ "jsx": "react-jsx" /* Specify what JSX code is generated. */,
18
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
19
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
+ /* Modules */
28
+ "module": "commonjs" /* Specify what module code is generated. */,
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "resolveJsonModule": true, /* Enable importing .json files. */
39
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40
+ /* JavaScript Support */
41
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
42
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
43
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
44
+ /* Emit */
45
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
50
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ "noEmit": true /* Disable emitting files from a compilation. */,
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ "importsNotUsedAsValues": "error",
55
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
56
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
57
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
58
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
59
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
61
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
62
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
63
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
64
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
65
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
66
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
67
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
68
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
69
+ /* Interop Constraints */
70
+ "isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
71
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
73
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
75
+ /* Type Checking */
76
+ "strict": true /* Enable all strict type-checking options. */,
77
+ "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
78
+ "strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */,
79
+ "strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */,
80
+ "strictBindCallApply": true /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */,
81
+ "strictPropertyInitialization": true /* Check for class properties that are declared but not set in the constructor. */,
82
+ "noImplicitThis": true /* Enable error reporting when 'this' is given the type 'any'. */,
83
+ "useUnknownInCatchVariables": false /* Default catch clause variables as 'unknown' instead of 'any'. */,
84
+ "alwaysStrict": true /* Ensure 'use strict' is always emitted. */,
85
+ "noUnusedLocals": true /* Enable error reporting when local variables aren't read. */,
86
+ "noUnusedParameters": true /* Raise an error when a function parameter isn't read. */,
87
+ // "exactOptionalPropertyTypes": false /* Interpret optional property types as written, rather than adding 'undefined'. */,
88
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
89
+ "noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
90
+ "noUncheckedIndexedAccess": true /* Add 'undefined' to a type when accessed using an index. */,
91
+ "noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
92
+ // "noPropertyAccessFromIndexSignature": true /* Enforces using indexed accessors for keys declared using an indexed type. */,
93
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
94
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
95
+ /* Completeness */
96
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
97
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
98
+ }
99
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "./tsconfig",
3
+ "compilerOptions": {
4
+ "outDir": "types",
5
+ "noEmit": false,
6
+ "declaration": true,
7
+ "emitDeclarationOnly": true,
8
+ "noEmitOnError": true
9
+ },
10
+ "include": ["api/*.d.ts", "api/src/store/models"]
11
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,19 @@
1
+ /* eslint-disable import/no-extraneous-dependencies */
2
+ import react from '@vitejs/plugin-react';
3
+ import { defineConfig } from 'vite';
4
+ import { createBlockletPlugin } from 'vite-plugin-blocklet';
5
+ import svgr from 'vite-plugin-svgr';
6
+
7
+ // https://vitejs.dev/config/
8
+ export default defineConfig(() => {
9
+ return {
10
+ plugins: [react(), createBlockletPlugin(), svgr()],
11
+ build: {
12
+ // 禁止 preload 可以解决 js 的请求没有 referer 的问题
13
+ cssCodeSplit: false,
14
+ commonjsOptions: {
15
+ transformMixedEsModules: true,
16
+ },
17
+ },
18
+ };
19
+ });