@tly-pay/vendure-plugin 0.0.0-stage → 1.0.0

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 (86) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +192 -2
  4. package/assets/coins/arb.svg +10 -0
  5. package/assets/coins/base.svg +4 -0
  6. package/assets/coins/bln.svg +4 -0
  7. package/assets/coins/bnb.svg +13 -0
  8. package/assets/coins/btc.svg +1 -0
  9. package/assets/coins/busd.svg +7 -0
  10. package/assets/coins/coin.svg +1 -0
  11. package/assets/coins/dai.svg +1 -0
  12. package/assets/coins/doge.svg +109 -0
  13. package/assets/coins/eth.svg +10 -0
  14. package/assets/coins/jst.svg +11 -0
  15. package/assets/coins/link.svg +4 -0
  16. package/assets/coins/ltc.svg +4 -0
  17. package/assets/coins/op.svg +12 -0
  18. package/assets/coins/pol.svg +11 -0
  19. package/assets/coins/shib.svg +18 -0
  20. package/assets/coins/sol.svg +15 -0
  21. package/assets/coins/sun.svg +71 -0
  22. package/assets/coins/trx.svg +4 -0
  23. package/assets/coins/uni.svg +10 -0
  24. package/assets/coins/usdc.svg +6 -0
  25. package/assets/coins/usdd.svg +18 -0
  26. package/assets/coins/usdt.svg +1 -0
  27. package/assets/coins/wbtc.svg +16 -0
  28. package/assets/coins/weth.svg +17 -0
  29. package/assets/tly-pay-mark.svg +31 -0
  30. package/dashboard/api.ts +167 -0
  31. package/dashboard/appearance.tsx +253 -0
  32. package/dashboard/banner.tsx +72 -0
  33. package/dashboard/i18n/en.po +584 -0
  34. package/dashboard/index.tsx +33 -0
  35. package/dashboard/logic.ts +219 -0
  36. package/dashboard/messages.tsx +90 -0
  37. package/dashboard/notice.tsx +15 -0
  38. package/dashboard/order-block.tsx +21 -0
  39. package/dashboard/orders.tsx +246 -0
  40. package/dashboard/page.tsx +174 -0
  41. package/dashboard/settings.tsx +186 -0
  42. package/dashboard/use-connect.ts +46 -0
  43. package/dist/api.d.ts +169 -0
  44. package/dist/api.js +541 -0
  45. package/dist/client-ref.d.ts +75 -0
  46. package/dist/client-ref.js +165 -0
  47. package/dist/connect-flow.d.ts +65 -0
  48. package/dist/connect-flow.js +177 -0
  49. package/dist/connection-check.d.ts +28 -0
  50. package/dist/connection-check.js +49 -0
  51. package/dist/connection.d.ts +140 -0
  52. package/dist/connection.js +361 -0
  53. package/dist/contracts.d.ts +66 -0
  54. package/dist/contracts.js +151 -0
  55. package/dist/creation-service.d.ts +136 -0
  56. package/dist/creation-service.js +242 -0
  57. package/dist/handler.d.ts +13 -0
  58. package/dist/handler.js +45 -0
  59. package/dist/hosted-checkout.d.ts +3 -0
  60. package/dist/hosted-checkout.js +25 -0
  61. package/dist/index.d.ts +11 -0
  62. package/dist/index.js +32 -0
  63. package/dist/ownership.d.ts +38 -0
  64. package/dist/ownership.js +38 -0
  65. package/dist/payment-sync.d.ts +45 -0
  66. package/dist/payment-sync.js +111 -0
  67. package/dist/persistence.d.ts +104 -0
  68. package/dist/persistence.js +405 -0
  69. package/dist/plugin.d.ts +26 -0
  70. package/dist/plugin.js +112 -0
  71. package/dist/public-api.d.ts +56 -0
  72. package/dist/public-api.js +221 -0
  73. package/dist/records.d.ts +53 -0
  74. package/dist/records.js +109 -0
  75. package/dist/release-config.d.ts +55 -0
  76. package/dist/release-config.js +107 -0
  77. package/dist/release-config.json +15 -0
  78. package/dist/secret-box.d.ts +19 -0
  79. package/dist/secret-box.js +65 -0
  80. package/dist/service.d.ts +267 -0
  81. package/dist/service.js +788 -0
  82. package/dist/signed-webhook.d.ts +67 -0
  83. package/dist/signed-webhook.js +119 -0
  84. package/dist/storefront/checkout.d.mts +86 -0
  85. package/dist/storefront/checkout.mjs +149 -0
  86. package/package.json +97 -4
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Dashboard logic without React or Dashboard globals: the popup relay of the account connection,
3
+ * callback parameters, status mapping and links. The consent page is cross-origin and its pages send
4
+ * Cross-Origin-Opener-Policy, which severs `window.opener` in the popup. The popup therefore completes
5
+ * the connection on the Dashboard origin itself and relays the result to the tab that opened it
6
+ * through BroadcastChannel and a localStorage write, then tries to close. The same policy hides the
7
+ * popup state from the tab (`popup.closed` turns true while it is still open), so the tab only waits
8
+ * for the relayed result. When the browser blocks the popup, the same flow runs in the current tab.
9
+ */
10
+ export const WINDOW_NAME = "tly-pay-connect"
11
+ export const CHANNEL = "tly-pay-connect"
12
+ export const STORAGE_KEY = "tly-pay-connect-result"
13
+ export const RESULT_TYPE = "tly-pay-connect-result"
14
+ /** Popup size of the consent page, as in the WooCommerce and Shopware plugins. */
15
+ export const POPUP_FEATURES = "popup,width=520,height=720"
16
+ /** Rows per page of the Orders view, as in the WooCommerce plugin. */
17
+ export const PAGE_SIZE = 20
18
+
19
+ const STATE = /^[A-Za-z0-9_-]{43}$/
20
+ const CODE = /^[a-z0-9_]{1,64}$/
21
+
22
+ /** Results shown as success; the rest are errors except the informational ones. */
23
+ export const SUCCESS_RESULTS = ["saved", "disconnected", "checkout_mode_saved", "checkout_icons_saved",
24
+ "checkout_icons_synced", "site_saved", "reconcile_scheduled", "payment_method_created"]
25
+ export const INFO_RESULTS = ["connection_cancelled"]
26
+
27
+ export type ConnectWindow = {
28
+ name: string
29
+ closed?: boolean
30
+ open(url: string, target: string, features: string): ConnectWindow | null
31
+ location: { href: string; assign(url: string): void }
32
+ focus?(): void
33
+ close(): void
34
+ localStorage: { setItem(key: string, value: string): void }
35
+ BroadcastChannel?: new (name: string) => { postMessage(message: unknown): void; close(): void; onmessage: ((event: { data: unknown }) => void) | null }
36
+ addEventListener(type: "storage", listener: (event: { key: string | null; newValue: string | null }) => void): void
37
+ removeEventListener(type: "storage", listener: (event: { key: string | null; newValue: string | null }) => void): void
38
+ }
39
+
40
+ export type ReturnParams =
41
+ | { popup: boolean; result: string }
42
+ | { popup: boolean; state: string; code: string }
43
+
44
+ export type RelayedResult = { result: string; retry: string }
45
+
46
+ /** Opens an empty popup synchronously from the click; null when the browser blocks it. */
47
+ export function openPopup(win: ConnectWindow): ConnectWindow | null {
48
+ try {
49
+ return win.open("", WINDOW_NAME, POPUP_FEATURES) ?? null
50
+ } catch {
51
+ return null
52
+ }
53
+ }
54
+
55
+ /** Sends the popup to the consent page, or this tab when no popup is open. */
56
+ export function navigate(win: ConnectWindow, popup: ConnectWindow | null, url: string): "popup" | "page" {
57
+ if (popup !== null && !popup.closed) {
58
+ popup.location.href = url
59
+ popup.focus?.()
60
+ return "popup"
61
+ }
62
+ win.location.assign(url)
63
+ return "page"
64
+ }
65
+
66
+ /** Reads the return of `/tly-pay/connect/return` from the page query; null when there is none. */
67
+ export function returnParams(search: string): ReturnParams | null {
68
+ const query = new URLSearchParams(search)
69
+ const value = (key: string) => query.get(key) ?? ""
70
+ const popup = value("tly_popup") === "1"
71
+ if (CODE.test(value("tly_result"))) return { popup, result: value("tly_result") }
72
+ if (!STATE.test(value("tly_state"))) return null
73
+ return { popup, state: value("tly_state"), code: value("tly_code") }
74
+ }
75
+
76
+ /** Relays a result from the popup and tries to close it; true when the window stays open. */
77
+ export function relay(win: ConnectWindow, message: RelayedResult): boolean {
78
+ const payload = { ...message, type: RESULT_TYPE }
79
+ try {
80
+ if (win.BroadcastChannel) {
81
+ const channel = new win.BroadcastChannel(CHANNEL)
82
+ channel.postMessage(payload)
83
+ channel.close()
84
+ }
85
+ } catch {
86
+ // The storage relay below still reaches the tab.
87
+ }
88
+ try {
89
+ win.localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...payload, at: Date.now() }))
90
+ } catch {
91
+ // The popup shows the result itself.
92
+ }
93
+ try {
94
+ win.close()
95
+ } catch {
96
+ // The page keeps showing the result when closing is refused.
97
+ }
98
+ return !win.closed
99
+ }
100
+
101
+ /** Calls `handler` with each relayed result; returns the function that stops listening. */
102
+ export function listen(win: ConnectWindow, handler: (message: RelayedResult) => void): () => void {
103
+ const accept = (message: unknown) => {
104
+ const value = message as Partial<RelayedResult & { type: string }> | null
105
+ if (value && value.type === RESULT_TYPE && CODE.test(value.result ?? "")) {
106
+ handler({ result: value.result as string, retry: typeof value.retry === "string" && STATE.test(value.retry) ? value.retry : "" })
107
+ }
108
+ }
109
+ let channel: InstanceType<NonNullable<ConnectWindow["BroadcastChannel"]>> | null = null
110
+ if (win.BroadcastChannel) {
111
+ channel = new win.BroadcastChannel(CHANNEL)
112
+ channel.onmessage = (event) => accept(event.data)
113
+ }
114
+ const onStorage = (event: { key: string | null; newValue: string | null }) => {
115
+ if (event.key !== STORAGE_KEY || !event.newValue) return
116
+ try { accept(JSON.parse(event.newValue)) } catch { /* Ignore foreign storage values. */ }
117
+ }
118
+ win.addEventListener("storage", onStorage)
119
+ return () => {
120
+ channel?.close()
121
+ win.removeEventListener("storage", onStorage)
122
+ }
123
+ }
124
+
125
+ export function resultTone(result: string): "success" | "info" | "error" {
126
+ if (SUCCESS_RESULTS.includes(result)) return "success"
127
+ return INFO_RESULTS.includes(result) ? "info" : "error"
128
+ }
129
+
130
+ /**
131
+ * A checkout icon option of the Checkout appearance panel, as the Admin API lists them: in the order
132
+ * checkout shows the icons, with whether the TLY Pay Store accepts the coin now.
133
+ */
134
+ export type IconOption = { mark: string; label: string; iconUrl: string; accepted: boolean }
135
+
136
+ /** The checkout icon selection after checking or unchecking one coin tile. */
137
+ export function toggleMark(selected: string[], mark: string, checked: boolean): string[] {
138
+ if (!checked) return selected.filter((value) => value !== mark)
139
+ return selected.includes(mark) ? selected : [...selected, mark]
140
+ }
141
+
142
+ /** Whether two checkout icon selections hold the same marks; their order does not matter. */
143
+ export function sameMarks(a: string[], b: string[]): boolean {
144
+ const set = new Set(a)
145
+ return set.size === new Set(b).size && b.every((mark) => set.has(mark))
146
+ }
147
+
148
+ /** The icons checkout shows for a selection: every selected option, accepted or not, in option order. */
149
+ export function shownIcons(options: IconOption[], selected: string[]): IconOption[] {
150
+ return options.filter((option) => selected.includes(option.mark))
151
+ }
152
+
153
+ /**
154
+ * The one note under the coin tiles: the selected coins the Store does not accept, named by their
155
+ * labels; that no icon is selected; or none.
156
+ */
157
+ export function selectionNote(options: IconOption[], selected: string[]):
158
+ { kind: "unaccepted"; labels: string[] } | { kind: "none" } | null {
159
+ const shown = shownIcons(options, selected)
160
+ if (shown.length === 0) return { kind: "none" }
161
+ const labels = shown.filter((option) => !option.accepted).map((option) => option.label)
162
+ return labels.length > 0 ? { kind: "unaccepted", labels } : null
163
+ }
164
+
165
+ /**
166
+ * The labels the coin names sentence lists. It always agrees with the icons: the icons shown, or the
167
+ * coins the Store accepts while no icon is selected; empty when the Store accepts none either.
168
+ */
169
+ export function coinNameLabels(options: IconOption[], selected: string[]): string[] {
170
+ const shown = shownIcons(options, selected)
171
+ return (shown.length > 0 ? shown : options.filter((option) => option.accepted)).map((option) => option.label)
172
+ }
173
+
174
+ /** Joins labels with the list format of a locale: "USDT and USDC", "USDT, USDC, and DAI" in English. */
175
+ export function listText(labels: string[], locale: string): string {
176
+ const join = (tag: string) => new Intl.ListFormat(tag, { style: "long", type: "conjunction" }).format(labels)
177
+ try {
178
+ return join(locale.replace(/_/g, "-"))
179
+ } catch {
180
+ return join("en")
181
+ }
182
+ }
183
+
184
+ /** Badge tone of an Orders row: the creation state until a Payment exists, then its status. */
185
+ export function rowBadge(state: string, status: string | null): { key: string; tone: "ok" | "pending" | "warn" | "off" | "muted" } {
186
+ if (state === "creating") return { key: "creating", tone: "warn" }
187
+ if (state === "failed") return { key: "creation_failed", tone: "warn" }
188
+ return statusBadge(status ?? "open")
189
+ }
190
+
191
+ export function statusBadge(status: string): { key: string; tone: "ok" | "pending" | "warn" | "off" | "muted" } {
192
+ switch (status) {
193
+ case "paid": return { key: status, tone: "ok" }
194
+ case "partially_paid":
195
+ case "overpaid":
196
+ case "review_required": return { key: status, tone: "pending" }
197
+ case "expired":
198
+ case "cancelled": return { key: status, tone: "muted" }
199
+ default: return { key: "open", tone: "off" }
200
+ }
201
+ }
202
+
203
+ /**
204
+ * The header action of the TLY Pay page: Connect TLY Pay until the store is connected (as the
205
+ * WooCommerce onboarding banner and the Medusa page header do), then Open TLY Pay account when the
206
+ * release packages an app Origin; nothing while the status is unknown.
207
+ */
208
+ export function headerAction(status: { connected: boolean; consoleOrigin: string } | null): "connect" | "account" | null {
209
+ if (status === null) return null
210
+ if (!status.connected) return "connect"
211
+ return status.consoleOrigin === "" ? null : "account"
212
+ }
213
+
214
+ /** Deep link to the Payment detail in the TLY Pay app, or "" without a packaged app Origin. */
215
+ export function paymentUrl(consoleOrigin: string, paymentId: string): string {
216
+ return consoleOrigin === "" ? "" : `${consoleOrigin}/payments/detail?resource=payments&ref=${encodeURIComponent(paymentId)}`
217
+ }
218
+
219
+ export const ORDER_FILTERS = ["all", "open", "paid", "attention", "closed", "creating"] as const
@@ -0,0 +1,90 @@
1
+ import { useLingui } from "@lingui/react/macro"
2
+
3
+ /** Translatable copy of the extension, shared by the page, the banner and the Order block. */
4
+ export function useCopy() {
5
+ const { t } = useLingui()
6
+ const currency = t`Use the same fiat currency in your Vendure Channel and your TLY Pay store, then reconnect.`
7
+ const invalid = t`TLY Pay returned an invalid response. The previous configuration was kept.`
8
+ const results: Record<string, string> = {
9
+ platform_store_inactive: t`Activate your store in TLY Pay, then reconnect.`,
10
+ platform_currency_mismatch: currency,
11
+ platform_webhook_mismatch: t`In TLY Pay, open Integrations > Webhooks and enable the payment notification endpoint for this website. Then reconnect TLY Pay.`,
12
+ connection_unavailable: t`Connection is unavailable. Install the current TLY Pay plugin release.`,
13
+ connection_unreadable: t`The saved connection cannot be read because the plugin secret key changed. Reconnect TLY Pay.`,
14
+ connection_expired: t`This connection request expired. Click Connect TLY Pay to start again.`,
15
+ connection_cancelled: t`The connection was cancelled. Your existing configuration was kept.`,
16
+ saved: t`TLY Pay was connected and validated.`,
17
+ disconnected: t`TLY Pay was disconnected. Connect an account to accept payments again.`,
18
+ disconnect_unconfirmed: t`Confirm that you understand the consequences before disconnecting.`,
19
+ checkout_mode_saved: t`Checkout mode saved.`,
20
+ checkout_mode_invalid: t`Choose a valid checkout mode.`,
21
+ checkout_icons_saved: t`Checkout appearance saved.`,
22
+ checkout_icons_invalid: t`Choose checkout icons from the list.`,
23
+ checkout_icons_synced: t`Checkout icons now match the coins your TLY Pay store accepts.`,
24
+ site_saved: t`Site saved. Reconnect.`,
25
+ site_invalid: t`Choose Standard or Test.`,
26
+ payment_method_created: t`The Crypto payment method was added to this Channel.`,
27
+ payment_method_exists: t`This Channel already has a TLY Pay payment method.`,
28
+ payment_method_invalid: t`Enter a name for the payment method.`,
29
+ reconcile_scheduled: t`Reconciliation requested. The order updates when the latest payment status is received.`,
30
+ reconcile_unavailable: t`This order has no TLY Pay payment to reconcile yet.`,
31
+ reconcile_failed: t`Reconciliation could not be scheduled. Try again in a few minutes.`,
32
+ api_key_required: t`Authorize the connection again to obtain valid payment credentials.`,
33
+ invalid_api_key: t`The payment credential is invalid. Authorize the connection again.`,
34
+ unauthorized: t`Payment credentials were rejected. Reconnect TLY Pay to authorize this store again.`,
35
+ forbidden: t`Payment permissions are missing. Reconnect TLY Pay and approve the requested permissions.`,
36
+ store_inactive: t`Your store is inactive in TLY Pay. Activate it in your account, then reload this page.`,
37
+ fiat_required: currency,
38
+ currency_mismatch: currency,
39
+ store_identity_mismatch: t`This authorization belongs to a different TLY Pay store than the one connected to this website. Disconnect TLY Pay before connecting a different store. The previous configuration was kept.`,
40
+ invalid_webhook_endpoint_id: invalid,
41
+ webhook_endpoint_mismatch: t`The payment notification endpoint for this website was not found in TLY Pay. Reconnect TLY Pay to restore it.`,
42
+ webhook_secret_invalid: t`Payment notification credentials have changed. Reconnect TLY Pay to synchronize them.`,
43
+ duplicate_webhook_secret: invalid,
44
+ webhook_endpoint_inactive: t`Payment notifications are disabled in TLY Pay. Enable them in your account, then reload this page.`,
45
+ webhook_url_changed: t`The public URL of this Vendure server changed since it was connected. Reconnect TLY Pay.`,
46
+ invalid_webhook_binding: invalid,
47
+ https_required: t`TLY Pay must reach your Vendure server over public HTTPS to send payment notifications, so local or IP addresses such as http://127.0.0.1 cannot be connected. Set the plugin publicUrl to the public https:// URL of this server, then connect again.`,
48
+ invalid_webhook_secret: invalid,
49
+ invalid_store_context: invalid,
50
+ invalid_webhook_response: invalid,
51
+ invalid_response: invalid,
52
+ persistence_failed: t`Vendure could not save the configuration. Try again; the previous configuration was kept.`,
53
+ }
54
+ return {
55
+ result(code: string, apiHost: string): string {
56
+ if (code === "upstream_unavailable") {
57
+ return t`Your Vendure server could not reach TLY Pay at ${apiHost}. Check that the hosting firewall allows outbound HTTPS and that the server certificates are current, then try again. The previous configuration was kept.`
58
+ }
59
+ return results[code]
60
+ ?? t`TLY Pay could not validate the connection. Reload this page to check again. If the problem continues, reconnect TLY Pay.`
61
+ },
62
+ pill(state: string): string {
63
+ switch (state) {
64
+ case "ok": return t`Connected`
65
+ case "pending": return t`Wallet setup needed`
66
+ case "warn": return t`Needs attention`
67
+ default: return t`Not connected`
68
+ }
69
+ },
70
+ status(key: string): string {
71
+ const labels: Record<string, string> = {
72
+ open: t`Open`, paid: t`Paid`, partially_paid: t`Partially paid`, overpaid: t`Overpaid`,
73
+ review_required: t`Review required`, expired: t`Expired`, cancelled: t`Cancelled`, creating: t`Creating`,
74
+ creation_failed: t`Creation failed`,
75
+ }
76
+ return labels[key] ?? key
77
+ },
78
+ filter(key: string): string {
79
+ const labels: Record<string, string> = {
80
+ all: t`All`, open: t`Open`, paid: t`Paid`, attention: t`Needs attention`, closed: t`Closed`, creating: t`Creating`,
81
+ }
82
+ return labels[key] ?? key
83
+ },
84
+ mode(mode: string): string {
85
+ return mode === "embedded" ? t`Embedded` : t`Hosted`
86
+ },
87
+ walletSetup: t`Your store is connected. Finish the wallet setup in TLY Pay to start accepting payments; TLY Pay is not offered at checkout until then.`,
88
+ unverified: t`TLY Pay could not be verified just now; checkout stays available and the next check runs automatically.`,
89
+ }
90
+ }
@@ -0,0 +1,15 @@
1
+ import { Alert, AlertDescription } from "@vendure/dashboard"
2
+ import { resultTone } from "./logic"
3
+ import { useCopy } from "./messages"
4
+
5
+ /** Result notice of a connection, settings or reconcile action. */
6
+ export function ResultNotice({ result, apiHost }: { result: string; apiHost: string }) {
7
+ const copy = useCopy()
8
+ if (result === "") return null
9
+ const tone = resultTone(result)
10
+ return (
11
+ <Alert variant={tone === "error" ? "destructive" : "default"} role={tone === "error" ? "alert" : "status"}>
12
+ <AlertDescription>{copy.result(result, apiHost)}</AlertDescription>
13
+ </Alert>
14
+ )
15
+ }
@@ -0,0 +1,21 @@
1
+ import { Trans } from "@lingui/react/macro"
2
+ import { Link } from "@vendure/dashboard"
3
+ import { useEffect, useState } from "react"
4
+ import { orderIntent } from "./api"
5
+ import { PAGE_PATH } from "./use-connect"
6
+
7
+ /** Side block of the Vendure Order detail page linking to the TLY Pay payment of the Order. */
8
+ export function TlyPayOrderBlock({ orderCode }: { orderCode: string | undefined }) {
9
+ const [intent, setIntent] = useState<string | null | undefined>(undefined)
10
+ useEffect(() => {
11
+ if (orderCode === undefined) return
12
+ orderIntent(orderCode).then(setIntent, () => setIntent(null))
13
+ }, [orderCode])
14
+ if (intent === undefined) return null
15
+ if (intent === null) return <p className="text-sm text-muted-foreground"><Trans>No TLY Pay payment is linked to this order.</Trans></p>
16
+ return (
17
+ <Link className="text-sm underline" to={PAGE_PATH} search={{ payment: intent } as never}>
18
+ <Trans>Show TLY Pay payment, live status and notifications</Trans>
19
+ </Link>
20
+ )
21
+ }
@@ -0,0 +1,246 @@
1
+ import { Trans, useLingui } from "@lingui/react/macro"
2
+ import {
3
+ Alert, AlertDescription, Badge, Button, Card, CardContent, CardHeader, CardTitle, Link, Table, TableBody, TableCell,
4
+ TableHead, TableHeader, TableRow, useLocalFormat,
5
+ } from "@vendure/dashboard"
6
+ import { ReactNode, useCallback, useEffect, useState } from "react"
7
+ import { listOrders, OrderCounts, OrderDetail, OrderRow, readOrder, reconcile } from "./api"
8
+ import { ORDER_FILTERS, PAGE_SIZE, paymentUrl, rowBadge, statusBadge } from "./logic"
9
+ import { useCopy } from "./messages"
10
+ import { ResultNotice } from "./notice"
11
+
12
+ /** Badge variants of the Dashboard design system v2, whose `default` Badge is the neutral one. */
13
+ const TONE = { ok: "success", pending: "warning", warn: "destructive", off: "outline", muted: "default" } as const
14
+
15
+ function StatusBadge({ badge }: { badge: { key: string; tone: keyof typeof TONE } }) {
16
+ const copy = useCopy()
17
+ return <Badge variant={TONE[badge.tone]}>{copy.status(badge.key)}</Badge>
18
+ }
19
+
20
+ function PaymentLink({ consoleOrigin, paymentId }: { consoleOrigin: string; paymentId: string | null }) {
21
+ if (paymentId === null) return <span className="text-muted-foreground">-</span>
22
+ const url = paymentUrl(consoleOrigin, paymentId)
23
+ return url === "" ? <code>{paymentId}</code>
24
+ : <a className="font-mono underline" href={url} target="_blank" rel="noopener noreferrer">{paymentId}</a>
25
+ }
26
+
27
+ function OrderLink({ row }: { row: OrderRow }) {
28
+ return row.orderId === null ? <span>{row.orderCode}</span>
29
+ : <Link className="underline" to={`/orders/${row.orderId}`}>{row.orderCode}</Link>
30
+ }
31
+
32
+ /**
33
+ * Orders tab: the TLY Pay payments of the local records, newest first, with status filters and
34
+ * pagination, and the detail of one payment. The list makes no request to TLY Pay.
35
+ */
36
+ export function OrdersTab({ consoleOrigin, apiHost }: { consoleOrigin: string; apiHost: string }) {
37
+ const [detail, setDetail] = useState<string | null>(new URLSearchParams(window.location.search).get("payment"))
38
+ const open = (id: string | null) => {
39
+ setDetail(id)
40
+ window.history.replaceState(null, "", window.location.pathname + (id === null ? "" : `?payment=${encodeURIComponent(id)}`))
41
+ }
42
+ return detail === null
43
+ ? <OrdersList consoleOrigin={consoleOrigin} onOpen={open} />
44
+ : <PaymentDetail id={detail} consoleOrigin={consoleOrigin} apiHost={apiHost} onBack={() => open(null)} />
45
+ }
46
+
47
+ function OrdersList({ consoleOrigin, onOpen }: { consoleOrigin: string; onOpen: (id: string) => void }) {
48
+ const { t } = useLingui()
49
+ const copy = useCopy()
50
+ const { formatCurrency, formatDate } = useLocalFormat()
51
+ const [filter, setFilter] = useState<string>("all")
52
+ const [page, setPage] = useState(0)
53
+ const [data, setData] = useState<{ items: OrderRow[]; totalItems: number; counts: OrderCounts } | null>(null)
54
+ const [failed, setFailed] = useState(false)
55
+
56
+ useEffect(() => {
57
+ let current = true
58
+ listOrders(filter, page * PAGE_SIZE, PAGE_SIZE)
59
+ .then((next) => { if (current) { setData(next); setFailed(false) } }, () => { if (current) setFailed(true) })
60
+ return () => { current = false }
61
+ }, [filter, page])
62
+
63
+ const pages = data === null ? 1 : Math.max(1, Math.ceil(data.totalItems / PAGE_SIZE))
64
+ return (
65
+ <div className="flex flex-col gap-3">
66
+ <nav className="flex flex-wrap gap-2" aria-label={t`Filter by status`}>
67
+ {ORDER_FILTERS.map((key) => (
68
+ <Button key={key} size="sm" variant={filter === key ? "default" : "outline"} aria-pressed={filter === key}
69
+ onClick={() => { setFilter(key); setPage(0) }}>
70
+ {copy.filter(key)} <span className="text-xs opacity-70">({data?.counts[key] ?? 0})</span>
71
+ </Button>
72
+ ))}
73
+ </nav>
74
+ {failed && <Alert variant="destructive"><AlertDescription><Trans>The TLY Pay order records could not be read. Reload this page to try again.</Trans></AlertDescription></Alert>}
75
+ <Table>
76
+ <TableHeader>
77
+ <TableRow>
78
+ <TableHead><Trans>Order</Trans></TableHead>
79
+ <TableHead><Trans>Status</Trans></TableHead>
80
+ <TableHead><Trans>Amount</Trans></TableHead>
81
+ <TableHead><Trans>Checkout</Trans></TableHead>
82
+ <TableHead><Trans>Payment ID</Trans></TableHead>
83
+ <TableHead><Trans>Updated</Trans></TableHead>
84
+ <TableHead><span className="sr-only"><Trans>Details</Trans></span></TableHead>
85
+ </TableRow>
86
+ </TableHeader>
87
+ <TableBody>
88
+ {data !== null && data.items.length === 0 && (
89
+ // The empty state only explains; connecting is the header's action, so the page has one Connect button.
90
+ <TableRow className="hover:bg-transparent">
91
+ <TableCell colSpan={7} className="py-12 text-center whitespace-normal">
92
+ {filter === "all" ? (
93
+ <>
94
+ <p className="text-sm font-medium"><Trans>No TLY Pay payments yet</Trans></p>
95
+ <p className="mt-1 text-sm text-muted-foreground">
96
+ <Trans>Payments appear here when customers choose Crypto payment.</Trans>
97
+ </p>
98
+ </>
99
+ ) : (
100
+ <p className="text-sm text-muted-foreground"><Trans>No payments match this filter.</Trans></p>
101
+ )}
102
+ </TableCell>
103
+ </TableRow>
104
+ )}
105
+ {data?.items.map((row) => (
106
+ <TableRow key={row.id}>
107
+ <TableCell><OrderLink row={row} /></TableCell>
108
+ <TableCell><StatusBadge badge={rowBadge(row.state, row.status)} /></TableCell>
109
+ <TableCell>{row.amountRaw === "" ? "-" : formatCurrency(Number(row.amountRaw), row.currency)}</TableCell>
110
+ <TableCell>{copy.mode(row.checkoutMode)}</TableCell>
111
+ <TableCell><PaymentLink consoleOrigin={consoleOrigin} paymentId={row.paymentId} /></TableCell>
112
+ <TableCell>{formatDate(row.updatedAt, { dateStyle: "medium", timeStyle: "short" })}</TableCell>
113
+ <TableCell><Button size="sm" variant="ghost" onClick={() => onOpen(row.id)}><Trans>Details</Trans></Button></TableCell>
114
+ </TableRow>
115
+ ))}
116
+ </TableBody>
117
+ </Table>
118
+ {pages > 1 && (
119
+ <div className="flex items-center justify-end gap-2 text-sm">
120
+ <Button size="sm" variant="outline" disabled={page === 0} onClick={() => setPage(page - 1)}><Trans>Previous</Trans></Button>
121
+ <span><Trans>Page {page + 1} of {pages}</Trans></span>
122
+ <Button size="sm" variant="outline" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}><Trans>Next</Trans></Button>
123
+ </div>
124
+ )}
125
+ </div>
126
+ )
127
+ }
128
+
129
+ function Fact({ label, children }: { label: string; children: ReactNode }) {
130
+ return (
131
+ <div className="grid grid-cols-[12rem_1fr] gap-2 py-1 text-sm">
132
+ <dt className="text-muted-foreground">{label}</dt>
133
+ <dd className="break-all">{children}</dd>
134
+ </div>
135
+ )
136
+ }
137
+
138
+ /**
139
+ * One payment: local facts, the live status read once from `GET /v1/payments/{id}`, the
140
+ * notifications received for it and the Reconcile action when the live version is newer.
141
+ */
142
+ function PaymentDetail({ id, consoleOrigin, apiHost, onBack }: { id: string; consoleOrigin: string; apiHost: string;
143
+ onBack: () => void }) {
144
+ const { t } = useLingui()
145
+ const copy = useCopy()
146
+ const { formatCurrency, formatDate } = useLocalFormat()
147
+ const [detail, setDetail] = useState<OrderDetail | null | undefined>(undefined)
148
+ const [result, setResult] = useState("")
149
+ const [busy, setBusy] = useState(false)
150
+
151
+ const load = useCallback(() => {
152
+ readOrder(id).then(setDetail, () => setDetail(null))
153
+ }, [id])
154
+ useEffect(load, [load])
155
+
156
+ const requestReconcile = async () => {
157
+ setBusy(true)
158
+ try {
159
+ setResult((await reconcile(id)).result)
160
+ } catch {
161
+ setResult("reconcile_failed")
162
+ } finally {
163
+ setBusy(false)
164
+ }
165
+ }
166
+
167
+ const back = <div><Button variant="ghost" size="sm" onClick={onBack}>&larr; <Trans>All TLY Pay orders</Trans></Button></div>
168
+ if (detail === undefined) return back
169
+ if (detail === null) {
170
+ return <div className="flex flex-col gap-3">{back}<Alert variant="destructive"><AlertDescription>
171
+ <Trans>No TLY Pay payment is linked to this order.</Trans></AlertDescription></Alert></div>
172
+ }
173
+ const row = detail.row
174
+ const live = detail.live
175
+ return (
176
+ <div className="flex flex-col gap-4">
177
+ {back}
178
+ <ResultNotice result={result} apiHost={apiHost} />
179
+ <div className="grid gap-4 lg:grid-cols-2">
180
+ <Card>
181
+ <CardHeader><CardTitle><Trans>Order {row.orderCode}</Trans></CardTitle></CardHeader>
182
+ <CardContent><dl>
183
+ <Fact label={t`Vendure order`}><OrderLink row={row} />{row.orderState !== null && <span className="text-muted-foreground"> - {row.orderState}</span>}</Fact>
184
+ <Fact label={t`Payment ID`}><PaymentLink consoleOrigin={consoleOrigin} paymentId={row.paymentId} /></Fact>
185
+ <Fact label={t`Applied status`}><StatusBadge badge={rowBadge(row.state, row.status)} /> <span className="text-muted-foreground"><Trans>version {row.statusVersion}</Trans></span></Fact>
186
+ <Fact label={t`Amount`}>{row.amountRaw === "" ? "-" : formatCurrency(Number(row.amountRaw), row.currency)}</Fact>
187
+ <Fact label={t`Checkout`}>{copy.mode(row.checkoutMode)}{detail.checkoutOrigin !== null && <span className="text-muted-foreground"> - {detail.checkoutOrigin}</span>}</Fact>
188
+ {detail.returnUrl !== null && <Fact label={t`Return page`}>{detail.returnUrl}</Fact>}
189
+ <Fact label={t`Installation reference`}><code>{detail.clientRef ?? "-"}</code></Fact>
190
+ {row.err !== null && <Fact label={t`Creation error`}><Trans>TLY Pay rejected the payment request ({row.err}). The customer can place the order again to retry.</Trans></Fact>}
191
+ {row.settleErr !== null && <Fact label={t`Settlement`}><Trans>The paid payment could not be added to the Vendure order ({row.settleErr}). Review the order.</Trans></Fact>}
192
+ {row.settledAt !== null && <Fact label={t`Settled`}>{formatDate(row.settledAt, { dateStyle: "medium", timeStyle: "short" })}</Fact>}
193
+ </dl></CardContent>
194
+ </Card>
195
+ <Card>
196
+ <CardHeader><CardTitle><Trans>Live status</Trans></CardTitle></CardHeader>
197
+ <CardContent className="flex flex-col gap-3">
198
+ {live === null ? (
199
+ <p className="text-sm text-muted-foreground">{row.paymentId === null
200
+ ? <Trans>TLY Pay has not created this payment yet.</Trans>
201
+ : <Trans>TLY Pay could not be reached just now; the local facts are shown.</Trans>}</p>
202
+ ) : (
203
+ <dl>
204
+ <Fact label={t`Status`}><StatusBadge badge={statusBadge(live.status)} /> <span className="text-muted-foreground"><Trans>version {live.statusVersion}</Trans></span></Fact>
205
+ <Fact label={t`Activated`}>{live.activatedAt === null ? "-" : formatDate(live.activatedAt, { dateStyle: "medium", timeStyle: "short" })}</Fact>
206
+ <Fact label={t`Expires`}>{formatDate(live.paymentExpiresAt, { dateStyle: "medium", timeStyle: "short" })}</Fact>
207
+ <Fact label={t`Updated`}>{formatDate(live.updatedAt, { dateStyle: "medium", timeStyle: "short" })}</Fact>
208
+ </dl>
209
+ )}
210
+ {live !== null && live.statusVersion !== row.statusVersion && (
211
+ <div><Button disabled={busy} onClick={() => void requestReconcile()}><Trans>Reconcile</Trans></Button></div>
212
+ )}
213
+ <p className="text-xs text-muted-foreground"><Trans>On-chain transfers are shown in TLY Pay.</Trans></p>
214
+ </CardContent>
215
+ </Card>
216
+ </div>
217
+ <Card>
218
+ <CardHeader><CardTitle><Trans>Notifications</Trans></CardTitle></CardHeader>
219
+ <CardContent>
220
+ {detail.events.length === 0 ? <p className="text-sm text-muted-foreground"><Trans>No notification has been received for this payment yet.</Trans></p> : (
221
+ <Table>
222
+ <TableHeader><TableRow>
223
+ <TableHead><Trans>Status</Trans></TableHead>
224
+ <TableHead><Trans>Version</Trans></TableHead>
225
+ <TableHead><Trans>Occurred</Trans></TableHead>
226
+ <TableHead><Trans>Received</Trans></TableHead>
227
+ <TableHead><Trans>Processing</Trans></TableHead>
228
+ </TableRow></TableHeader>
229
+ <TableBody>
230
+ {detail.events.map((event) => (
231
+ <TableRow key={event.eventId}>
232
+ <TableCell><StatusBadge badge={statusBadge(event.status)} /></TableCell>
233
+ <TableCell>{event.statusVersion}</TableCell>
234
+ <TableCell>{formatDate(event.occurredAt, { dateStyle: "medium", timeStyle: "short" })}</TableCell>
235
+ <TableCell>{formatDate(event.receivedAt, { dateStyle: "medium", timeStyle: "short" })}</TableCell>
236
+ <TableCell>{event.outcome === null ? <Trans>Pending</Trans> : event.outcome === "applied" ? <Trans>Applied</Trans> : event.outcome}</TableCell>
237
+ </TableRow>
238
+ ))}
239
+ </TableBody>
240
+ </Table>
241
+ )}
242
+ </CardContent>
243
+ </Card>
244
+ </div>
245
+ )
246
+ }