@fleetbridge/client 0.0.0-stage → 1.4.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 (4) hide show
  1. package/README.md +308 -2
  2. package/index.d.ts +1691 -0
  3. package/index.js +2078 -0
  4. package/package.json +20 -4
package/README.md CHANGED
@@ -1,3 +1,309 @@
1
- # Temporary Holding Version
1
+ # @fleetbridge/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ FleetBridge's customer booking logic, without any UI: searching every supplier, turning offers into cars, filters and sorting, rate packages, extras, the price breakdown, driver checks, booking, quotes, manage booking and online payment.
4
+
5
+ It's the same code [`@fleetbridge/ui`](../ui) runs, so a web site, the WordPress plugin and a native app book the same way and can't drift apart.
6
+
7
+ - **No dependencies.** No React, no DOM, nothing to configure in Metro.
8
+ - **Runs anywhere:** React Native (Hermes), Node 20+, Bun and browsers. It uses only `fetch`, `FormData` and `URLSearchParams`.
9
+ - **ESM with types.**
10
+
11
+ If you use `@fleetbridge/ui`, you don't need this package: ui already bundles it and re-exports the parts it always did (`httpTransport`, `searchAvailability`, `mapOffersToCars`…).
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @fleetbridge/client
17
+ ```
18
+
19
+ Inside this repository: `"@fleetbridge/client": "workspace:*"` (the workspace uses the TypeScript source directly).
20
+
21
+ Outside it, before it's on npm, build once (`bun run build` in `packages/client`) and install the tarball:
22
+
23
+ ```json
24
+ "@fleetbridge/client": "file:../FLEETBRIDGE/packages/client/release/fleetbridge-client.tgz"
25
+ ```
26
+
27
+ ## Connect it to your site
28
+
29
+ Every call goes through one transport, which you set once at start-up. The transport posts an action to your site's server, which holds the supplier credentials and the account API key. Those never go into the app.
30
+
31
+ ```ts
32
+ import { setTransport, httpTransport } from '@fleetbridge/client';
33
+
34
+ setTransport(
35
+ httpTransport({
36
+ // A route on your site that runs createPublicHandler from @fleetbridge/ui/server.
37
+ endpoint: 'https://www.example.co.za/api/fleetbridge',
38
+ // Optional. Native apps send their own headers here, e.g. an app key or version.
39
+ headers: { 'X-App-Version': '2.4.0' },
40
+ // Optional, default 'same-origin'.
41
+ credentials: 'omit',
42
+ // Optional. Where the requests come from: 'web', 'app' or 'whatsapp'. Sent as the
43
+ // x-fleetbridge-channel header; coupons limited to other channels are refused.
44
+ // Leave it out on web pages (the site treats its own pages as 'web').
45
+ channel: 'app',
46
+ // Optional. Give up after this many milliseconds (failing with status 0), for
47
+ // every action or per action. 0 or undefined means no limit.
48
+ timeoutMs: (action) => (action === 'search_availability' || action === 'booking_request' ? 90_000 : 20_000),
49
+ }),
50
+ );
51
+ ```
52
+
53
+ The body is `FormData` built with `append()` only, so it works with React Native's `FormData` (which has no `set()`).
54
+
55
+ A failure is `{ success: false, error, status?, data? }`. `status` is the HTTP status (401, 404, 409, 429…), or `0` when the site could not be reached or the request timed out.
56
+
57
+ A WordPress site with the FleetBridge plugin uses `wordpressTransport({ ajaxUrl, nonce })` instead. You can also pass any object with `post(action, fields)` that returns a `QueryResult` (`{ success: true, data }` or `{ success: false, error }`), for example to add logging or retries.
58
+
59
+ Until a transport is set, every call fails with "This site isn't connected to FleetBridge yet."
60
+
61
+ ## Search
62
+
63
+ `searchAvailability` asks the site which suppliers to search, searches them all at once, and calls `onProgress` each time one answers, so you can show progress per supplier. It resolves with every offer together, or throws when there are no cars (the error's `sources` says why, per supplier).
64
+
65
+ ```ts
66
+ import {
67
+ DEFAULT_CRITERIA,
68
+ searchAvailability,
69
+ isOffersResult,
70
+ mapOffersToCars,
71
+ rentalDays,
72
+ type SearchCriteria,
73
+ } from '@fleetbridge/client';
74
+
75
+ const criteria: SearchCriteria = {
76
+ ...DEFAULT_CRITERIA,
77
+ pickupLocation: 'Cape Town International Airport',
78
+ pickupDate: '2026-12-18',
79
+ dropoffDate: '2026-12-27',
80
+ };
81
+
82
+ const data = await searchAvailability(criteria, (sources) => {
83
+ // [{ source: 'hertz', supplierName: 'Hertz', status, pending: true }, …]
84
+ setProgress(sources);
85
+ });
86
+
87
+ const cars = isOffersResult(data) ? mapOffersToCars(data.offers) : [];
88
+ const days = rentalDays(criteria); // 9
89
+ ```
90
+
91
+ `onProgress` also gets every offer found so far, as a second argument, so an app can show cars while the other suppliers are still answering:
92
+
93
+ ```ts
94
+ await searchAvailability(criteria, (sources, offers) => {
95
+ setProgress(sources);
96
+ setCars(mapOffersToCars(offers));
97
+ });
98
+ ```
99
+
100
+ `availabilityQueryKey(criteria)` is a ready-made cache key for TanStack Query (React or React Native).
101
+
102
+ `criteriaToQuery(criteria)` and `criteriaFromParams(search)` turn a search into a query string and back, for deep links.
103
+
104
+ ## Places (branches)
105
+
106
+ ```ts
107
+ import { branchQueries, type BranchLocation } from '@fleetbridge/client';
108
+
109
+ const result = await branchQueries.list();
110
+ // [{ name: 'Cape Town International Airport', region: 'Western Cape', isAirportBranch: true, isInternational: false, address?: '…' }, …]
111
+ if (result.success) setPlaces(result.data);
112
+ ```
113
+
114
+ ## Cache version (when to drop cached places and suppliers)
115
+
116
+ ```ts
117
+ import { cacheQueries, cacheVersionQueryKey, type CacheVersion } from '@fleetbridge/client';
118
+
119
+ const result = await cacheQueries.version(); // QueryResult<{ version: string; generatedAt: string }>
120
+ if (result.success && result.data.version !== stored.cacheVersion) {
121
+ // The site's branches, suppliers or its "clear app caches" stamp changed:
122
+ // drop cached locations / sources, store result.data.version, reload.
123
+ }
124
+ // A failure (offline, an older site without cache_version) says nothing: keep your cache.
125
+ ```
126
+
127
+ `cache_version` is cheap (the site keeps the answer for about 30 seconds), so asking on launch and when the app comes back to the foreground is fine; a few minutes between checks is plenty. `cacheVersionQueryKey` is `['cache-version']`.
128
+
129
+ ## Filters, sorting and prices
130
+
131
+ ```ts
132
+ import { DEFAULT_FILTERS, filterCars, sortCars, facetCounts, priceBoundsFromCars, formatZAR } from '@fleetbridge/client';
133
+
134
+ const shown = sortCars(filterCars(cars, { ...DEFAULT_FILTERS, transmission: 'Automatic' }), 'price-asc');
135
+ formatZAR(1234.5); // "R1 234,50"
136
+ ```
137
+
138
+ ## Rate packages and cover
139
+
140
+ A car can come with several packages (km per day) and a SuperCover tier. `withPackage` gives you the car to price and book:
141
+
142
+ ```ts
143
+ import { withPackage, packageKey } from '@fleetbridge/client';
144
+
145
+ const chosen = withPackage(car, car.packages[1], 'super');
146
+ ```
147
+
148
+ ## Extras, live quotes and the price breakdown
149
+
150
+ ```ts
151
+ import { extrasQueries, estimationQueries, oneWayFeeQueries, quoteFor, type ExtraSelection } from '@fleetbridge/client';
152
+
153
+ const extras = (await extrasQueries.extras(car)) ?? []; // null: no add-ons step (or they could not be loaded)
154
+
155
+ // To tell "could not load" apart from "none":
156
+ const loaded = await extrasQueries.extrasResult(car); // { ok: true, extras: Extra[] | null } | { ok: false, error, status? }
157
+ const selection: ExtraSelection = { GPS: 1, BABY_SEAT: 2 };
158
+ const oneWay = await oneWayFeeQueries.check(car, criteria);
159
+
160
+ // What one of an add-on costs for the whole rental, and whether the trip is one-way.
161
+ extraUnitPrice(extras[0], days);
162
+ isOneWay(car);
163
+
164
+ // Every line the customer pays: vehicle, extras, one-way fee, deposit.
165
+ const quote = quoteFor(car, criteria, days, selection, extras, null, oneWay?.fee ?? null);
166
+ quote.total;
167
+ ```
168
+
169
+ ## Driver details
170
+
171
+ ```ts
172
+ import { EMPTY_DRIVER, validateDriver, describeDriverErrors, COUNTRIES } from '@fleetbridge/client';
173
+
174
+ const errors = validateDriver(driver); // {} when everything is filled in
175
+ if (Object.keys(errors).length) alert(describeDriverErrors(errors));
176
+ ```
177
+
178
+ `driver.dialCode` (optional, for example `'+44'`) is the phone's dial code when it differs from the country of residence's. Left out, the country's is sent.
179
+
180
+ ## Booking
181
+
182
+ ```ts
183
+ import { bookingQueries } from '@fleetbridge/client';
184
+
185
+ const result = await bookingQueries.submitBooking({
186
+ car, criteria, driver, selection, extras, days,
187
+ total: quote.total,
188
+ // Only for the site's own cars paid online. returnUrl is where the payment
189
+ // page sends the customer back to, e.g. your app's deep link.
190
+ payment: { methodId, purpose: 'FULL', returnUrl: 'myapp://payment-return' },
191
+ });
192
+
193
+ if (result.ok && result.payment?.redirectUrl) openBrowser(result.payment.redirectUrl);
194
+ else if (result.ok) showConfirmation(result.reservationId, result.bookingPin);
195
+ else showError(result.error);
196
+ ```
197
+
198
+ `bookingQueries.supplierTerms(identifier)` gives the supplier's published terms, or null. `supplierTermsResult(identifier)` answers `{ ok: true, terms }` or `{ ok: false, error, status? }`, so a failure is not mistaken for "no terms".
199
+
200
+ `bookingQueries.requestQuote(request)` sends the same request as a quote, which the site emails instead of booking.
201
+
202
+ To run code when a booking or quote is sent (analytics, for example), or to give every request the same payment return address, make your own instance:
203
+
204
+ ```ts
205
+ import { createBookingQueries } from '@fleetbridge/client';
206
+
207
+ const bookings = createBookingQueries({
208
+ onBookingRequested: (request) => analytics.track('booking_requested', { car: request.car.id }),
209
+ onQuoteRequested: (request) => analytics.track('quote_requested', { car: request.car.id }),
210
+ paymentReturnUrl: () => 'myapp://payment-return',
211
+ });
212
+ ```
213
+
214
+ The hooks are optional. A hook that throws doesn't stop the booking. (`@fleetbridge/ui` uses them to dispatch the `fleetbridge:booking-requested` and `fleetbridge:quote-requested` window events.)
215
+
216
+ ## Manage booking
217
+
218
+ ```ts
219
+ import { bookingManagementQueries } from '@fleetbridge/client';
220
+
221
+ const found = await bookingManagementQueries.lookup('K7QXD2', '4821');
222
+ if (found.success) render(found.data.booking);
223
+
224
+ await bookingManagementQueries.cancel('K7QXD2', '4821', 'Plans changed');
225
+ await bookingManagementQueries.amend('K7QXD2', '4821', newRequest);
226
+ ```
227
+
228
+ `booking.status` is one of `PENDING`, `PAYMENT_PENDING`, `FAILED`, `CONFIRMED`, `PICKED_UP`, `RETURNED`, `CANCELLED`, `RECONCILED`, `NO_SHOW`. `booking.rate` (when the site priced it) has `amount`, `dailyRate`, `days`, `ratePackageLabel`, `extrasTotal`, `dropOffFee`, `deposit`, `total` and `currency`, in rands.
229
+
230
+ `createBookingManagementQueries({ paymentReturnUrl })` makes an instance that fills in the payment return address for `amend`.
231
+
232
+ ## Paying online
233
+
234
+ ```ts
235
+ import { paymentQueries, PAYMENT_RETURN_PARAM } from '@fleetbridge/client';
236
+
237
+ const methods = await paymentQueries.methods(car.pickUpBranch ?? '');
238
+
239
+ // Try the payment again. The payment page sends the customer back to
240
+ // returnUrl with ?fb_payment=<token> (PAYMENT_RETURN_PARAM) added.
241
+ const started = await paymentQueries.start(token, methodId, 'FULL', 'myapp://payment-return');
242
+
243
+ // When they come back:
244
+ const check = await paymentQueries.verify(token);
245
+ if (check.ok && check.check.outcome === 'confirmed') showConfirmation(check.check.reservationId);
246
+ ```
247
+
248
+ Nothing here reads the address bar or browser storage. Remembering the payment across the redirect is up to the app (`@fleetbridge/ui` uses `sessionStorage`).
249
+
250
+ ## Coupons a customer claims
251
+
252
+ A signed-in customer can claim a coupon by its code and see the ones they claimed. Both go through the site, which knows who is signed in (`getCustomer` on `createPublicHandler`) and which channel the request comes from (`getChannel`). Send the customer's sign-in with the transport, for example `headers: { Authorization: 'Bearer …' }`.
253
+
254
+ ```ts
255
+ import { couponQueries, couponUsable, couponLabel, channelsLabel, discountLabel, type AppCoupon } from '@fleetbridge/client';
256
+
257
+ const claimed = await couponQueries.claim('APP20', 'appDownload'); // claimType is optional free text
258
+ if (claimed.ok) show(claimed.coupon);
259
+ else if (claimed.status === 401) askToSignIn();
260
+ else showError(claimed.error); // claimed.code: COUPON_NOT_FOUND | COUPON_EXPIRED | COUPON_WRONG_CHANNEL | COUPON_ALREADY_CLAIMED | SIGN_IN_REQUIRED
261
+
262
+ const mine = await couponQueries.mine(); // { ok: true, coupons: AppCoupon[] } newest first, or { ok: false, error, status? }
263
+
264
+ couponUsable(coupon, 'app', new Date()); // switched on, started, not ended, not used up (overall, or remainingForCustomer 0), and allowed in the app
265
+ couponLabel(coupon); // "Special rate with Europcar" (unlocks a CDP rate), else "15% off" / "R150 off"
266
+ channelsLabel(coupon.channels); // "Everywhere", "App only", "Website and app"…
267
+ discountLabel(coupon); // "20% off" or "R150,00 off"
268
+ ```
269
+
270
+ `AppCoupon` is `{ id, code, description, discountType, discountValue, startDate, endDate, usageLimit, usageCount, usesByCustomer, perCustomerLimit, remainingForCustomer, requireClaim, supplierIdentifier, supplierName, unlocksSpecialRate, isActive, isLive, channels, channel, claimType, claimedAt }`. `id` is the coupon's id; `channel` is where it was claimed. `usesByCustomer` is how many of this customer's bookings use it; `remainingForCustomer` is how many more they may make (null = unlimited, 0 = none left). `requireClaim` means only customers who claimed it can book with it. A claim is not a use: the customer still types the code (`criteria.coupon`) when searching or booking, and each booking is one use (a cancelled booking gives it back).
271
+
272
+ A search result can carry `couponNotice: { code, message, couponCode }` (type `CouponNotice`) when the signed-in customer cannot use the typed coupon any more (`COUPON_CUSTOMER_LIMIT`) or must claim it first (`COUPON_NOT_CLAIMED`): the special rate is left out, so show `message`. A booking refused for its coupon has `code` `COUPON_EXPIRED`, `COUPON_WRONG_CHANNEL`, `COUPON_REQUIRED`, `COUPON_LIMIT_REACHED`, `COUPON_CUSTOMER_LIMIT` or `COUPON_NOT_CLAIMED` (type `CouponBookingProblem`) with a message to show. Errors on the site:
273
+
274
+ | status | when |
275
+ | --- | --- |
276
+ | 401 | nobody signed in ("Please sign in to claim a coupon.") |
277
+ | 403 | the coupon does not work on this channel ("This coupon only works on the website.") |
278
+ | 404 | no coupon has that code, or the site has no customer sign-in |
279
+ | 409 | already claimed |
280
+ | 410 | ended, not started yet, switched off or used up |
281
+ | 429 | too many claims (about 10 an hour) or lists (about 60 an hour) |
282
+
283
+ `COUPON_CHANNELS`, `isCouponChannel` and `CHANNEL_HEADER` are exported too. The list is kept in step by hand with `@fleetbridge/contract`.
284
+
285
+ ## Writing your own query
286
+
287
+ ```ts
288
+ import { BaseQuery } from '@fleetbridge/client';
289
+
290
+ class BranchQueries extends BaseQuery {
291
+ branches() {
292
+ return this.post<{ branches: unknown[] }>('public_branches');
293
+ }
294
+ }
295
+ ```
296
+
297
+ ## Notes
298
+
299
+ - `@fleetbridge/ui` bundles its own copy of this package. If a web page uses both packages, each has its own transport, so call `setTransport` on both (or use `FleetBridgeProvider` for ui).
300
+ - `formatZAR` and `formatDateLabel` use `Intl`. Hermes includes it on iOS and Android.
301
+
302
+ ## Build
303
+
304
+ ```sh
305
+ bun run build # dist/index.js + index.d.ts, dist/package.json, dist/README.md, release/fleetbridge-client.tgz
306
+ bun test # tests/ (transport, coupons, helpers)
307
+ ```
308
+
309
+ `package.json` in this folder is the workspace one: it points at `src/`. The build writes `dist/package.json`, which points at the built files. That's the package to publish.