@fantastic.dev/better-stripe 0.69.0 → 0.71.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.
@@ -1,8 +1,200 @@
1
1
  // @vitest-environment jsdom
2
- import { act, cleanup, renderHook } from "@testing-library/react";
2
+ import {
3
+ act,
4
+ cleanup,
5
+ fireEvent,
6
+ render,
7
+ renderHook,
8
+ screen,
9
+ } from "@testing-library/react";
3
10
  import { afterEach, expect, it, vi } from "vitest";
4
- import { useProductManager } from "./Products.js";
11
+ import { Products, useProductManager } from "./Products.js";
5
12
  afterEach(cleanup);
13
+ it("supports editing and archiving without advertising creation capabilities", async () => {
14
+ const updateProduct = vi.fn().mockResolvedValue(null);
15
+ const deactivateProduct = vi.fn().mockResolvedValue(null);
16
+ render(
17
+ <Products
18
+ scopeKey="owner"
19
+ products={[
20
+ {
21
+ stripeProductId: "prod_original",
22
+ name: "Original plan",
23
+ active: true,
24
+ prices: [],
25
+ },
26
+ ]}
27
+ updateProduct={updateProduct}
28
+ deactivateProduct={deactivateProduct}
29
+ />,
30
+ );
31
+ expect(screen.queryByRole("button", { name: "Create product" })).toBeNull();
32
+ expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
33
+ fireEvent.click(screen.getByRole("button", { name: "Edit product" }));
34
+ fireEvent.change(screen.getByLabelText("Product name"), {
35
+ target: { value: "Updated plan" },
36
+ });
37
+ await act(async () => {
38
+ fireEvent.click(screen.getByRole("button", { name: "Save product" }));
39
+ });
40
+ expect(updateProduct).toHaveBeenCalledWith({
41
+ stripeProductId: "prod_original",
42
+ name: "Updated plan",
43
+ description: undefined,
44
+ });
45
+ await act(async () => {
46
+ fireEvent.click(screen.getByRole("button", { name: "Archive product" }));
47
+ });
48
+ expect(deactivateProduct).toHaveBeenCalledWith({
49
+ stripeProductId: "prod_original",
50
+ });
51
+ expect(updateProduct).toHaveBeenCalledTimes(1);
52
+ });
53
+
54
+ it("reports unavailable creation without calling a different capability", async () => {
55
+ const updateProduct = vi.fn();
56
+ const { result } = renderHook(() =>
57
+ useProductManager({ scopeKey: "owner", updateProduct }),
58
+ );
59
+ act(() =>
60
+ result.current.setNewProduct({ name: "Original plan", description: "" }),
61
+ );
62
+ await act(async () => {
63
+ await result.current.handleCreateProduct();
64
+ });
65
+ expect(result.current.error).toBe("Product creation is not configured.");
66
+ expect(result.current.newProduct.name).toBe("Original plan");
67
+ expect(updateProduct).not.toHaveBeenCalled();
68
+ act(() =>
69
+ result.current.setNewPrice({
70
+ amount: "1500",
71
+ currency: "usd",
72
+ interval: "month",
73
+ }),
74
+ );
75
+ await act(async () => {
76
+ await result.current.handleAddPrice("prod_original");
77
+ });
78
+ expect(result.current.error).toBe("Price creation is not configured.");
79
+ expect(result.current.newPrice.amount).toBe("1500");
80
+ expect(updateProduct).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it("allows product creation without exposing price creation", async () => {
84
+ const createProduct = vi.fn().mockResolvedValue("prod_new");
85
+ render(
86
+ <Products
87
+ scopeKey="product-editor"
88
+ createProduct={createProduct}
89
+ products={[
90
+ {
91
+ stripeProductId: "prod_original",
92
+ name: "Original plan",
93
+ active: true,
94
+ prices: [],
95
+ },
96
+ ]}
97
+ />,
98
+ );
99
+ expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
100
+ fireEvent.change(screen.getByLabelText("Product name"), {
101
+ target: { value: " New plan " },
102
+ });
103
+ await act(async () => {
104
+ fireEvent.click(screen.getByRole("button", { name: "Create product" }));
105
+ });
106
+ expect(createProduct).toHaveBeenCalledWith({
107
+ name: "New plan",
108
+ description: undefined,
109
+ });
110
+ });
111
+
112
+ it("allows price creation without exposing product creation", async () => {
113
+ const createPrice = vi.fn().mockResolvedValue("price_new");
114
+ render(
115
+ <Products
116
+ scopeKey="price-editor"
117
+ createPrice={createPrice}
118
+ products={[
119
+ {
120
+ stripeProductId: "prod_original",
121
+ name: "Original plan",
122
+ active: true,
123
+ prices: [],
124
+ },
125
+ ]}
126
+ />,
127
+ );
128
+ expect(screen.queryByRole("button", { name: "Create product" })).toBeNull();
129
+ fireEvent.click(screen.getByRole("button", { name: "Add price" }));
130
+ fireEvent.change(screen.getByLabelText("Price in minor units"), {
131
+ target: { value: "1500" },
132
+ });
133
+ await act(async () => {
134
+ fireEvent.click(screen.getByRole("button", { name: "Create price" }));
135
+ });
136
+ expect(createPrice).toHaveBeenCalledWith({
137
+ stripeProductId: "prod_original",
138
+ unitAmount: 1500,
139
+ currency: "usd",
140
+ type: "recurring",
141
+ interval: "month",
142
+ });
143
+ });
144
+
145
+ it("hides an open price form when creation becomes unavailable", () => {
146
+ const products = [
147
+ {
148
+ stripeProductId: "prod_original",
149
+ name: "Original plan",
150
+ active: true,
151
+ prices: [],
152
+ },
153
+ ];
154
+ const createPrice = vi.fn();
155
+ const { rerender } = render(
156
+ <Products scopeKey="owner" products={products} createPrice={createPrice} />,
157
+ );
158
+ fireEvent.click(screen.getByRole("button", { name: "Add price" }));
159
+ expect(screen.getByLabelText("Price in minor units")).toBeDefined();
160
+ rerender(<Products scopeKey="owner" products={products} />);
161
+ expect(screen.queryByLabelText("Price in minor units")).toBeNull();
162
+ expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
163
+ expect(createPrice).not.toHaveBeenCalled();
164
+ });
165
+
166
+ it("keeps the new scope's draft after an old creation finishes", async () => {
167
+ let finish!: () => void;
168
+ const createProduct = () =>
169
+ new Promise<void>((resolve) => {
170
+ finish = resolve;
171
+ });
172
+ const { result, rerender } = renderHook(
173
+ ({ scopeKey }) => useProductManager({ scopeKey, createProduct }),
174
+ { initialProps: { scopeKey: "original-owner" } },
175
+ );
176
+ act(() =>
177
+ result.current.setNewProduct({ name: "Original draft", description: "" }),
178
+ );
179
+ let pending!: Promise<void>;
180
+ act(() => {
181
+ pending = result.current.handleCreateProduct();
182
+ });
183
+ rerender({ scopeKey: "new-owner" });
184
+ act(() =>
185
+ result.current.setNewProduct({
186
+ name: "New owner's draft",
187
+ description: "",
188
+ }),
189
+ );
190
+ await act(async () => {
191
+ finish();
192
+ await pending;
193
+ });
194
+ expect(result.current.newProduct.name).toBe("New owner's draft");
195
+ expect(result.current.error).toBeNull();
196
+ });
197
+
6
198
  it("validates product names and price minor units before mutation", async () => {
7
199
  const createProduct = vi.fn().mockResolvedValue("prod_test");
8
200
  const createPrice = vi.fn().mockResolvedValue("price_test");
@@ -12,8 +12,8 @@ export type PriceInput = {
12
12
  };
13
13
  export type ProductActions = {
14
14
  scopeKey: string;
15
- createProduct: (args: ProductInput) => Promise<unknown>;
16
- createPrice: (args: PriceInput) => Promise<unknown>;
15
+ createProduct?: (args: ProductInput) => Promise<unknown>;
16
+ createPrice?: (args: PriceInput) => Promise<unknown>;
17
17
  updateProduct?: (
18
18
  args: ProductInput & { stripeProductId: string },
19
19
  ) => Promise<unknown>;
@@ -46,6 +46,8 @@ export function useProductManager(props: ProductActions) {
46
46
  setCommand(command);
47
47
  switch (command.type) {
48
48
  case "create": {
49
+ if (!props.createProduct)
50
+ throw new Error("Product creation is not configured.");
49
51
  if (!fields.newProduct.name.trim())
50
52
  throw new Error("Enter a product name.");
51
53
  await props.createProduct({
@@ -55,6 +57,8 @@ export function useProductManager(props: ProductActions) {
55
57
  break;
56
58
  }
57
59
  case "price": {
60
+ if (!props.createPrice)
61
+ throw new Error("Price creation is not configured.");
58
62
  const unitAmount = Number(fields.newPrice.amount);
59
63
  if (
60
64
  !/^\d+$/.test(fields.newPrice.amount) ||
@@ -186,39 +190,41 @@ function ProductsBody(props: ProductsProps) {
186
190
  <section data-better-stripe="products" aria-busy={state.isPending}>
187
191
  <h2>Products</h2>
188
192
  {state.error && <p role="alert">{state.error}</p>}
189
- <form
190
- onSubmit={(event) => {
191
- event.preventDefault();
192
- void state.handleCreateProduct();
193
- }}
194
- >
195
- <label htmlFor={`${id}-name`}>Product name</label>
196
- <input
197
- id={`${id}-name`}
198
- required
199
- value={state.newProduct.name}
200
- onChange={(event) =>
201
- state.setNewProduct({
202
- ...state.newProduct,
203
- name: event.target.value,
204
- })
205
- }
206
- />
207
- <label htmlFor={`${id}-description`}>Description</label>
208
- <input
209
- id={`${id}-description`}
210
- value={state.newProduct.description}
211
- onChange={(event) =>
212
- state.setNewProduct({
213
- ...state.newProduct,
214
- description: event.target.value,
215
- })
216
- }
217
- />
218
- <button type="submit" disabled={state.isPending}>
219
- {state.isCreatingProduct ? "Creating…" : "Create product"}
220
- </button>
221
- </form>
193
+ {props.createProduct && (
194
+ <form
195
+ onSubmit={(event) => {
196
+ event.preventDefault();
197
+ void state.handleCreateProduct();
198
+ }}
199
+ >
200
+ <label htmlFor={`${id}-name`}>Product name</label>
201
+ <input
202
+ id={`${id}-name`}
203
+ required
204
+ value={state.newProduct.name}
205
+ onChange={(event) =>
206
+ state.setNewProduct({
207
+ ...state.newProduct,
208
+ name: event.target.value,
209
+ })
210
+ }
211
+ />
212
+ <label htmlFor={`${id}-description`}>Description</label>
213
+ <input
214
+ id={`${id}-description`}
215
+ value={state.newProduct.description}
216
+ onChange={(event) =>
217
+ state.setNewProduct({
218
+ ...state.newProduct,
219
+ description: event.target.value,
220
+ })
221
+ }
222
+ />
223
+ <button type="submit" disabled={state.isPending}>
224
+ {state.isCreatingProduct ? "Creating…" : "Create product"}
225
+ </button>
226
+ </form>
227
+ )}
222
228
  {result.isLoading ? (
223
229
  <p role="status">Loading products…</p>
224
230
  ) : !result.products.length ? (
@@ -246,13 +252,17 @@ function ProductsBody(props: ProductsProps) {
246
252
  )}
247
253
  </div>
248
254
  ))}
249
- <button
250
- type="button"
251
- disabled={state.isPending}
252
- onClick={() => state.setShowAddPriceFor(product.stripeProductId)}
253
- >
254
- Add price
255
- </button>
255
+ {props.createPrice && (
256
+ <button
257
+ type="button"
258
+ disabled={state.isPending}
259
+ onClick={() =>
260
+ state.setShowAddPriceFor(product.stripeProductId)
261
+ }
262
+ >
263
+ Add price
264
+ </button>
265
+ )}
256
266
  {props.updateProduct && (
257
267
  <button
258
268
  type="button"
@@ -281,7 +291,7 @@ function ProductsBody(props: ProductsProps) {
281
291
  </article>
282
292
  ))
283
293
  )}
284
- {state.showAddPriceFor && (
294
+ {props.createPrice && state.showAddPriceFor && (
285
295
  <form
286
296
  onSubmit={(event) => {
287
297
  event.preventDefault();