@fantastic.dev/better-stripe 0.8.1 → 0.9.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.
- package/CHANGELOG.md +6 -0
- package/README.md +18 -2
- package/dist/component/_generated/component.d.ts +35 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/connect/queries.d.ts +30 -1
- package/dist/component/connect/queries.d.ts.map +1 -1
- package/dist/component/connect/queries.js +19 -2
- package/dist/component/connect/queries.js.map +1 -1
- package/dist/react/workflows/AffiliatePayoutEditor.d.ts +41 -0
- package/dist/react/workflows/AffiliatePayoutEditor.d.ts.map +1 -0
- package/dist/react/workflows/AffiliatePayoutEditor.js +80 -0
- package/dist/react/workflows/AffiliatePayoutEditor.js.map +1 -0
- package/dist/react/workflows/AffiliateRateEditor.d.ts +26 -0
- package/dist/react/workflows/AffiliateRateEditor.d.ts.map +1 -0
- package/dist/react/workflows/AffiliateRateEditor.js +49 -0
- package/dist/react/workflows/AffiliateRateEditor.js.map +1 -0
- package/dist/react/workflows/CheckoutForms.d.ts +2 -0
- package/dist/react/workflows/CheckoutForms.d.ts.map +1 -1
- package/dist/react/workflows/CheckoutForms.js +22 -16
- package/dist/react/workflows/CheckoutForms.js.map +1 -1
- package/dist/react/workflows/IntegrationSwitch.js +2 -2
- package/dist/react/workflows/IntegrationSwitch.js.map +1 -1
- package/dist/react/workflows/Pagination.d.ts +32 -0
- package/dist/react/workflows/Pagination.d.ts.map +1 -0
- package/dist/react/workflows/Pagination.js +49 -0
- package/dist/react/workflows/Pagination.js.map +1 -0
- package/dist/react/workflows/PlanPricingEditor.d.ts +35 -0
- package/dist/react/workflows/PlanPricingEditor.d.ts.map +1 -0
- package/dist/react/workflows/PlanPricingEditor.js +64 -0
- package/dist/react/workflows/PlanPricingEditor.js.map +1 -0
- package/dist/react/workflows/index.d.ts +8 -0
- package/dist/react/workflows/index.d.ts.map +1 -1
- package/dist/react/workflows/index.js +4 -0
- package/dist/react/workflows/index.js.map +1 -1
- package/docs/react-workflows-audit.md +19 -0
- package/docs/react-workflows.md +89 -1
- package/package.json +5 -4
- package/src/component/_generated/component.ts +41 -0
- package/src/component/connect/queries.ts +26 -2
- package/src/component/earnings-totals.test.ts +13 -0
- package/src/component/transfers.test.ts +48 -0
- package/src/react/workflows/AffiliatePayoutEditor.test.tsx +90 -0
- package/src/react/workflows/AffiliatePayoutEditor.tsx +201 -0
- package/src/react/workflows/AffiliateRateEditor.test.tsx +36 -0
- package/src/react/workflows/AffiliateRateEditor.tsx +92 -0
- package/src/react/workflows/CheckoutForms.test.tsx +40 -0
- package/src/react/workflows/CheckoutForms.tsx +37 -16
- package/src/react/workflows/IntegrationSwitch.test.tsx +25 -0
- package/src/react/workflows/IntegrationSwitch.tsx +2 -2
- package/src/react/workflows/Pagination.test.tsx +53 -0
- package/src/react/workflows/Pagination.tsx +93 -0
- package/src/react/workflows/PlanPricingEditor.test.tsx +79 -0
- package/src/react/workflows/PlanPricingEditor.tsx +156 -0
- package/src/react/workflows/index.ts +22 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useId, useState, type ReactNode } from "react";
|
|
3
|
+
import { useWorkflowAction } from "./useWorkflowAction.js";
|
|
4
|
+
export type AffiliateRateUpdate = {
|
|
5
|
+
affiliateBasisPoints: number | null;
|
|
6
|
+
expectedVersion: number;
|
|
7
|
+
};
|
|
8
|
+
export type AffiliateRateEditorState = {
|
|
9
|
+
percentage: string;
|
|
10
|
+
setPercentage: (value: string) => void;
|
|
11
|
+
effectiveLabel: string;
|
|
12
|
+
isPending: boolean;
|
|
13
|
+
error: string | null;
|
|
14
|
+
message: string | undefined;
|
|
15
|
+
save: () => Promise<unknown>;
|
|
16
|
+
};
|
|
17
|
+
export type AffiliateRateEditorProps = {
|
|
18
|
+
scopeKey: string;
|
|
19
|
+
affiliateBasisPoints: number | null;
|
|
20
|
+
effectiveBasisPoints: number;
|
|
21
|
+
source: "plan" | "product" | "price" | "store" | "global" | "none";
|
|
22
|
+
version: number;
|
|
23
|
+
onSave: (update: AffiliateRateUpdate) => Promise<unknown>;
|
|
24
|
+
children?: (state: AffiliateRateEditorState) => ReactNode;
|
|
25
|
+
};
|
|
26
|
+
/** Unstyled nullable commission editor. Blank inherits the next applicable rate. */
|
|
27
|
+
export function AffiliateRateEditor(props: AffiliateRateEditorProps) {
|
|
28
|
+
const id = useId();
|
|
29
|
+
const scope = `${props.scopeKey}:${props.version}`;
|
|
30
|
+
const initial = {
|
|
31
|
+
scope,
|
|
32
|
+
percentage:
|
|
33
|
+
props.affiliateBasisPoints === null
|
|
34
|
+
? ""
|
|
35
|
+
: String(props.affiliateBasisPoints / 100),
|
|
36
|
+
};
|
|
37
|
+
const [fields, setFields] = useState(initial);
|
|
38
|
+
if (fields.scope !== scope) setFields(initial);
|
|
39
|
+
const action = useWorkflowAction(async () => {
|
|
40
|
+
const value = fields.percentage.trim();
|
|
41
|
+
const rate = value === "" ? null : Math.round(Number(value) * 100);
|
|
42
|
+
if (
|
|
43
|
+
rate !== null &&
|
|
44
|
+
(!/^\d+(\.\d{1,2})?$/.test(value) ||
|
|
45
|
+
!Number.isSafeInteger(rate) ||
|
|
46
|
+
rate < 0 ||
|
|
47
|
+
rate > 10000)
|
|
48
|
+
)
|
|
49
|
+
throw new Error(
|
|
50
|
+
"Enter a percentage from 0 to 100 with at most two decimal places, or leave it blank to inherit.",
|
|
51
|
+
);
|
|
52
|
+
await props.onSave({
|
|
53
|
+
affiliateBasisPoints: rate,
|
|
54
|
+
expectedVersion: props.version,
|
|
55
|
+
});
|
|
56
|
+
return "Affiliate payout saved.";
|
|
57
|
+
}, props.scopeKey);
|
|
58
|
+
const state: AffiliateRateEditorState = {
|
|
59
|
+
percentage: fields.percentage,
|
|
60
|
+
setPercentage: (percentage) =>
|
|
61
|
+
setFields((previous) => ({ ...previous, percentage })),
|
|
62
|
+
effectiveLabel: `Effective payout: ${props.effectiveBasisPoints / 100}% from ${props.source === "plan" ? "store plan" : props.source}.`,
|
|
63
|
+
isPending: action.isPending,
|
|
64
|
+
error: action.error,
|
|
65
|
+
message: action.result,
|
|
66
|
+
save: action.run,
|
|
67
|
+
};
|
|
68
|
+
if (props.children) return <>{props.children(state)}</>;
|
|
69
|
+
return (
|
|
70
|
+
<form
|
|
71
|
+
onSubmit={(event) => {
|
|
72
|
+
event.preventDefault();
|
|
73
|
+
void state.save();
|
|
74
|
+
}}
|
|
75
|
+
>
|
|
76
|
+
<label htmlFor={id}>Affiliate payout (%)</label>
|
|
77
|
+
<input
|
|
78
|
+
id={id}
|
|
79
|
+
inputMode="decimal"
|
|
80
|
+
value={state.percentage}
|
|
81
|
+
disabled={state.isPending}
|
|
82
|
+
onChange={(event) => state.setPercentage(event.target.value)}
|
|
83
|
+
/>
|
|
84
|
+
<p>{state.effectiveLabel} Leave blank to inherit.</p>
|
|
85
|
+
{state.error && <p role="alert">{state.error}</p>}
|
|
86
|
+
{state.message && <p role="status">{state.message}</p>}
|
|
87
|
+
<button type="submit" disabled={state.isPending}>
|
|
88
|
+
{state.isPending ? "Saving…" : "Save payout"}
|
|
89
|
+
</button>
|
|
90
|
+
</form>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
@@ -4,6 +4,7 @@ import userEvent from "@testing-library/user-event";
|
|
|
4
4
|
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
|
5
5
|
import type { ReactNode } from "react";
|
|
6
6
|
const mocks = vi.hoisted(() => ({
|
|
7
|
+
sessionEmail: null as string | null,
|
|
7
8
|
updateEmail: vi.fn(),
|
|
8
9
|
confirm: vi.fn(),
|
|
9
10
|
submit: vi.fn(),
|
|
@@ -21,6 +22,7 @@ vi.mock("@stripe/react-stripe-js/checkout", () => ({
|
|
|
21
22
|
type: "success",
|
|
22
23
|
checkout: {
|
|
23
24
|
id: "cs_test",
|
|
25
|
+
email: mocks.sessionEmail,
|
|
24
26
|
canConfirm: false,
|
|
25
27
|
updateEmail: mocks.updateEmail,
|
|
26
28
|
confirm: mocks.confirm,
|
|
@@ -36,6 +38,7 @@ import { CheckoutElementsForm, PaymentIntentForm } from "./CheckoutForms.js";
|
|
|
36
38
|
afterEach(cleanup);
|
|
37
39
|
beforeEach(() => {
|
|
38
40
|
vi.clearAllMocks();
|
|
41
|
+
mocks.sessionEmail = null;
|
|
39
42
|
mocks.updateEmail.mockResolvedValue({ type: "success" });
|
|
40
43
|
mocks.confirm.mockResolvedValue({
|
|
41
44
|
type: "error",
|
|
@@ -53,6 +56,27 @@ const props = {
|
|
|
53
56
|
email: "buyer@example.com",
|
|
54
57
|
onNavigate: vi.fn(),
|
|
55
58
|
};
|
|
59
|
+
it("confirms a session with a server-set email without attempting to update it", async () => {
|
|
60
|
+
mocks.sessionEmail = "account@example.com";
|
|
61
|
+
mocks.updateEmail.mockResolvedValue({
|
|
62
|
+
type: "error",
|
|
63
|
+
error: { message: "You cannot update the email" },
|
|
64
|
+
});
|
|
65
|
+
mocks.confirm.mockResolvedValue({ type: "success" });
|
|
66
|
+
const navigate = vi.fn();
|
|
67
|
+
render(<CheckoutElementsForm {...props} onNavigate={navigate} />);
|
|
68
|
+
const input = screen.getByRole("textbox", {
|
|
69
|
+
name: "Email for your receipt",
|
|
70
|
+
}) as HTMLInputElement;
|
|
71
|
+
expect(input.value).toBe("account@example.com");
|
|
72
|
+
expect(input.readOnly).toBe(true);
|
|
73
|
+
await userEvent.click(screen.getByRole("button", { name: "Pay" }));
|
|
74
|
+
expect(mocks.updateEmail).not.toHaveBeenCalled();
|
|
75
|
+
expect(mocks.confirm).toHaveBeenCalledOnce();
|
|
76
|
+
expect(navigate).toHaveBeenCalledWith(
|
|
77
|
+
"https://app.test/receipt?session_id=cs_test",
|
|
78
|
+
);
|
|
79
|
+
});
|
|
56
80
|
it("sends the email before confirming, including when canConfirm is initially false", async () => {
|
|
57
81
|
render(<CheckoutElementsForm {...props} />);
|
|
58
82
|
await userEvent.click(screen.getByRole("button", { name: "Pay" }));
|
|
@@ -70,6 +94,22 @@ it("does not confirm after Stripe rejects the email", async () => {
|
|
|
70
94
|
expect(screen.getByRole("alert").textContent).toContain("Invalid email");
|
|
71
95
|
expect(mocks.confirm).not.toHaveBeenCalled();
|
|
72
96
|
});
|
|
97
|
+
it("keeps a guest email editable after a declined payment", async () => {
|
|
98
|
+
mocks.updateEmail.mockImplementation(async (email: string) => {
|
|
99
|
+
mocks.sessionEmail = email;
|
|
100
|
+
return { type: "success" };
|
|
101
|
+
});
|
|
102
|
+
render(<CheckoutElementsForm {...props} />);
|
|
103
|
+
await userEvent.click(screen.getByRole("button", { name: "Pay" }));
|
|
104
|
+
await screen.findByText("Card declined");
|
|
105
|
+
const input = screen.getByRole("textbox", { name: "Email for your receipt" });
|
|
106
|
+
expect((input as HTMLInputElement).readOnly).toBe(false);
|
|
107
|
+
await userEvent.clear(input);
|
|
108
|
+
await userEvent.type(input, "other@example.com");
|
|
109
|
+
await userEvent.click(screen.getByRole("button", { name: "Pay" }));
|
|
110
|
+
expect(mocks.updateEmail).toHaveBeenLastCalledWith("other@example.com");
|
|
111
|
+
expect(mocks.confirm).toHaveBeenCalledTimes(2);
|
|
112
|
+
});
|
|
73
113
|
it("disables confirmation while Stripe is processing and supports a new attempt after failure", async () => {
|
|
74
114
|
let resolve!: (value: unknown) => void;
|
|
75
115
|
mocks.confirm.mockImplementationOnce(
|
|
@@ -24,6 +24,8 @@ import { StripeProvider } from "../components/StripeProvider.js";
|
|
|
24
24
|
import { useWorkflowAction } from "./useWorkflowAction.js";
|
|
25
25
|
export type CheckoutFormState = {
|
|
26
26
|
email: string;
|
|
27
|
+
/** Stripe supplied this email when the session loaded; do not edit it. */
|
|
28
|
+
emailReadOnly?: boolean;
|
|
27
29
|
setEmail: (email: string) => void;
|
|
28
30
|
emailInputId: string;
|
|
29
31
|
isPending: boolean;
|
|
@@ -44,6 +46,7 @@ export type CheckoutFormProps = CheckoutFormOptions & {
|
|
|
44
46
|
};
|
|
45
47
|
function NativeForm({
|
|
46
48
|
email,
|
|
49
|
+
emailReadOnly,
|
|
47
50
|
setEmail,
|
|
48
51
|
emailInputId,
|
|
49
52
|
paymentElement,
|
|
@@ -65,6 +68,7 @@ function NativeForm({
|
|
|
65
68
|
required
|
|
66
69
|
autoComplete="email"
|
|
67
70
|
value={email}
|
|
71
|
+
readOnly={emailReadOnly}
|
|
68
72
|
onChange={(event) => setEmail(event.target.value)}
|
|
69
73
|
/>
|
|
70
74
|
{paymentElement}
|
|
@@ -86,31 +90,48 @@ export function CheckoutElementsForm(props: CheckoutFormProps) {
|
|
|
86
90
|
</CheckoutSessionProvider>
|
|
87
91
|
);
|
|
88
92
|
}
|
|
89
|
-
function SessionForm({
|
|
93
|
+
function SessionForm(props: CheckoutFormProps) {
|
|
94
|
+
const checkout = useCheckout();
|
|
95
|
+
if (checkout.type === "loading")
|
|
96
|
+
return <p role="status">Loading checkout…</p>;
|
|
97
|
+
if (checkout.type === "error")
|
|
98
|
+
return <p role="alert">{checkout.error.message}</p>;
|
|
99
|
+
return (
|
|
100
|
+
<ReadySessionForm
|
|
101
|
+
key={checkout.checkout.id}
|
|
102
|
+
{...props}
|
|
103
|
+
checkout={checkout.checkout}
|
|
104
|
+
/>
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
function ReadySessionForm({
|
|
108
|
+
checkout,
|
|
90
109
|
email: initialEmail = "",
|
|
91
110
|
returnUrl,
|
|
92
111
|
onNavigate,
|
|
93
112
|
renderForm,
|
|
94
|
-
}: CheckoutFormProps
|
|
95
|
-
|
|
96
|
-
|
|
113
|
+
}: CheckoutFormProps & {
|
|
114
|
+
checkout: Extract<
|
|
115
|
+
ReturnType<typeof useCheckout>,
|
|
116
|
+
{ type: "success" }
|
|
117
|
+
>["checkout"];
|
|
118
|
+
}) {
|
|
119
|
+
// Snapshot once per session: a guest update must not lock their input on retry.
|
|
120
|
+
const [sessionEmail] = useState(() => checkout.email);
|
|
121
|
+
const [email, setEmail] = useState(sessionEmail ?? initialEmail);
|
|
97
122
|
const emailInputId = useId();
|
|
98
123
|
const action = useWorkflowAction(async () => {
|
|
99
|
-
if (
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
124
|
+
if (!sessionEmail) {
|
|
125
|
+
const updated = await checkout.updateEmail(email);
|
|
126
|
+
if (updated.type === "error") throw new Error(updated.error.message);
|
|
127
|
+
}
|
|
128
|
+
const confirmed = await checkout.confirm();
|
|
103
129
|
if (confirmed.type === "error") throw new Error(confirmed.error.message);
|
|
104
|
-
onNavigate(
|
|
105
|
-
returnUrl.replace("{CHECKOUT_SESSION_ID}", checkout.checkout.id),
|
|
106
|
-
);
|
|
130
|
+
onNavigate(returnUrl.replace("{CHECKOUT_SESSION_ID}", checkout.id));
|
|
107
131
|
});
|
|
108
|
-
if (checkout.type === "loading")
|
|
109
|
-
return <p role="status">Loading checkout…</p>;
|
|
110
|
-
if (checkout.type === "error")
|
|
111
|
-
return <p role="alert">{checkout.error.message}</p>;
|
|
112
132
|
const state: CheckoutFormState = {
|
|
113
|
-
email,
|
|
133
|
+
email: sessionEmail ?? email,
|
|
134
|
+
emailReadOnly: !!sessionEmail,
|
|
114
135
|
setEmail,
|
|
115
136
|
emailInputId,
|
|
116
137
|
paymentElement: <PaymentElement />,
|
|
@@ -34,3 +34,28 @@ it("allows an uncontrolled choice without requiring a router", async () => {
|
|
|
34
34
|
expect(screen.getByText("Stripe component")).toBeTruthy();
|
|
35
35
|
expect(screen.queryByText("API controls")).toBeNull();
|
|
36
36
|
});
|
|
37
|
+
it("names API, BetterStripe components, and Stripe UI distinctly while preserving mode values", async () => {
|
|
38
|
+
const changed = vi.fn();
|
|
39
|
+
render(
|
|
40
|
+
<IntegrationSwitch
|
|
41
|
+
views={{
|
|
42
|
+
headless: <p>API controls</p>,
|
|
43
|
+
components: <p>Package UI</p>,
|
|
44
|
+
embedded: <p>Stripe embed</p>,
|
|
45
|
+
hosted: <p>Stripe portal</p>,
|
|
46
|
+
}}
|
|
47
|
+
onValueChange={changed}
|
|
48
|
+
/>,
|
|
49
|
+
);
|
|
50
|
+
expect(screen.getByRole("button", { name: "via API" })).toBeTruthy();
|
|
51
|
+
expect(screen.getByRole("button", { name: "Stripe embedded" })).toBeTruthy();
|
|
52
|
+
expect(screen.getByRole("button", { name: "Stripe hosted" })).toBeTruthy();
|
|
53
|
+
await userEvent.click(
|
|
54
|
+
screen.getByRole("button", { name: "BetterStripe components" }),
|
|
55
|
+
);
|
|
56
|
+
expect(changed).toHaveBeenLastCalledWith("components");
|
|
57
|
+
expect(screen.getByText("Package UI")).toBeTruthy();
|
|
58
|
+
await userEvent.click(screen.getByRole("button", { name: "via API" }));
|
|
59
|
+
expect(changed).toHaveBeenLastCalledWith("headless");
|
|
60
|
+
expect(screen.queryByRole("button", { name: "Headless" })).toBeNull();
|
|
61
|
+
});
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import { useState, type ReactNode } from "react";
|
|
3
3
|
export type IntegrationMode = "headless" | "components" | "embedded" | "hosted";
|
|
4
4
|
const labels: Record<IntegrationMode, string> = {
|
|
5
|
-
headless: "
|
|
6
|
-
components: "
|
|
5
|
+
headless: "via API",
|
|
6
|
+
components: "BetterStripe components",
|
|
7
7
|
embedded: "Stripe embedded",
|
|
8
8
|
hosted: "Stripe hosted",
|
|
9
9
|
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, render, screen } from "@testing-library/react";
|
|
3
|
+
import userEvent from "@testing-library/user-event";
|
|
4
|
+
import { afterEach, expect, it } from "vitest";
|
|
5
|
+
import { Pagination, useCursorPagination } from "./Pagination.js";
|
|
6
|
+
afterEach(cleanup);
|
|
7
|
+
it("navigates cursor history and resets when the account changes", async () => {
|
|
8
|
+
function View({ account }: { account: string }) {
|
|
9
|
+
const state = useCursorPagination(account);
|
|
10
|
+
return (
|
|
11
|
+
<>
|
|
12
|
+
<output>{state.cursor ?? "first"}</output>
|
|
13
|
+
<Pagination
|
|
14
|
+
page={state.page}
|
|
15
|
+
canPrevious={state.canPrevious}
|
|
16
|
+
canNext={state.page < 3}
|
|
17
|
+
onPrevious={state.previous}
|
|
18
|
+
onNext={() => state.next(`cursor-${state.page}`)}
|
|
19
|
+
/>
|
|
20
|
+
</>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
const { rerender } = render(<View account="a" />);
|
|
24
|
+
expect(
|
|
25
|
+
screen.getByRole("button", { name: "Previous" }).hasAttribute("disabled"),
|
|
26
|
+
).toBe(true);
|
|
27
|
+
await userEvent.click(screen.getByRole("button", { name: "Next" }));
|
|
28
|
+
expect(screen.getByText("cursor-1")).toBeTruthy();
|
|
29
|
+
await userEvent.click(screen.getByRole("button", { name: "Next" }));
|
|
30
|
+
expect(screen.getByText("Page 3")).toBeTruthy();
|
|
31
|
+
expect(
|
|
32
|
+
screen.getByRole("button", { name: "Next" }).hasAttribute("disabled"),
|
|
33
|
+
).toBe(true);
|
|
34
|
+
await userEvent.click(screen.getByRole("button", { name: "Previous" }));
|
|
35
|
+
expect(screen.getByText("cursor-1")).toBeTruthy();
|
|
36
|
+
rerender(<View account="b" />);
|
|
37
|
+
expect(screen.getByText("Page 1")).toBeTruthy();
|
|
38
|
+
expect(screen.getByText("first")).toBeTruthy();
|
|
39
|
+
});
|
|
40
|
+
it("disables navigation while a page is loading", () => {
|
|
41
|
+
render(
|
|
42
|
+
<Pagination
|
|
43
|
+
page={2}
|
|
44
|
+
canPrevious
|
|
45
|
+
canNext
|
|
46
|
+
isLoading
|
|
47
|
+
onPrevious={() => {}}
|
|
48
|
+
onNext={() => {}}
|
|
49
|
+
/>,
|
|
50
|
+
);
|
|
51
|
+
for (const button of screen.getAllByRole("button"))
|
|
52
|
+
expect(button.hasAttribute("disabled")).toBe(true);
|
|
53
|
+
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useState, type ReactNode } from "react";
|
|
3
|
+
|
|
4
|
+
/** Cursor history for bounded server pages. Changing scope resets navigation. */
|
|
5
|
+
export function useCursorPagination(scopeKey: string) {
|
|
6
|
+
const initial = { scopeKey, cursors: [null] as (string | null)[], index: 0 };
|
|
7
|
+
const [state, setState] = useState(initial);
|
|
8
|
+
const current = state.scopeKey === scopeKey ? state : initial;
|
|
9
|
+
if (state.scopeKey !== scopeKey) setState(initial);
|
|
10
|
+
return {
|
|
11
|
+
cursor: current.cursors[current.index],
|
|
12
|
+
page: current.index + 1,
|
|
13
|
+
canPrevious: current.index > 0,
|
|
14
|
+
previous: () =>
|
|
15
|
+
setState((previous) => ({
|
|
16
|
+
...previous,
|
|
17
|
+
index: Math.max(0, previous.index - 1),
|
|
18
|
+
})),
|
|
19
|
+
next: (cursor: string) =>
|
|
20
|
+
setState((previous) => ({
|
|
21
|
+
...previous,
|
|
22
|
+
cursors: [...previous.cursors.slice(0, previous.index + 1), cursor],
|
|
23
|
+
index: previous.index + 1,
|
|
24
|
+
})),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export type PaginationProps = {
|
|
28
|
+
page: number;
|
|
29
|
+
canPrevious: boolean;
|
|
30
|
+
canNext: boolean;
|
|
31
|
+
isLoading?: boolean;
|
|
32
|
+
onPrevious: () => void;
|
|
33
|
+
onNext: () => void;
|
|
34
|
+
previousLabel?: string;
|
|
35
|
+
nextLabel?: string;
|
|
36
|
+
pageLabel?: string;
|
|
37
|
+
children?: (state: {
|
|
38
|
+
pageLabel: string;
|
|
39
|
+
previousLabel: string;
|
|
40
|
+
nextLabel: string;
|
|
41
|
+
previousDisabled: boolean;
|
|
42
|
+
nextDisabled: boolean;
|
|
43
|
+
previous: () => void;
|
|
44
|
+
next: () => void;
|
|
45
|
+
}) => ReactNode;
|
|
46
|
+
};
|
|
47
|
+
/** Unstyled navigation with render props for application design systems. */
|
|
48
|
+
export function Pagination({
|
|
49
|
+
page,
|
|
50
|
+
canPrevious,
|
|
51
|
+
canNext,
|
|
52
|
+
isLoading = false,
|
|
53
|
+
onPrevious,
|
|
54
|
+
onNext,
|
|
55
|
+
previousLabel = "Previous",
|
|
56
|
+
nextLabel = "Next",
|
|
57
|
+
pageLabel = `Page ${page}`,
|
|
58
|
+
children,
|
|
59
|
+
}: PaginationProps) {
|
|
60
|
+
const previousDisabled = isLoading || !canPrevious;
|
|
61
|
+
const nextDisabled = isLoading || !canNext;
|
|
62
|
+
const state = {
|
|
63
|
+
pageLabel,
|
|
64
|
+
previousLabel,
|
|
65
|
+
nextLabel,
|
|
66
|
+
previousDisabled,
|
|
67
|
+
nextDisabled,
|
|
68
|
+
previous: () => {
|
|
69
|
+
if (!previousDisabled) onPrevious();
|
|
70
|
+
},
|
|
71
|
+
next: () => {
|
|
72
|
+
if (!nextDisabled) onNext();
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
if (children) return <>{children(state)}</>;
|
|
76
|
+
return (
|
|
77
|
+
<nav aria-label="Pagination">
|
|
78
|
+
<button
|
|
79
|
+
type="button"
|
|
80
|
+
disabled={previousDisabled}
|
|
81
|
+
onClick={state.previous}
|
|
82
|
+
>
|
|
83
|
+
{previousLabel}
|
|
84
|
+
</button>
|
|
85
|
+
<span role="status" aria-live="polite">
|
|
86
|
+
{pageLabel}
|
|
87
|
+
</span>
|
|
88
|
+
<button type="button" disabled={nextDisabled} onClick={state.next}>
|
|
89
|
+
{nextLabel}
|
|
90
|
+
</button>
|
|
91
|
+
</nav>
|
|
92
|
+
);
|
|
93
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, render, screen } from "@testing-library/react";
|
|
3
|
+
import userEvent from "@testing-library/user-event";
|
|
4
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
5
|
+
import { PlanPricingEditor } from "./PlanPricingEditor.js";
|
|
6
|
+
afterEach(cleanup);
|
|
7
|
+
it("validates money and percentages before saving minor units", async () => {
|
|
8
|
+
const save = vi.fn().mockResolvedValue(undefined);
|
|
9
|
+
render(
|
|
10
|
+
<PlanPricingEditor
|
|
11
|
+
plan={{
|
|
12
|
+
id: "starter",
|
|
13
|
+
name: "Starter",
|
|
14
|
+
monthlyAmount: 900,
|
|
15
|
+
feeBasisPoints: 900,
|
|
16
|
+
version: 0,
|
|
17
|
+
}}
|
|
18
|
+
onSave={save}
|
|
19
|
+
/>,
|
|
20
|
+
);
|
|
21
|
+
const monthly = screen.getByLabelText("Monthly price (USD)");
|
|
22
|
+
await userEvent.clear(monthly);
|
|
23
|
+
await userEvent.type(monthly, "12.34");
|
|
24
|
+
const fee = screen.getByLabelText("Sale fee (%)");
|
|
25
|
+
await userEvent.clear(fee);
|
|
26
|
+
await userEvent.type(fee, "7.5");
|
|
27
|
+
await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
|
|
28
|
+
expect(save).toHaveBeenCalledWith({
|
|
29
|
+
monthlyAmount: 1234,
|
|
30
|
+
feeBasisPoints: 750,
|
|
31
|
+
affiliateBasisPoints: 0,
|
|
32
|
+
expectedVersion: 0,
|
|
33
|
+
});
|
|
34
|
+
expect(screen.getByRole("status").textContent).toContain("saved");
|
|
35
|
+
await userEvent.clear(fee);
|
|
36
|
+
await userEvent.type(fee, "101");
|
|
37
|
+
await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
|
|
38
|
+
expect(save).toHaveBeenCalledTimes(1);
|
|
39
|
+
expect(screen.getByRole("alert").textContent).toMatch(/fee/i);
|
|
40
|
+
await userEvent.clear(fee);
|
|
41
|
+
await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
|
|
42
|
+
expect(save).toHaveBeenLastCalledWith({
|
|
43
|
+
monthlyAmount: 1234,
|
|
44
|
+
feeBasisPoints: null,
|
|
45
|
+
affiliateBasisPoints: 0,
|
|
46
|
+
expectedVersion: 0,
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
it("validates affiliate payout percentages and saves basis points", async () => {
|
|
50
|
+
const save = vi.fn().mockResolvedValue(undefined);
|
|
51
|
+
render(
|
|
52
|
+
<PlanPricingEditor
|
|
53
|
+
plan={{
|
|
54
|
+
id: "growth",
|
|
55
|
+
name: "Growth",
|
|
56
|
+
monthlyAmount: 4900,
|
|
57
|
+
feeBasisPoints: 490,
|
|
58
|
+
affiliateBasisPoints: 2000,
|
|
59
|
+
version: 1,
|
|
60
|
+
}}
|
|
61
|
+
onSave={save}
|
|
62
|
+
/>,
|
|
63
|
+
);
|
|
64
|
+
const share = screen.getByLabelText("Affiliate payout (%)");
|
|
65
|
+
await userEvent.clear(share);
|
|
66
|
+
await userEvent.type(share, "12.5");
|
|
67
|
+
await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
|
|
68
|
+
expect(save).toHaveBeenLastCalledWith({
|
|
69
|
+
monthlyAmount: 4900,
|
|
70
|
+
feeBasisPoints: 490,
|
|
71
|
+
affiliateBasisPoints: 1250,
|
|
72
|
+
expectedVersion: 1,
|
|
73
|
+
});
|
|
74
|
+
await userEvent.clear(share);
|
|
75
|
+
await userEvent.type(share, "100.001");
|
|
76
|
+
await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
|
|
77
|
+
expect(save).toHaveBeenCalledTimes(1);
|
|
78
|
+
expect(screen.getByRole("alert").textContent).toMatch(/affiliate/i);
|
|
79
|
+
});
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useId, useState, type ReactNode } from "react";
|
|
3
|
+
import { useWorkflowAction } from "./useWorkflowAction.js";
|
|
4
|
+
export type PlanPricing = {
|
|
5
|
+
id: string;
|
|
6
|
+
name: string;
|
|
7
|
+
monthlyAmount: number;
|
|
8
|
+
feeBasisPoints: number | null;
|
|
9
|
+
affiliateBasisPoints?: number | null;
|
|
10
|
+
version: number;
|
|
11
|
+
};
|
|
12
|
+
export type PlanPricingUpdate = {
|
|
13
|
+
monthlyAmount: number;
|
|
14
|
+
feeBasisPoints: number | null;
|
|
15
|
+
affiliateBasisPoints?: number | null;
|
|
16
|
+
expectedVersion: number;
|
|
17
|
+
};
|
|
18
|
+
export type PlanPricingEditorState = {
|
|
19
|
+
monthlyPrice: string;
|
|
20
|
+
saleFee: string;
|
|
21
|
+
affiliateShare: string;
|
|
22
|
+
setMonthlyPrice: (value: string) => void;
|
|
23
|
+
setSaleFee: (value: string) => void;
|
|
24
|
+
setAffiliateShare: (value: string) => void;
|
|
25
|
+
save: () => Promise<unknown>;
|
|
26
|
+
isPending: boolean;
|
|
27
|
+
error: string | null;
|
|
28
|
+
message: string | undefined;
|
|
29
|
+
};
|
|
30
|
+
export type PlanPricingEditorProps = {
|
|
31
|
+
plan: PlanPricing;
|
|
32
|
+
onSave: (update: PlanPricingUpdate) => Promise<unknown>;
|
|
33
|
+
children?: (state: PlanPricingEditorState) => ReactNode;
|
|
34
|
+
};
|
|
35
|
+
/** Unstyled store-plan pricing editor. Authorization and Stripe price creation belong on the server. */
|
|
36
|
+
export function PlanPricingEditor({
|
|
37
|
+
plan,
|
|
38
|
+
onSave,
|
|
39
|
+
children,
|
|
40
|
+
}: PlanPricingEditorProps) {
|
|
41
|
+
const id = useId();
|
|
42
|
+
const scope = `${plan.id}:${plan.version}`;
|
|
43
|
+
const initial = {
|
|
44
|
+
scope,
|
|
45
|
+
affiliateShare: String((plan.affiliateBasisPoints ?? 0) / 100),
|
|
46
|
+
monthlyPrice: (plan.monthlyAmount / 100).toFixed(2),
|
|
47
|
+
saleFee:
|
|
48
|
+
plan.feeBasisPoints === null ? "" : String(plan.feeBasisPoints / 100),
|
|
49
|
+
};
|
|
50
|
+
const [fields, setFields] = useState(initial);
|
|
51
|
+
if (fields.scope !== scope) setFields(initial);
|
|
52
|
+
const action = useWorkflowAction(async () => {
|
|
53
|
+
if (!/^\d+(\.\d{1,2})?$/.test(fields.monthlyPrice.trim()))
|
|
54
|
+
throw new Error(
|
|
55
|
+
"Enter a positive monthly price with at most two decimal places.",
|
|
56
|
+
);
|
|
57
|
+
const monthlyAmount = Math.round(Number(fields.monthlyPrice) * 100);
|
|
58
|
+
if (!Number.isSafeInteger(monthlyAmount) || monthlyAmount <= 0)
|
|
59
|
+
throw new Error("Enter a positive monthly price.");
|
|
60
|
+
const feeBasisPoints =
|
|
61
|
+
fields.saleFee.trim() === ""
|
|
62
|
+
? null
|
|
63
|
+
: Math.round(Number(fields.saleFee) * 100);
|
|
64
|
+
if (
|
|
65
|
+
feeBasisPoints !== null &&
|
|
66
|
+
(!/^\d+(\.\d{1,2})?$/.test(fields.saleFee.trim()) ||
|
|
67
|
+
!Number.isSafeInteger(feeBasisPoints) ||
|
|
68
|
+
feeBasisPoints < 0 ||
|
|
69
|
+
feeBasisPoints > 10000)
|
|
70
|
+
)
|
|
71
|
+
throw new Error(
|
|
72
|
+
"Enter a sale fee from 0 to 100%, with at most two decimal places, or leave it blank for Stripe processing only.",
|
|
73
|
+
);
|
|
74
|
+
const affiliateBasisPoints = Math.round(
|
|
75
|
+
Number(fields.affiliateShare) * 100,
|
|
76
|
+
);
|
|
77
|
+
if (
|
|
78
|
+
!/^\d+(\.\d{1,2})?$/.test(fields.affiliateShare.trim()) ||
|
|
79
|
+
!Number.isSafeInteger(affiliateBasisPoints) ||
|
|
80
|
+
affiliateBasisPoints < 0 ||
|
|
81
|
+
affiliateBasisPoints > 10000
|
|
82
|
+
)
|
|
83
|
+
throw new Error(
|
|
84
|
+
"Enter an affiliate payout from 0 to 100%, with at most two decimal places.",
|
|
85
|
+
);
|
|
86
|
+
await onSave({
|
|
87
|
+
monthlyAmount,
|
|
88
|
+
feeBasisPoints,
|
|
89
|
+
affiliateBasisPoints,
|
|
90
|
+
expectedVersion: plan.version,
|
|
91
|
+
});
|
|
92
|
+
return "Pricing saved. Existing subscriptions keep their monthly price.";
|
|
93
|
+
}, plan.id);
|
|
94
|
+
const state: PlanPricingEditorState = {
|
|
95
|
+
...fields,
|
|
96
|
+
setMonthlyPrice: (monthlyPrice) =>
|
|
97
|
+
setFields((previous) => ({ ...previous, monthlyPrice })),
|
|
98
|
+
setSaleFee: (saleFee) =>
|
|
99
|
+
setFields((previous) => ({ ...previous, saleFee })),
|
|
100
|
+
setAffiliateShare: (affiliateShare) =>
|
|
101
|
+
setFields((previous) => ({ ...previous, affiliateShare })),
|
|
102
|
+
save: action.run,
|
|
103
|
+
isPending: action.isPending,
|
|
104
|
+
error: action.error,
|
|
105
|
+
message: action.result,
|
|
106
|
+
};
|
|
107
|
+
if (children) return <>{children(state)}</>;
|
|
108
|
+
return (
|
|
109
|
+
<form
|
|
110
|
+
onSubmit={(event) => {
|
|
111
|
+
event.preventDefault();
|
|
112
|
+
void state.save();
|
|
113
|
+
}}
|
|
114
|
+
aria-label={`${plan.name} pricing`}
|
|
115
|
+
>
|
|
116
|
+
<h3>{plan.name}</h3>
|
|
117
|
+
<label htmlFor={`${id}-monthly`}>Monthly price (USD)</label>
|
|
118
|
+
<input
|
|
119
|
+
id={`${id}-monthly`}
|
|
120
|
+
inputMode="decimal"
|
|
121
|
+
value={state.monthlyPrice}
|
|
122
|
+
disabled={state.isPending}
|
|
123
|
+
onChange={(event) => state.setMonthlyPrice(event.target.value)}
|
|
124
|
+
/>
|
|
125
|
+
<label htmlFor={`${id}-fee`}>Sale fee (%)</label>
|
|
126
|
+
<input
|
|
127
|
+
id={`${id}-fee`}
|
|
128
|
+
inputMode="decimal"
|
|
129
|
+
value={state.saleFee}
|
|
130
|
+
disabled={state.isPending}
|
|
131
|
+
onChange={(event) => state.setSaleFee(event.target.value)}
|
|
132
|
+
/>
|
|
133
|
+
<p>
|
|
134
|
+
Leave the sale fee blank for Stripe processing only. The seller always
|
|
135
|
+
covers actual Stripe processing costs.
|
|
136
|
+
</p>
|
|
137
|
+
<label htmlFor={`${id}-affiliate`}>Affiliate payout (%)</label>
|
|
138
|
+
<input
|
|
139
|
+
id={`${id}-affiliate`}
|
|
140
|
+
inputMode="decimal"
|
|
141
|
+
value={state.affiliateShare}
|
|
142
|
+
disabled={state.isPending}
|
|
143
|
+
onChange={(event) => state.setAffiliateShare(event.target.value)}
|
|
144
|
+
/>
|
|
145
|
+
<p>
|
|
146
|
+
Percentage of a referred sale after the sale fee. The seller receives
|
|
147
|
+
the remainder.
|
|
148
|
+
</p>
|
|
149
|
+
{state.error && <p role="alert">{state.error}</p>}
|
|
150
|
+
{state.message && <p role="status">{state.message}</p>}
|
|
151
|
+
<button type="submit" disabled={state.isPending}>
|
|
152
|
+
{state.isPending ? "Saving…" : "Save pricing"}
|
|
153
|
+
</button>
|
|
154
|
+
</form>
|
|
155
|
+
);
|
|
156
|
+
}
|