bitsnap-react 1.5.0 → 1.6.1

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/README.md CHANGED
@@ -57,6 +57,479 @@ It uses modern React patterns and libraries like:
57
57
  - Customizable host URL
58
58
  - Supports test/production environments
59
59
 
60
+ ## Checkout appearance
61
+
62
+ `BitsnapCheckout` accepts an optional `appearance` prop. Omitting it - or passing
63
+ `{}` - keeps the current presentation exactly as it is, so existing integrations
64
+ do not have to change.
65
+
66
+ ### Import the stylesheet
67
+
68
+ ```tsx
69
+ import "bitsnap-react/dist/index.css";
70
+ ```
71
+
72
+ The stylesheet ships ready to use. Do not run it through a PostCSS prefixer or
73
+ compile the library's Tailwind source again: the rules are already scoped.
74
+
75
+ ### Brand colors, font and radius
76
+
77
+ ```tsx
78
+ import { BitsnapCheckout } from "bitsnap-react";
79
+
80
+ function MyComponent() {
81
+ return (
82
+ <BitsnapCheckout
83
+ projectID="your-project-id"
84
+ appearance={{
85
+ tokens: {
86
+ fontFamily: '"Inter", sans-serif',
87
+ background: "#ffffff",
88
+ foreground: "#202020",
89
+ buttonBackground: "#635bff",
90
+ buttonForeground: "#ffffff",
91
+ radius: "12px",
92
+ },
93
+ }}
94
+ />
95
+ );
96
+ }
97
+ ```
98
+
99
+ Fonts are not loaded by the library - load the font file in your application, the
100
+ checkout only applies the family you pass.
101
+
102
+ ### Light theme
103
+
104
+ ```tsx
105
+ <BitsnapCheckout projectID="your-project-id" appearance={{ theme: "light" }} />
106
+ ```
107
+
108
+ `theme` accepts `"dark"` (the default presentation) and `"light"`. There is no
109
+ automatic system theme selection.
110
+
111
+ ### Individual elements
112
+
113
+ Every part of the checkout is addressable through a stable slot. Slots accept a
114
+ `className` (merged after the built-in classes) and a `style` (merged after the
115
+ built-in styles):
116
+
117
+ ```tsx
118
+ <BitsnapCheckout
119
+ projectID="your-project-id"
120
+ appearance={{
121
+ elements: {
122
+ title: { style: { fontFamily: '"Georgia", serif', fontSize: "28px" } },
123
+ checkoutButton: { className: "store-checkout-button" },
124
+ countryOption: { className: "px-4" },
125
+ },
126
+ }}
127
+ />
128
+ ```
129
+
130
+ | Slot | Element |
131
+ | -------------------- | ------------------------------------------- |
132
+ | `root` | Theme boundary of the drawer |
133
+ | `overlay` | Backdrop behind the drawer |
134
+ | `panel` | Drawer panel |
135
+ | `header` | Drawer header row |
136
+ | `title` | "Cart" heading |
137
+ | `closeButton` | Close button |
138
+ | `productList` | Scrollable product list |
139
+ | `product` | Single product row |
140
+ | `productImage` | Product image |
141
+ | `productName` | Product name |
142
+ | `productPrice` | Product price |
143
+ | `quantityControl` | Quantity stepper |
144
+ | `quantityInput` | Quantity value input |
145
+ | `quantityButton` | Quantity `-`/`+` buttons |
146
+ | `removeButton` | "Remove" button |
147
+ | `summary` | Total block |
148
+ | `totalLabel` | "Total" label |
149
+ | `totalValue` | Total amount |
150
+ | `deliveryText` | Delivery note |
151
+ | `countryLabel` | "Choose country" label |
152
+ | `countryTrigger` | Country select trigger |
153
+ | `countryDropdown` | Portalled country list |
154
+ | `countrySearch` | Country search field |
155
+ | `countryOption` | Single country option |
156
+ | `paymentButtons` | Apple Pay / Google Pay wrappers |
157
+ | `checkoutButton` | "Next step" button |
158
+ | `emptyState` | Empty cart message |
159
+ | `error` | Checkout error message |
160
+ | `skeleton` | Loading placeholder |
161
+
162
+ The same names are rendered as `data-bitsnap-checkout-slot` attributes, and the
163
+ drawer/dropdown boundaries carry `data-bitsnap-checkout`, so plain CSS works too:
164
+
165
+ ```css
166
+ /* brand hover and focus states that the library cannot express */
167
+ .store-checkout-button:hover {
168
+ filter: brightness(1.1);
169
+ }
170
+
171
+ [data-bitsnap-checkout-slot="countryOption"]:hover {
172
+ background: #eef2ff;
173
+ }
174
+ ```
175
+
176
+ Custom classes follow the normal CSS cascade; `className` is merged with `cn`, so
177
+ conflicting Tailwind utilities from the library are resolved in your favor.
178
+
179
+ ### Tokens
180
+
181
+ | Token | Applies to |
182
+ | ------------------------- | ------------------------------------------------------- |
183
+ | `fontFamily` | The whole checkout |
184
+ | `fontSize` | The whole checkout |
185
+ | `background` | Panel, country trigger |
186
+ | `surface` | Country dropdown, search bar, loading skeletons |
187
+ | `foreground` | Titles, prices, total |
188
+ | `mutedForeground` | Empty cart, delivery note, country label, search field |
189
+ | `border` | Country trigger, dropdown, product separators |
190
+ | `buttonBackground` | "Next step" button |
191
+ | `buttonForeground` | "Next step" button |
192
+ | `buttonHoverBackground` | "Next step" button on hover |
193
+ | `hoverSurface` | Close button, country options |
194
+ | `focusRing` | Focus rings of the shared controls |
195
+ | `error` | Error message, unavailable product outline |
196
+ | `overlay` | Drawer backdrop |
197
+ | `radius` | Radius of the rounded elements |
198
+
199
+ ### What stays untouched
200
+
201
+ - The trigger button (`className`, `children`, `numberOfProductsInCartOptions`) and
202
+ every callback keep their current meaning.
203
+ - The appearance lives in the checkout component only. It is not a global setting
204
+ and does not reuse the panel's `setTheme`.
205
+ - Apple Pay and Google Pay keep their native artwork and fonts; only the space
206
+ around them is themed.
207
+ - Layout, responsive widths and checkout actions are unchanged. Override widths
208
+ from your own CSS.
209
+ - The country list is rendered in a portal. It receives the theme (colors, font,
210
+ focus ring and stacking) as soon as you pass an `appearance`; without one it
211
+ renders exactly as before.
212
+
213
+ ## Returns
214
+
215
+ `BitsnapReturns` is the customer return flow: email, verification code, orders,
216
+ line and quantity selection, confirmation, result, plus a list of earlier returns
217
+ with their status. The views are themeable from the start, with the same
218
+ `appearance` shape as the checkout. It needs the same stylesheet
219
+ (`bitsnap-react/dist/index.css`).
220
+
221
+ ```tsx
222
+ import { BitsnapReturns } from "bitsnap-react";
223
+ import "bitsnap-react/dist/index.css";
224
+
225
+ function ReturnsPage() {
226
+ return <BitsnapReturns projectID="your-project-id" />;
227
+ }
228
+ ```
229
+
230
+ It is an inline page section, not an overlay, and it is safe to render on the
231
+ server.
232
+
233
+ **Upgrading from 1.6.0.** 1.6.0 code keeps working without changes, imported
234
+ from `bitsnap-react` or `bitsnap-react/returns`. Both paths now export this
235
+ implementation.
236
+ - **`BitsnapReturns` props:** it still accepts the `Environment` enum, `theme.brandColor` (prefer `appearance.tokens`) and the old text keys (`title`, `email`, `sendCode`, `code`, `verify`, `orders`, `submit`, `note`, `loading`, `history`).
237
+ - **Provider:** `BitsnapReturnsProvider` is an alias of `ReturnsProvider`.
238
+ - **Hooks:** they accept both the 1.6.0 calls (`useReturnOrders(pageSize, pageToken)`, `useMyReturns(pageSize, pageToken)`) and the new object form. Their results include the 1.6.0 fields (`data`, `mutateAsync`, `startSession`, `verifySession`, `starting`, `verifying`) next to the new ones.
239
+ - **Visual change:** the widget now uses the new themed views.
240
+ - **Wording:** without `texts`, the wording follows the library locale (`setLocale`). 1.6.0 was always English.
241
+
242
+ | Prop | Meaning |
243
+ | ------------------- | -------------------------------------------------------------------------- |
244
+ | `projectID` | Bitsnap project ID |
245
+ | `host` | API host. Falls back to `setCustomHost`, then `https://bitsnap.pl` |
246
+ | `environment` | `"production"` (default) or `"test"` |
247
+ | `appearance` | `{ theme, tokens, elements }`, see below |
248
+ | `texts` | Partial text overrides, see [Texts](#texts) |
249
+ | `locale` | Locale of texts, dates and money. Defaults to `getLocale()` |
250
+ | `panelAccessToken` | Customer panel token; skips email and code, see [Panel](#returns-in-the-customer-panel) |
251
+ | `className` | Class of the themed root element |
252
+
253
+ The session token lives in React state and `sessionStorage` (one key per project),
254
+ never in `localStorage`, and is never logged. An expired session returns the flow
255
+ to the email step.
256
+
257
+ ### Shared brand
258
+
259
+ One object can style the checkout and the returns views:
260
+
261
+ ```tsx
262
+ import { BitsnapCheckout, BitsnapReturns } from "bitsnap-react";
263
+
264
+ const brand = {
265
+ theme: "light",
266
+ tokens: {
267
+ fontFamily: '"Inter", sans-serif',
268
+ buttonBackground: "#635bff",
269
+ buttonForeground: "#ffffff",
270
+ radius: "12px",
271
+ },
272
+ } as const;
273
+
274
+ <BitsnapCheckout projectID="your-project-id" appearance={brand} />
275
+ <BitsnapReturns
276
+ projectID="your-project-id"
277
+ appearance={{
278
+ ...brand,
279
+ elements: {
280
+ title: { style: { fontFamily: '"Georgia", serif' } },
281
+ submitButton: { className: "store-primary-button" },
282
+ },
283
+ }}
284
+ />
285
+ ```
286
+
287
+ `theme` is `"light"` or `"dark"`. The default for returns is `"light"`; the
288
+ checkout keeps its `"dark"` default. `elements` take `{ className, style }`,
289
+ merged after the built-in classes and styles, exactly like the checkout slots.
290
+
291
+ ### Return tokens
292
+
293
+ The returns views use the checkout tokens, plus five more. `overlay` is
294
+ checkout-only and ignored by returns.
295
+
296
+ | Token | Applies to | Returns only |
297
+ | ------------------------- | ---------------------------------------------------------- | ------------ |
298
+ | `fontFamily`, `fontSize` | All returns views | |
299
+ | `background` | Page background | |
300
+ | `surface` | Cards, summaries, loading skeletons | |
301
+ | `foreground` | Titles, names, amounts | |
302
+ | `mutedForeground` | Descriptions, dates, hints | |
303
+ | `border` | Cards, inputs, separators | |
304
+ | `buttonBackground` | Primary buttons | |
305
+ | `buttonForeground` | Primary buttons | |
306
+ | `buttonHoverBackground` | Primary buttons on hover | |
307
+ | `hoverSurface` | Secondary buttons, selectable cards | |
308
+ | `focusRing` | Focus rings | |
309
+ | `error` | Error messages | |
310
+ | `radius` | Rounded elements | |
311
+ | `success` | Result screen, completed and refunded statuses | yes |
312
+ | `warning` | Statuses that need attention | yes |
313
+ | `badgeBackground` | Status badges | yes |
314
+ | `badgeForeground` | Status badges | yes |
315
+ | `inputBackground` | Text inputs and the note field | yes |
316
+
317
+ ### Return slots
318
+
319
+ Slots are exported as `RETURNS_SLOT_NAMES` and rendered as
320
+ `data-bitsnap-returns-slot` attributes.
321
+
322
+ | Group | Slots |
323
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
324
+ | Frame | `root`, `header`, `title`, `description`, `backButton`, `stepIndicator`, `error`, `emptyState`, `skeleton` |
325
+ | Auth | `emailForm`, `emailInput`, `codeForm`, `codeInput`, `resendButton`, `logoutButton` |
326
+ | Orders | `orderList`, `orderCard`, `orderReference`, `orderDate`, `orderTotal`, `pagination` |
327
+ | Selection | `lineList`, `line`, `lineName`, `linePrice`, `lineQuantityControl`, `quantityButton`, `quantityInput`, `lineIneligibleReason`, `noteInput` |
328
+ | Confirmation and result | `summary`, `submitButton`, `secondaryButton`, `successState`, `returnReference`, `returnInstructions` |
329
+ | My returns | `returnList`, `returnCard`, `statusBadge`, `history`, `historyEntry` |
330
+
331
+ ### Texts
332
+
333
+ Both `BitsnapCheckout` and `BitsnapReturns` accept a `texts` prop: a partial
334
+ object that overrides the default strings whatever the locale. Without it the
335
+ strings are unchanged, and `setLocale`/`getLocale` keep working. For different
336
+ copy per language, pass a different object.
337
+
338
+ ```tsx
339
+ <BitsnapCheckout
340
+ projectID="your-project-id"
341
+ texts={{ cart: "Your basket", nextStep: "Pay now" }}
342
+ />
343
+
344
+ <BitsnapReturns
345
+ projectID="your-project-id"
346
+ locale="en"
347
+ texts={{
348
+ emailStepTitle: "Return a product",
349
+ successDescription: "We'll email you once it arrives.",
350
+ statusAwaitingReceipt: "On its way to us",
351
+ }}
352
+ />
353
+ ```
354
+
355
+ Checkout keys (`CheckoutTexts`): `cart`, `emptyCart`, `total`, `delivery`,
356
+ `chooseCountry`, `nextStep`, `unavailableProducts`.
357
+
358
+ Returns keys (`ReturnsTexts`) cover each step (`emailStepTitle`,
359
+ `codeStepDescription`, `ordersEmpty`, `confirmationSubmit`, `successTitle`,
360
+ `myReturnsTitle`, ...), the request statuses (`statusSubmitted`,
361
+ `statusApproved`, `statusAwaitingReceipt`, `statusReceived`, `statusRefunded`,
362
+ `statusFallback`, ...) and the error messages (`errorGeneric`,
363
+ `errorInvalidCode`, `errorSessionExpired`, ...). Strings with placeholders such
364
+ as `{reference}` or `{count}` keep them in overrides. See `ReturnsTexts` and
365
+ `CheckoutTexts` in the type declarations for the full list and the placeholders.
366
+
367
+ ### Custom layout
368
+
369
+ Compose your own page from the step components under `ReturnsProvider`. The
370
+ provider holds the session, appearance, texts and the transport, and renders the
371
+ themed root. Each step takes small navigation callbacks and the IDs it needs, and
372
+ throws a clear error when rendered outside the provider.
373
+
374
+ ```tsx
375
+ import {
376
+ ReturnsConfirmation,
377
+ ReturnsEmailStep,
378
+ ReturnsCodeStep,
379
+ ReturnsOrderDetail,
380
+ ReturnsOrderList,
381
+ ReturnsProvider,
382
+ ReturnsResult,
383
+ useReturnSession,
384
+ type SelectedReturnLine,
385
+ } from "bitsnap-react";
386
+
387
+ function Flow() {
388
+ const { isAuthenticated } = useReturnSession();
389
+ const [step, setStep] = useState<"email" | "code" | "orders" | "order" | "confirm" | "done">("email");
390
+ const [orderId, setOrderId] = useState("");
391
+ const [items, setItems] = useState<SelectedReturnLine[]>([]);
392
+ const [note, setNote] = useState("");
393
+ const [returnId, setReturnId] = useState("");
394
+
395
+ if (!isAuthenticated) {
396
+ return step === "code" ? (
397
+ <ReturnsCodeStep onBack={() => setStep("email")} />
398
+ ) : (
399
+ <ReturnsEmailStep onSubmitted={() => setStep("code")} />
400
+ );
401
+ }
402
+ if (step === "order") {
403
+ return (
404
+ <ReturnsOrderDetail
405
+ orderId={orderId}
406
+ initialItems={items}
407
+ initialNote={note}
408
+ onBack={() => setStep("orders")}
409
+ onContinue={(selection) => {
410
+ setItems(selection.items);
411
+ setNote(selection.note);
412
+ setStep("confirm");
413
+ }}
414
+ />
415
+ );
416
+ }
417
+ if (step === "confirm") {
418
+ return (
419
+ <ReturnsConfirmation
420
+ orderId={orderId}
421
+ items={items}
422
+ note={note}
423
+ onBack={() => setStep("order")}
424
+ onSubmitted={(id) => {
425
+ setReturnId(id);
426
+ setStep("done");
427
+ }}
428
+ />
429
+ );
430
+ }
431
+ if (step === "done") {
432
+ return <ReturnsResult returnId={returnId} onContinue={() => setStep("orders")} />;
433
+ }
434
+ return (
435
+ <ReturnsOrderList
436
+ onSelectOrder={(id) => {
437
+ setOrderId(id);
438
+ setStep("order");
439
+ }}
440
+ />
441
+ );
442
+ }
443
+
444
+ <ReturnsProvider projectID="your-project-id" appearance={brand}>
445
+ <Flow />
446
+ </ReturnsProvider>;
447
+ ```
448
+
449
+ Available steps: `ReturnsEmailStep`, `ReturnsCodeStep`, `ReturnsOrderList`
450
+ (`onSelectOrder`, `onOpenMyReturns`, `showLogout`), `ReturnsOrderDetail`,
451
+ `ReturnsConfirmation`, `ReturnsResult`, `ReturnsMyReturnsList` and
452
+ `ReturnsMyReturnDetail`. Each accepts its own `className`. A session left in
453
+ `sessionStorage` is picked up on the next visit, so `useReturnSession().status`
454
+ is `"hydrating"` until the provider has read it on the client.
455
+
456
+ ### Headless hooks
457
+
458
+ To build the markup yourself, use the hooks under `ReturnsProvider`: they return
459
+ data, loading and error state, and actions, and no markup.
460
+
461
+ | Hook | Returns |
462
+ | ---------------------------- | ----------------------------------------------------------------------- |
463
+ | `useReturnSession()` | `status`, `isAuthenticated`, `start(email)`, `verify(code)`, `resend()`, `logout()`, `error` |
464
+ | `useReturnOrders(options?)` | Paged returnable `orders`, `total`, `next()`, `previous()`, `refetch()` |
465
+ | `useReturnableOrder(id)` | `order` with per-line eligibility, `returnHistory` |
466
+ | `useCreateReturn()` | `submit({ orderId, items, note })`; retries reuse one idempotency key |
467
+ | `useMyReturns(options?)` | Paged earlier returns |
468
+ | `useMyReturn(id)` | One return with its status and history |
469
+
470
+ ```tsx
471
+ function Orders() {
472
+ const { orders, isLoading, errorKey } = useReturnOrders();
473
+ if (isLoading) return null;
474
+ return <ul>{orders.map((order) => <li key={order.canonicalOrderId}>{order.displayReference}</li>)}</ul>;
475
+ }
476
+ ```
477
+
478
+ A request that fails with `SESSION_EXPIRED` drops the session, so
479
+ `useReturnSession().status` becomes `"anonymous"`.
480
+
481
+ ### CSS only
482
+
483
+ Everything is also addressable without props. The root carries
484
+ `data-bitsnap-returns` and the theme class (`light` or `dark`), and every slot
485
+ carries `data-bitsnap-returns-slot`. The library rules sit in `@layer components`,
486
+ so ordinary stylesheets win:
487
+
488
+ ```css
489
+ /* the theme is applied as inline custom properties, so overrides need !important */
490
+ [data-bitsnap-returns] {
491
+ --bitsnap-returns-button-background: #635bff !important;
492
+ --bitsnap-returns-radius: 12px !important;
493
+ }
494
+
495
+ [data-bitsnap-returns-slot="orderCard"]:hover {
496
+ border-color: #635bff;
497
+ }
498
+
499
+ [data-bitsnap-returns-slot="line"][data-ineligible] {
500
+ opacity: 0.5;
501
+ }
502
+ ```
503
+
504
+ Token variables are named `--bitsnap-returns-<token in kebab case>`, for example
505
+ `--bitsnap-returns-muted-foreground`.
506
+
507
+ ### Returns in the customer panel
508
+
509
+ The `Panel` has a Returns screen (`/panel?state=returns`, with `orderId` and
510
+ `returnId` in the URL for the selected order and return). It is built from the
511
+ step components above and reuses the panel login: the panel access token is
512
+ exchanged for a returns session, so the customer sees their orders with no
513
+ second code, and there is no email, code or logout step. When the panel session
514
+ has expired, the customer is sent to the panel login.
515
+
516
+ ```tsx
517
+ <Panel
518
+ returnsAppearance={{ theme: "light", tokens: { buttonBackground: "#635bff" } }}
519
+ returnsTexts={{ ordersTitle: "Choose an order to return" }}
520
+ />
521
+ ```
522
+
523
+ | Prop | Meaning |
524
+ | ------------------- | ------------------------------------------------------------------------------- |
525
+ | `returnsAppearance` | `ReturnsAppearance` of the screen |
526
+ | `returnsTexts` | `Partial<ReturnsTexts>` of the screen |
527
+
528
+ Without `returnsAppearance`, `buttonBackground` and `focusRing` come from the
529
+ panel's `theme.colors.brand` (set with `setTheme`) and `buttonForeground` is
530
+ chosen for contrast. Other panel screens and `setTheme` are unchanged. The
531
+ navigation label follows `setLocale` ("Zwroty" / "Returns").
532
+
60
533
  # Examples
61
534
 
62
535
  1. `BitsnapCheckout` Component:
@@ -450,6 +923,7 @@ The panel provides the following screens:
450
923
  | Profile | `/panel?state=profile` | User profile and settings |
451
924
  | Notifications | `/panel?state=notifications` | Notification preferences |
452
925
  | Plans | `/panel?state=plans` | Subscription management |
926
+ | Returns | `/panel?state=returns` | Return products, track returns |
453
927
 
454
928
  ## Features Detail
455
929
 
@@ -0,0 +1,2 @@
1
+ import{enumDesc as ye,fileDesc as O}from"@bufbuild/protobuf/codegenv2";var k=O("Chtjb21tb24vdjEvZW52aXJvbm1lbnQucHJvdG8SCWNvbW1vbi52MSonCgtFbnZpcm9ubWVudBIOCgpQUk9EVUNUSU9OEAASCAoEVEVTVBABQk5aTGdpdGh1Yi5jb20vZW1tZW1zL3N1cGVyLWNhcnQvYXBwcy9zcnYtd29ya2VyL3V0aWxzL21vZGVscy9jb21tb24vdjE7Y29tbW9udjFiBnByb3RvMw"),T=(t=>(t[t.PRODUCTION=0]="PRODUCTION",t[t.TEST=1]="TEST",t))(T||{});import{Code as P,ConnectError as _,createClient as $}from"@connectrpc/connect";import{createConnectTransport as ee}from"@connectrpc/connect-web";import{fileDesc as Q,messageDesc as Ve,serviceDesc as U}from"@bufbuild/protobuf/codegenv2";import{file_google_protobuf_timestamp as D}from"@bufbuild/protobuf/wkt";var z=Q("ChdwdWJsaWMvdjEvcmV0dXJucy5wcm90bxIJcHVibGljLnYxImsKGVN0YXJ0UmV0dXJuU2Vzc2lvblJlcXVlc3QSEgoKcHJvamVjdF9pZBgBIAEoCRINCgVlbWFpbBgCIAEoCRIrCgtlbnZpcm9ubWVudBgDIAEoDjIWLmNvbW1vbi52MS5FbnZpcm9ubWVudCJhChpTdGFydFJldHVyblNlc3Npb25SZXNwb25zZRIUCgxjaGFsbGVuZ2VfaWQYASABKAkSHAoUcmVzZW5kX2FmdGVyX3NlY29uZHMYAiABKAUSDwoHbWVzc2FnZRgDIAEoCSKBAQoaVmVyaWZ5UmV0dXJuU2Vzc2lvblJlcXVlc3QSEgoKcHJvamVjdF9pZBgBIAEoCRIUCgxjaGFsbGVuZ2VfaWQYAiABKAkSDAoEY29kZRgDIAEoCRIrCgtlbnZpcm9ubWVudBgEIAEoDjIWLmNvbW1vbi52MS5FbnZpcm9ubWVudCJkChtWZXJpZnlSZXR1cm5TZXNzaW9uUmVzcG9uc2USFQoNc2Vzc2lvbl90b2tlbhgBIAEoCRIuCgp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Nwb25zZRJkChNDcmVhdGVSZXR1cm5SZXF1ZXN0EiUucHVibGljLnYxLkNyZWF0ZVJldHVyblJlcXVlc3RSZXF1ZXN0GiYucHVibGljLnYxLkNyZWF0ZVJldHVyblJlcXVlc3RSZXNwb25zZRJSCg1MaXN0TXlSZXR1cm5zEh8ucHVibGljLnYxLkxpc3RNeVJldHVybnNSZXF1ZXN0GiAucHVibGljLnYxLkxpc3RNeVJldHVybnNSZXNwb25zZRJMCgtHZXRNeVJldHVybhIdLnB1YmxpYy52MS5HZXRNeVJldHVyblJlcXVlc3QaHi5wdWJsaWMudjEuR2V0TXlSZXR1cm5SZXNwb25zZWIGcHJvdG8z",[k,D]);var L=U(z,0);import{QueryClient as te,QueryClientProvider as ne,useMutation as C,useQuery as N,useQueryClient as se}from"@tanstack/react-query";import re,{createContext as oe,useContext as ie,useMemo as F,useRef as K,useState as l}from"react";import{Fragment as ge,jsx as r,jsxs as o}from"react/jsx-runtime";var q=oe(null);function ue({projectID:e,host:n="https://bitsnap.pl",environment:t=0,children:i}){let u=`${n.replace(/\/$/,"")}|${e}|${t}`,[a,c]=l(),d=a?.scope===u?a.token:void 0,R=a?.scope===u?a.expiresAt:void 0,[h]=l(()=>new te({defaultOptions:{queries:{staleTime:0,refetchOnWindowFocus:!0}}})),g=F(()=>$(L,ee({baseUrl:`${n.replace(/\/$/,"")}/api/rpc`,useBinaryFormat:!0})),[n]),S=F(()=>({projectID:e,host:n.replace(/\/$/,""),environment:t,client:g,sessionToken:d,setSession:(m,Z)=>c(m?{token:m,expiresAt:Z,scope:u}:void 0),expiresAt:R}),[e,n,t,g,d,R,u]);return r(ne,{client:h,children:r(q.Provider,{value:S,children:i})})}function y(){let e=ie(q);if(!e)throw new Error("Wrap returns hooks in BitsnapReturnsProvider.");return e}function V(e,n){throw e instanceof _&&e.code===P.Unauthenticated&&n(),e}function ae(){let e=y(),n=C({mutationFn:u=>e.client.startReturnSession({projectId:e.projectID,email:u,environment:e.environment})}),t=C({mutationFn:async({challengeId:u,code:a})=>{let c=await e.client.verifyReturnSession({projectId:e.projectID,challengeId:u,code:a,environment:e.environment}),d=c.expiresAt?Number(c.expiresAt.seconds)*1e3+c.expiresAt.nanos/1e6:void 0;return e.setSession(c.sessionToken,d),c}}),i=()=>{e.setSession(void 0),t.reset(),n.reset()};return{startSession:n.mutateAsync,verifySession:t.mutateAsync,logout:i,isAuthenticated:!!(e.sessionToken&&(!e.expiresAt||Date.now()<e.expiresAt)),starting:n.isPending,verifying:t.isPending,error:n.error??t.error}}function ce(e=20,n=""){let t=y(),i=t.sessionToken;return N({queryKey:["bitsnap-returns",t.host,t.projectID,t.environment,e,n,"orders"],enabled:!!(i&&(!t.expiresAt||Date.now()<t.expiresAt)),queryFn:()=>t.client.listReturnOrders({projectId:t.projectID,sessionToken:i,pageSize:e,pageToken:n}).catch(u=>V(u,()=>t.setSession(void 0)))})}function le(e){let n=y(),t=n.sessionToken;return N({queryKey:["bitsnap-returns",n.host,n.projectID,n.environment,e,"order"],enabled:!!(t&&e&&(!n.expiresAt||Date.now()<n.expiresAt)),queryFn:()=>n.client.getReturnableOrder({projectId:n.projectID,sessionToken:t,canonicalOrderId:e}).catch(i=>V(i,()=>n.setSession(void 0)))})}function de(){let e=y(),n=e.sessionToken,t=se();return C({mutationFn:i=>{if(!n||e.expiresAt&&Date.now()>=e.expiresAt)throw e.setSession(void 0),new Error("Verify your email to continue.");return e.client.createReturnRequest({projectId:e.projectID,sessionToken:n,canonicalOrderId:i.canonicalOrderID,items:i.items,note:i.note??"",idempotencyKey:i.idempotencyKey??globalThis.crypto.randomUUID()}).catch(u=>V(u,()=>e.setSession(void 0)))},onSuccess:async()=>t.invalidateQueries({queryKey:["bitsnap-returns",e.host,e.projectID,e.environment]})})}function pe(e=20,n=""){let t=y(),i=t.sessionToken;return N({queryKey:["bitsnap-returns",t.host,t.projectID,t.environment,e,n,"mine"],enabled:!!(i&&(!t.expiresAt||Date.now()<t.expiresAt)),queryFn:()=>t.client.listMyReturns({projectId:t.projectID,sessionToken:i,pageSize:e,pageToken:n}).catch(u=>V(u,()=>t.setSession(void 0)))})}var Re={title:"Request a return",email:"Email address",sendCode:"Send code",code:"Email code",verify:"Verify",orders:"Your orders",submit:"Submit return",note:"Note (optional)",loading:"Loading\u2026",history:"My return requests"};function Ce(e){return r(ue,{projectID:e.projectID,host:e.host,environment:e.environment,children:r(me,{...e})})}function me(e){let n={...Re,...e.texts},t=ae(),[i,u]=l(""),a=ce(20,i),c=pe(),d=de(),[R,h]=l(""),[g,S]=l(""),[m,Z]=l(""),[J,X]=l(),[x,f]=l(),[G,Y]=l({}),[M,H]=l(""),[p,E]=l(),I=K(!1),W=K(void 0),A=le(J?.canonicalOrderId);re.useEffect(()=>{A.data?.order&&f(A.data.order)},[A.data]);let B=t.error??a.error??A.error??d.error,j={"--bitsnap-returns-brand":e.theme?.brandColor??"#111827"};return o("section",{className:`bitsnap-returns ${e.className??""}`,style:j,"aria-live":"polite",children:[r("h2",{className:"mb-4 text-xl font-semibold",children:n.title}),!t.isAuthenticated&&o("div",{className:"space-y-3",children:[o("label",{className:"block text-sm",children:[n.email,r("input",{type:"email",autoComplete:"email",value:R,onChange:s=>h(s.target.value),className:"mt-1 block w-full rounded border p-2"})]}),g?o(ge,{children:[o("label",{className:"block text-sm",children:[n.code,r("input",{inputMode:"numeric",autoComplete:"one-time-code",value:m,onChange:s=>Z(s.target.value),className:"mt-1 block w-full rounded border p-2"})]}),r("button",{type:"button",disabled:t.verifying||!m,onClick:()=>t.verifySession({challengeId:g,code:m}),className:"rounded bg-[var(--bitsnap-returns-brand)] px-4 py-2 text-white disabled:opacity-50",children:t.verifying?n.loading:n.verify}),r("button",{type:"button",disabled:t.starting,onClick:async()=>{let s=await t.startSession(R);S(s.challengeId)},className:"ml-3 underline",children:"Resend code"})]}):r("button",{type:"button",disabled:t.starting||!R,onClick:async()=>{let s=await t.startSession(R);S(s.challengeId)},className:"rounded bg-[var(--bitsnap-returns-brand)] px-4 py-2 text-white disabled:opacity-50",children:t.starting?n.loading:n.sendCode})]}),a.isLoading&&r("p",{children:n.loading}),a.data!=null&&!J&&!p&&o("div",{className:"space-y-3",children:[r("h3",{className:"font-medium",children:n.orders}),a.data.orders.length===0&&r("p",{children:"No eligible orders found."}),a.data.orders.map(s=>o("button",{type:"button",onClick:()=>X(s),className:"block w-full rounded border p-3 text-left hover:border-[var(--bitsnap-returns-brand)]",children:[r("span",{className:"font-medium",children:s.displayReference}),o("span",{className:"ml-2 text-sm text-gray-600",children:[s.currency," ",w(s.totalMinor)]})]},s.canonicalOrderId)),a.data.nextPageToken&&r("button",{type:"button",onClick:()=>u(a.data?.nextPageToken??""),className:"underline",children:"Next orders"})]}),x&&!p&&o("div",{className:"space-y-3",children:[o("button",{type:"button",onClick:()=>{X(void 0),f(void 0)},className:"text-sm underline",children:["\u2190 ",n.orders]}),x.lines.map(s=>o("label",{className:"flex items-center justify-between gap-3 rounded border p-3",children:[o("span",{children:[s.name,o("small",{className:"block text-gray-600",children:[s.availableQuantity," available \xB7 ",s.currency," ",w(s.paidUnitMinor)]})]}),r("input",{type:"number",min:0,max:s.availableQuantity,disabled:!s.eligible,value:G[s.lineId]??0,onChange:b=>Y(v=>({...v,[s.lineId]:Math.max(0,Math.min(s.availableQuantity,Number(b.target.value)))})),className:"w-20 rounded border p-2"}),!s.eligible&&r("small",{children:s.exclusionReason})]},s.lineId)),o("label",{className:"block text-sm",children:[n.note,r("textarea",{value:M,onChange:s=>H(s.target.value),className:"mt-1 block w-full rounded border p-2"})]}),r("button",{type:"button",disabled:d.isPending||!Object.values(G).some(s=>s>0),onClick:async()=>{if(!I.current){I.current=!0,W.current??=globalThis.crypto.randomUUID();try{let s=await d.mutateAsync({canonicalOrderID:x.canonicalOrderId,items:Object.entries(G).filter(([,b])=>b>0).map(([b,v])=>({lineId:b,quantity:v})),note:M,idempotencyKey:W.current});s&&"request"in s&&s.request&&E(s.request)}finally{I.current=!1}}},className:"rounded bg-[var(--bitsnap-returns-brand)] px-4 py-2 text-white disabled:opacity-50",children:d.isPending?n.loading:n.submit})]}),p&&o("div",{className:"rounded border p-4",children:[r("h3",{className:"font-semibold",children:"Return submitted"}),o("p",{children:["Reference: ",r("strong",{children:p.reference})]}),o("p",{children:["Status: ",p.status]}),p.returnInstructions&&r("p",{className:"mt-2",children:p.returnInstructions}),r("button",{type:"button",onClick:()=>{E(void 0),X(void 0),f(void 0),Y({}),c.refetch()},className:"mt-3 underline",children:n.history})]}),c.data?.returns&&c.data.returns.length>0&&!p&&o("div",{className:"mt-6",children:[r("h3",{className:"mb-2 font-medium",children:n.history}),c.data.returns.map(s=>o("div",{className:"border-t py-2",children:[r("strong",{children:s.reference}),r("span",{className:"ml-2",children:s.status})]},s.id))]}),B&&r("p",{role:"alert",className:"mt-3 text-sm text-red-700",children:B.message})]})}function w(e){return(Number(e)/100).toFixed(2)}export{T as a,L as b,ue as c,ae as d,ce as e,le as f,de as g,pe as h,Ce as i};
2
+ //# sourceMappingURL=chunk-O4ICBP4G.mjs.map