@fleetbridge/ui 1.1.1 → 1.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fleetbridge/ui",
3
- "version": "1.1.1",
3
+ "version": "1.4.1",
4
4
  "description": "FleetBridge customer UI (search, results, booking, manage booking) for WordPress and custom sites.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -86,7 +86,7 @@
86
86
  "peerDependencies": {
87
87
  "react": "^19",
88
88
  "react-dom": "^19",
89
- "@fleetbridge/sdk": "^1.2.0"
89
+ "@fleetbridge/sdk": "^1.4.0"
90
90
  },
91
91
  "peerDependenciesMeta": {
92
92
  "@fleetbridge/sdk": {
package/server.d.ts CHANGED
@@ -1,5 +1,87 @@
1
1
  import { AppConnector, FleetBridge, StorageAdapter } from '@fleetbridge/sdk';
2
2
 
3
+ /**
4
+ * Where a request comes from: the website, the mobile app or a WhatsApp bot.
5
+ * Coupons can be limited to some channels.
6
+ *
7
+ * Kept in step by hand with COUPON_CHANNELS in @fleetbridge/contract
8
+ * (packages/contract/src/promotions.ts), which this package does not depend
9
+ * on at run time. Add a channel there and here together.
10
+ */
11
+ declare const COUPON_CHANNELS: readonly ["web", "app", "whatsapp"];
12
+ type CouponChannel = (typeof COUPON_CHANNELS)[number];
13
+
14
+ /** A coupon a customer claimed, with the coupon as it stands now. */
15
+ interface AppCoupon {
16
+ /** The coupon's id (not the claim's). */
17
+ id: string;
18
+ /** What the customer types, for example "APP20". */
19
+ code: string;
20
+ description: string | null;
21
+ /** "PERCENTAGE" or "FIXED_AMOUNT". */
22
+ discountType: string;
23
+ /** A percent (0 to 100) or an amount in rands. */
24
+ discountValue: number;
25
+ /** ISO time the coupon starts working. */
26
+ startDate: string | null;
27
+ /** ISO time it stops working. Null means no end. */
28
+ endDate: string | null;
29
+ /** Null means no limit. */
30
+ usageLimit: number | null;
31
+ /** Bookings that use it, by every customer (cancelled ones give their use back). Claims do not count. */
32
+ usageCount: number;
33
+ /** Bookings this customer made with it that still count. */
34
+ usesByCustomer: number;
35
+ /** How many bookings one customer may make with it. Null means no per-customer limit. */
36
+ perCustomerLimit: number | null;
37
+ /**
38
+ * How many more bookings this customer may make with it (the per-customer
39
+ * and the overall limit together). Null means unlimited; 0 means they
40
+ * cannot use it again.
41
+ */
42
+ remainingForCustomer: number | null;
43
+ /** "Must be claimed first": only customers who claimed it can book with it. */
44
+ requireClaim: boolean;
45
+ /** The supplier it is for, as its adapter name, for example "europcar" or "own-fleet". Null when unknown. */
46
+ supplierIdentifier: string | null;
47
+ /** The supplier's name customers know, for example "Europcar". Null when unknown. */
48
+ supplierName: string | null;
49
+ /** True when it unlocks a supplier's special (CDP) rate, rather than only taking money off. */
50
+ unlocksSpecialRate: boolean;
51
+ /** False when staff switched it off. */
52
+ isActive: boolean;
53
+ /** Whether it could be used when the site answered. couponUsable() checks again against a given time. */
54
+ isLive: boolean;
55
+ /** Where it works ("web", "app", "whatsapp"). Empty means everywhere. */
56
+ channels: string[];
57
+ /** The channel it was claimed from. */
58
+ channel: string;
59
+ /** Why the customer got it, for example "appDownload" or "referral". */
60
+ claimType: string | null;
61
+ /** ISO time it was claimed. */
62
+ claimedAt: string;
63
+ }
64
+
65
+ /**
66
+ * The signed-in customer, as the site knows them (its own login). The email
67
+ * is who claims and lists coupons; the other details fill in a customer the
68
+ * site does not have yet.
69
+ *
70
+ * `authUserId` is the customer's id in the site's login (for example the
71
+ * Clerk user id). When given, it is sent to the core with searches
72
+ * (trip.customer), bookings and amendments (customer.authUserId), claims and
73
+ * the coupon list. The core finds the customer by it first and by email
74
+ * second, saves it on a guest customer with the same email (so their
75
+ * earlier coupon uses count), and counts per-customer coupon limits by it.
76
+ */
77
+ interface PublicCustomer {
78
+ email: string;
79
+ /** The customer's id in the site's own login, for example a Clerk user id. */
80
+ authUserId?: string;
81
+ firstName?: string;
82
+ lastName?: string;
83
+ phone?: string;
84
+ }
3
85
  /**
4
86
  * One supplier connection the site may search and book. The browser only
5
87
  * ever sees `identifier` (for example "europcar") and `name`. `credentials`
@@ -77,6 +159,17 @@ interface PublicHandlerHooks {
77
159
  status: string;
78
160
  payment: unknown;
79
161
  }): Promise<void>;
162
+ /** A signed-in customer claimed a coupon (claim_coupon). `isNew` is true when the claim added them to the site's customers. */
163
+ onCouponClaimed?(e: {
164
+ coupon: AppCoupon;
165
+ customer: {
166
+ id: string;
167
+ email: string;
168
+ isNew: boolean;
169
+ };
170
+ channel: CouponChannel;
171
+ claimType: string | null;
172
+ }): Promise<void>;
80
173
  onError?(e: {
81
174
  action: string;
82
175
  error: unknown;
@@ -122,6 +215,49 @@ interface PublicHandlerOptions {
122
215
  env?: Record<string, string | undefined>;
123
216
  /** Logs problems (WordPress's error_log). Default console.error. */
124
217
  log?(message: string): void;
218
+ /**
219
+ * Where a request comes from: "web", "app" or "whatsapp". It goes to the
220
+ * core as trip.channel on searches, bookings, amendments and confirmed
221
+ * quotes, so a coupon limited to other channels is refused there
222
+ * (COUPON_WRONG_CHANNEL, with a message such as "This coupon only works in
223
+ * the app."), and claims are recorded under it.
224
+ *
225
+ * Default: the `x-fleetbridge-channel` request header when it names a known
226
+ * channel, otherwise null (no channel: every coupon works, as before).
227
+ * The header is only a claim the caller makes; a site that can tell its
228
+ * callers apart (for example its own web pages from its app) should decide
229
+ * here instead.
230
+ */
231
+ getChannel?(request: Request): CouponChannel | null | Promise<CouponChannel | null>;
232
+ /**
233
+ * The signed-in customer for this request, from the site's own login
234
+ * (a session cookie, a bearer token from the app…), or null when nobody is
235
+ * signed in. Needed by claim_coupon and my_coupons: without this option
236
+ * those actions answer 404 "Unknown action.", and with it but no customer
237
+ * they answer 401.
238
+ *
239
+ * It is also asked (once per request) by search_availability when a promo
240
+ * code is typed, and by booking_request, confirm_quote and
241
+ * amend_my_booking, so the core can apply per-customer coupon rules to a
242
+ * signed-in customer. A failure there counts as nobody signed in.
243
+ */
244
+ getCustomer?(request: Request): Promise<PublicCustomer | null>;
245
+ /**
246
+ * A manual stamp the site controls (for example a "Clear app caches"
247
+ * button that saves the current time). It is folded into cache_version,
248
+ * so changing it makes every app drop its cached locations and suppliers.
249
+ * Null or a failure counts as "no stamp".
250
+ */
251
+ extraCacheStamp?: () => Promise<string | null>;
252
+ /** How long cache_version keeps its answer in memory, in seconds. Default 30; 0 works it out every time. */
253
+ cacheVersionTtlSeconds?: number;
254
+ }
255
+ /** What cache_version answers. */
256
+ interface CacheVersion {
257
+ /** A short hash of everything apps cache (branches, suppliers, the site's stamp). Compare it, never parse it. */
258
+ version: string;
259
+ /** When this server worked the version out (ISO 8601). */
260
+ generatedAt: string;
125
261
  }
126
262
  interface AdminHandlerOptions {
127
263
  /** Runs actions through the site's tenant database (preferred, same as WordPress). */
@@ -149,14 +285,25 @@ interface AdminHandlerOptions {
149
285
  log?(message: string): void;
150
286
  }
151
287
 
152
- /** Core error codes whose message is written for customers. Any other error only says "try again". */
288
+ /**
289
+ * Core error codes whose message is written for customers. Any other error
290
+ * only says "try again". The coupon codes keep the core's status:
291
+ * COUPON_EXPIRED 422, COUPON_WRONG_CHANNEL 422, COUPON_REQUIRED 422 (a
292
+ * coupon-gated special rate without its coupon), COUPON_LIMIT_REACHED 409
293
+ * (fully used), COUPON_CUSTOMER_LIMIT 409 ("You've already used this
294
+ * coupon.") and COUPON_NOT_CLAIMED 403 (must be claimed first).
295
+ */
153
296
  declare const CUSTOMER_ERRORS: string[];
297
+ /** What claim_coupon and my_coupons answer when getCustomer finds nobody signed in. */
298
+ declare const SIGN_IN_MESSAGE = "Please sign in to claim a coupon.";
299
+ /** The default getChannel: the x-fleetbridge-channel header, when it names a known channel. */
300
+ declare function channelFromHeader(request: Request): CouponChannel | null;
154
301
  /** One message for "no such booking number" and "wrong PIN", so nobody can tell which part was wrong. */
155
302
  declare const LOOKUP_ERROR = "We could not find a booking with that booking number and PIN. Please check both and try again.";
156
303
  /** Row keys the customer never sees: the site's own ids and the PIN. */
157
304
  declare const STAFF_ONLY: string[];
158
305
  /** Every public action this handler answers, by its WordPress name without "fleetbridge_". */
159
- declare const PUBLIC_ACTIONS: readonly ["public_branches", "search_sources", "search_availability", "booking_request", "lookup_booking", "cancel_my_booking", "amend_my_booking", "get_estimation", "get_extras", "get_one_way_fee", "supplier_terms", "payment_methods", "start_payment", "verify_payment", "request_quote", "lookup_quote", "confirm_quote"];
306
+ declare const PUBLIC_ACTIONS: readonly ["public_branches", "search_sources", "cache_version", "search_availability", "booking_request", "lookup_booking", "cancel_my_booking", "amend_my_booking", "get_estimation", "get_extras", "get_one_way_fee", "supplier_terms", "payment_methods", "start_payment", "verify_payment", "request_quote", "lookup_quote", "confirm_quote", "claim_coupon", "my_coupons"];
160
307
  type PublicAction = (typeof PUBLIC_ACTIONS)[number];
161
308
  declare function createPublicHandler(opts: PublicHandlerOptions): (request: Request) => Promise<Response>;
162
309
 
@@ -196,4 +343,4 @@ declare class MemoryStateStore implements StateStore {
196
343
  /** The name the core and the widget use for the site's own cars. */
197
344
  declare const OWN_FLEET = "own-fleet";
198
345
 
199
- export { type AdminHandlerOptions, CUSTOMER_ERRORS, DEFAULT_ADMIN_ALLOW, type Forwarding, LOOKUP_ERROR, MemoryStateStore, OWN_FLEET, PUBLIC_ACTIONS, type PublicAction, type PublicHandlerHooks, type PublicHandlerOptions, STAFF_ADMIN_ALLOW, STAFF_ONLY, type StateStore, type SupplierAccount, adminMayRun, createAdminHandler, createPublicHandler, readSuppliersFromEnv };
346
+ export { type AdminHandlerOptions, type AppCoupon, CUSTOMER_ERRORS, type CacheVersion, type CouponChannel, DEFAULT_ADMIN_ALLOW, type Forwarding, LOOKUP_ERROR, MemoryStateStore, OWN_FLEET, PUBLIC_ACTIONS, type PublicAction, type PublicCustomer, type PublicHandlerHooks, type PublicHandlerOptions, SIGN_IN_MESSAGE, STAFF_ADMIN_ALLOW, STAFF_ONLY, type StateStore, type SupplierAccount, adminMayRun, channelFromHeader, createAdminHandler, createPublicHandler, readSuppliersFromEnv };
package/server.js CHANGED
@@ -217,6 +217,7 @@ function trip(fields, timeZone) {
217
217
  isInternational: !!fields.isInternational
218
218
  };
219
219
  if (fields.promoCode) out.promoCode = fields.promoCode;
220
+ if (fields.channel) out.channel = fields.channel;
220
221
  const age = Number(fields.driverAge);
221
222
  if (fields.driverAge && Number.isInteger(age) && age >= 16 && age <= 99) out.driverAge = age;
222
223
  return out;
@@ -254,6 +255,7 @@ function bookingForm(post) {
254
255
  estimated_total: number("estimatedTotal"),
255
256
  vehicle_amount: number("vehicleAmount"),
256
257
  deposit: number("deposit"),
258
+ excess: number("excess"),
257
259
  drop_off_fee: number("dropOffFee"),
258
260
  rate_package_label: text("ratePackageLabel", 40),
259
261
  terms_id: text("termsId", 64),
@@ -324,7 +326,8 @@ function searchAnswer(data, ownFleetName) {
324
326
  }
325
327
  const own = JSON.parse(JSON.stringify(data?.ownFleet ?? []));
326
328
  if (own.length > 0) offers.push(ownFleetOffer(own, ownFleetName));
327
- return { offers, sources: JSON.parse(JSON.stringify(data?.sources ?? [])) };
329
+ const notice = data?.couponNotice && typeof data.couponNotice === "object" ? JSON.parse(JSON.stringify(data.couponNotice)) : void 0;
330
+ return { offers, sources: JSON.parse(JSON.stringify(data?.sources ?? [])), ...notice ? { couponNotice: notice } : {} };
328
331
  }
329
332
  function ownFleetOffer(classes, name) {
330
333
  const fromCore = typeof classes[0]?.supplierName === "string" ? classes[0].supplierName.trim() : "";
@@ -408,9 +411,9 @@ function ownFleetRate(item) {
408
411
  }
409
412
  return rate;
410
413
  }
411
- function bookingInput(request, supplierId, credentials, timeZone, notification2 = null) {
414
+ function bookingInput(request, supplierId, credentials, timeZone, notification2 = null, channel = null) {
412
415
  const input = {
413
- trip: bookingTrip(request, timeZone),
416
+ trip: bookingTrip(request, timeZone, channel),
414
417
  source: source(request, supplierId, credentials),
415
418
  customer: customer(request),
416
419
  extras: extras(request),
@@ -421,10 +424,10 @@ function bookingInput(request, supplierId, credentials, timeZone, notification2
421
424
  if (request.terms_id !== "" && request.terms_version > 0) input.terms = { id: request.terms_id, version: request.terms_version };
422
425
  return input;
423
426
  }
424
- function amendInput(request, booking, bookingId, supplierId, credentials, timeZone, notification2 = null) {
425
- return { booking, bookingId: String(bookingId), ...bookingInput(request, supplierId, credentials, timeZone, notification2) };
427
+ function amendInput(request, booking, bookingId, supplierId, credentials, timeZone, notification2 = null, channel = null) {
428
+ return { booking, bookingId: String(bookingId), ...bookingInput(request, supplierId, credentials, timeZone, notification2, channel) };
426
429
  }
427
- function bookingTrip(request, timeZone) {
430
+ function bookingTrip(request, timeZone, channel = null) {
428
431
  return trip(
429
432
  {
430
433
  pickupLocation: request.pickup_location,
@@ -434,7 +437,8 @@ function bookingTrip(request, timeZone) {
434
437
  returnDate: request.return_date,
435
438
  returnTime: request.return_time,
436
439
  promoCode: request.coupon,
437
- isInternational: request.is_international
440
+ isInternational: request.is_international,
441
+ channel
438
442
  },
439
443
  timeZone
440
444
  );
@@ -531,7 +535,8 @@ function notification(request, supplierName, timeZone) {
531
535
  dropoffBranchName: request.dropoff_location,
532
536
  rentalDays: request.days || null,
533
537
  ratePackageLabel: request.rate_package_label,
534
- depositAmount: request.deposit > 0 ? cents(request.deposit) : null
538
+ depositAmount: request.deposit > 0 ? cents(request.deposit) : null,
539
+ excessAmount: request.excess > 0 ? cents(request.excess) : null
535
540
  };
536
541
  for (const [key, value] of Object.entries(optional)) if (value !== null && value !== "") out[key] = value;
537
542
  if (request.unlimited_mileage) out.unlimitedMileage = true;
@@ -551,6 +556,9 @@ function priceLines(request) {
551
556
  return lines;
552
557
  }
553
558
 
559
+ // src/server/public.handler.ts
560
+ import { createHash } from "node:crypto";
561
+
554
562
  // src/server/tenant.ts
555
563
  var MAX_VARCHAR = 191;
556
564
  var ONLINE_KINDS = ["PAYSTACK", "STITCH", "PAYFAST"];
@@ -633,6 +641,21 @@ var Tenant = class {
633
641
  }
634
642
  return [...byName.values()];
635
643
  }
644
+ /**
645
+ * A cheap summary of the live branches for cache_version: how many there
646
+ * are and when the newest one changed. A site whose Branches table has no
647
+ * updatedAt column yet gives the count alone.
648
+ */
649
+ async branchSummary() {
650
+ let rows = await this.rows("SELECT COUNT(*) AS {n}, MAX({updatedAt}) AS {lastUpdated} FROM {Branches} WHERE {isArchived} = ?", [false]);
651
+ if (!rows[0]) rows = await this.rows("SELECT COUNT(*) AS {n} FROM {Branches} WHERE {isArchived} = ?", [false]);
652
+ const row = rows[0] ?? {};
653
+ const last = row.lastUpdated;
654
+ return {
655
+ count: Number(row.n ?? 0) || 0,
656
+ lastUpdated: last === null || last === void 0 || last === "" ? null : last instanceof Date ? last.toISOString() : String(last)
657
+ };
658
+ }
636
659
  async codeForName(identifier, name) {
637
660
  const trimmed = name.trim();
638
661
  if (trimmed === "") return null;
@@ -1057,13 +1080,45 @@ var Tenant = class {
1057
1080
  }
1058
1081
  };
1059
1082
 
1083
+ // ../client/src/transport.ts
1084
+ var COUPON_CHANNELS = ["web", "app", "whatsapp"];
1085
+ function isCouponChannel(value) {
1086
+ return typeof value === "string" && COUPON_CHANNELS.includes(value);
1087
+ }
1088
+ var CHANNEL_HEADER = "x-fleetbridge-channel";
1089
+
1060
1090
  // src/server/public.handler.ts
1061
- var CUSTOMER_ERRORS = ["VALIDATION_ERROR", "INVALID_DATE", "UNAVAILABLE", "NOT_FOUND", "MIN_DAYS"];
1091
+ var CUSTOMER_ERRORS = [
1092
+ "VALIDATION_ERROR",
1093
+ "INVALID_DATE",
1094
+ "UNAVAILABLE",
1095
+ "NOT_FOUND",
1096
+ "MIN_DAYS",
1097
+ "COUPON_WRONG_CHANNEL",
1098
+ "COUPON_EXPIRED",
1099
+ "COUPON_REQUIRED",
1100
+ "COUPON_LIMIT_REACHED",
1101
+ "COUPON_CUSTOMER_LIMIT",
1102
+ "COUPON_NOT_CLAIMED"
1103
+ ];
1104
+ var SIGN_IN_MESSAGE = "Please sign in to claim a coupon.";
1105
+ var CLAIM_ERRORS = {
1106
+ COUPON_NOT_FOUND: { status: 404, message: "We could not find a coupon with that code." },
1107
+ COUPON_WRONG_CHANNEL: { status: 403 },
1108
+ COUPON_ALREADY_CLAIMED: { status: 409, message: "You have already claimed this coupon." },
1109
+ COUPON_EXPIRED: { status: 410 },
1110
+ VALIDATION_ERROR: { status: 422, message: "Please check the coupon code and try again." }
1111
+ };
1112
+ function channelFromHeader(request) {
1113
+ const value = request.headers.get(CHANNEL_HEADER)?.trim().toLowerCase() ?? "";
1114
+ return isCouponChannel(value) ? value : null;
1115
+ }
1062
1116
  var LOOKUP_ERROR = "We could not find a booking with that booking number and PIN. Please check both and try again.";
1063
1117
  var STAFF_ONLY = ["id", "bookingRef", "bookingPin", "supplierId", "customerId", "pickupBranchId", "dropoffBranchId", "updatedAt"];
1064
- var PUBLIC_ACTIONS = [
1118
+ var PUBLIC_ACTIONS2 = [
1065
1119
  "public_branches",
1066
1120
  "search_sources",
1121
+ "cache_version",
1067
1122
  "search_availability",
1068
1123
  "booking_request",
1069
1124
  "lookup_booking",
@@ -1078,8 +1133,11 @@ var PUBLIC_ACTIONS = [
1078
1133
  "verify_payment",
1079
1134
  "request_quote",
1080
1135
  "lookup_quote",
1081
- "confirm_quote"
1136
+ "confirm_quote",
1137
+ "claim_coupon",
1138
+ "my_coupons"
1082
1139
  ];
1140
+ var CUSTOMER_ACTIONS = ["claim_coupon", "my_coupons"];
1083
1141
  function createPublicHandler(opts) {
1084
1142
  const env = opts.env ?? (globalThis.process?.env ?? {});
1085
1143
  const timeZone = opts.timeZone ?? "Africa/Johannesburg";
@@ -1094,6 +1152,7 @@ function createPublicHandler(opts) {
1094
1152
  const tenant = new Tenant(storage ?? null, siteUrl, manageBookingPath);
1095
1153
  const hooks = opts.hooks ?? {};
1096
1154
  const getIp = opts.getIp ?? defaultIp;
1155
+ const getChannel = opts.getChannel ?? channelFromHeader;
1097
1156
  async function connected() {
1098
1157
  return (await opts.suppliers()).filter((s) => s.enabled !== false && s.supplierId && s.identifier);
1099
1158
  }
@@ -1126,14 +1185,18 @@ function createPublicHandler(opts) {
1126
1185
  return await opts.connector.forward(action, input);
1127
1186
  } catch (error) {
1128
1187
  const core = coreError(error);
1129
- log(`[FleetBridge] ${action} failed: ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1188
+ const ref = Math.random().toString(36).slice(2, 8).toUpperCase();
1189
+ log(`[FleetBridge] ${action} failed (ref ${ref}): ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1130
1190
  await hooks.onError?.({ action: ctx.action, error }).catch(() => void 0);
1131
1191
  if (quiet) return null;
1132
1192
  if (core) {
1133
- const shown = CUSTOMER_ERRORS.includes(core.code);
1134
- fail({ message: shown ? core.message : "Something went wrong. Please try again.", code: core.code }, core.status || 502);
1193
+ if (CUSTOMER_ERRORS.includes(core.code)) fail({ message: core.message, code: core.code }, core.status || 502);
1194
+ if (core.code === "SCHEMA_UPGRADE_REQUIRED") {
1195
+ fail({ message: `Online booking is being updated. Please try again shortly, or contact us (ref ${ref}).`, code: core.code, ref }, 503);
1196
+ }
1197
+ fail({ message: `We couldn't complete that just now. Please try again (ref ${ref}).`, code: core.code, ref }, core.status || 502);
1135
1198
  }
1136
- fail({ message: "Something went wrong. Please try again." }, 502);
1199
+ fail({ message: `We couldn't reach the booking system just now. Please try again in a moment (ref ${ref}).`, code: "SITE_ERROR", ref }, 502);
1137
1200
  }
1138
1201
  }
1139
1202
  function mapped(map) {
@@ -1148,6 +1211,39 @@ function createPublicHandler(opts) {
1148
1211
  async function publicBranches() {
1149
1212
  return success({ locations: await tenant.pickerLocations() });
1150
1213
  }
1214
+ const cacheTtlMs = Math.max(0, opts.cacheVersionTtlSeconds ?? 30) * 1e3;
1215
+ let cachedVersion = null;
1216
+ let computingVersion = null;
1217
+ async function computeCacheVersion() {
1218
+ const [summary, locations, accounts, stamp] = await Promise.all([
1219
+ tenant.branchSummary(),
1220
+ tenant.pickerLocations(),
1221
+ opts.suppliers(),
1222
+ opts.extraCacheStamp ? opts.extraCacheStamp().catch((error) => {
1223
+ log(`[FleetBridge] extraCacheStamp failed: ${error instanceof Error ? error.message : String(error)}`);
1224
+ return null;
1225
+ }) : Promise.resolve(null)
1226
+ ]);
1227
+ const suppliers = accounts.map((s) => ({ supplierId: String(s.supplierId ?? ""), identifier: String(s.identifier ?? ""), name: String(s.name ?? ""), logo: String(s.logo ?? ""), enabled: s.enabled !== false, login: hasCredentials(s) })).sort((a, b) => (a.identifier + a.supplierId).localeCompare(b.identifier + b.supplierId));
1228
+ const source2 = JSON.stringify({
1229
+ branches: summary,
1230
+ locations,
1231
+ suppliers,
1232
+ ownFleet: { on: !!opts.ownFleet, name: ownFleetName() },
1233
+ stamp: stamp ?? null
1234
+ });
1235
+ return { version: createHash("sha1").update(source2).digest("hex").slice(0, 16), generatedAt: (/* @__PURE__ */ new Date()).toISOString() };
1236
+ }
1237
+ async function cacheVersion(ctx) {
1238
+ await start(ctx, "cache_version", 600);
1239
+ if (cachedVersion && Date.now() - cachedVersion.at < cacheTtlMs) return success(cachedVersion.value);
1240
+ computingVersion ??= computeCacheVersion().finally(() => {
1241
+ computingVersion = null;
1242
+ });
1243
+ const value = await computingVersion;
1244
+ if (cacheTtlMs > 0) cachedVersion = { value, at: Date.now() };
1245
+ return success(value);
1246
+ }
1151
1247
  async function searchSources(ctx) {
1152
1248
  await start(ctx, "search", 60);
1153
1249
  const sources = [];
@@ -1157,7 +1253,9 @@ function createPublicHandler(opts) {
1157
1253
  ownFleet = true;
1158
1254
  continue;
1159
1255
  }
1160
- if (hasCredentials(row)) sources.push({ source: row.identifier, supplierName: row.name || row.identifier.charAt(0).toUpperCase() + row.identifier.slice(1) });
1256
+ if (!hasCredentials(row)) continue;
1257
+ const logoUrl = typeof row.logo === "string" && /^https?:\/\//i.test(row.logo) ? row.logo : void 0;
1258
+ sources.push({ source: row.identifier, supplierName: row.name || row.identifier.charAt(0).toUpperCase() + row.identifier.slice(1), ...logoUrl ? { logoUrl } : {} });
1161
1259
  }
1162
1260
  if (ownFleet || opts.ownFleet) sources.push({ source: OWN_FLEET, supplierName: ownFleetName() });
1163
1261
  return success({ sources });
@@ -1177,11 +1275,14 @@ function createPublicHandler(opts) {
1177
1275
  returnTime: field(ctx.fields, "returnTime", 5),
1178
1276
  promoCode: field(ctx.fields, "promoCode", 40),
1179
1277
  isInternational: field(ctx.fields, "isInternational", 5) === "true",
1180
- driverAge: field(ctx.fields, "driverAge", 3)
1278
+ driverAge: field(ctx.fields, "driverAge", 3),
1279
+ channel: ctx.channel
1181
1280
  },
1182
1281
  timeZone
1183
1282
  )
1184
1283
  );
1284
+ const who = trip2.promoCode ? await customerKeys(ctx) : null;
1285
+ if (who) trip2.customer = who;
1185
1286
  const ownFleetOn = await ownFleetConnection() !== null;
1186
1287
  const result = await forward(ctx, "search.availability", {
1187
1288
  trip: trip2,
@@ -1190,10 +1291,11 @@ function createPublicHandler(opts) {
1190
1291
  });
1191
1292
  const answer = searchAnswer(result?.data, ownFleetName());
1192
1293
  const count = answer.offers.reduce((sum, offer) => sum + (Array.isArray(offer.fleets) ? offer.fleets.length : 0), 0);
1193
- await hooks.onSearch?.({ trip: trip2, resultCount: count, sources: answer.sources }).catch(() => void 0);
1294
+ const { customer: _searcher, ...searched } = trip2;
1295
+ await hooks.onSearch?.({ trip: searched, resultCount: count, sources: answer.sources }).catch(() => void 0);
1194
1296
  if (answer.offers.length === 0) {
1195
1297
  const first = answer.sources.find((source2) => source2.message)?.message;
1196
- fail({ message: first || "No cars for those dates and places.", sources: answer.sources }, 404);
1298
+ fail({ message: first || "No cars for those dates and places.", sources: answer.sources, ...answer.couponNotice ? { couponNotice: answer.couponNotice } : {} }, 404);
1197
1299
  }
1198
1300
  return success(answer);
1199
1301
  }
@@ -1222,12 +1324,14 @@ function createPublicHandler(opts) {
1222
1324
  supplierId = found.supplierId;
1223
1325
  credentials = found.credentials;
1224
1326
  supplierName = found.name || supplierName;
1225
- note = mapped(() => notification(request, supplierName, timeZone));
1327
+ note = withManageLink(mapped(() => notification(request, supplierName, timeZone)));
1226
1328
  } else if (isEmail(request.email)) {
1227
- note = mapped(() => notification(request, supplierName, timeZone));
1329
+ note = withManageLink(mapped(() => notification(request, supplierName, timeZone)));
1228
1330
  }
1229
- const input = mapped(() => bookingInput(request, supplierId, credentials, timeZone, note));
1331
+ const input = mapped(() => bookingInput(request, supplierId, credentials, timeZone, note, ctx.channel));
1230
1332
  if (request.pay_online) input.payOnline = true;
1333
+ const signedInAs = (await customerKeys(ctx))?.authUserId;
1334
+ if (signedInAs) input.customer.authUserId = signedInAs;
1231
1335
  const result = await forward(ctx, "bookings.create", input);
1232
1336
  const booking = result?.data?.booking ?? null;
1233
1337
  const created = { booking: plain(booking), customer: input.customer, trip: input.trip, source: { ...input.source, credentials: void 0 }, extras: input.extras, price: plain(booking?.price ?? booking?.total ?? null) };
@@ -1324,6 +1428,10 @@ function createPublicHandler(opts) {
1324
1428
  if (!id) fail({ message: "This payment link is not valid. Please contact us with your booking details." }, 400);
1325
1429
  return id;
1326
1430
  }
1431
+ function withManageLink(note) {
1432
+ const url = tenant.manageBookingUrl("__RESERVATION__", "__PIN__");
1433
+ return url && isWebAddress(url) && !note.manageBookingUrl ? { ...note, manageBookingUrl: url } : note;
1434
+ }
1327
1435
  function bookingLookup(number, pin) {
1328
1436
  const typed = number.trim().replace(/^[\s.]+|[\s.]+$/g, "");
1329
1437
  const upper = typed.toUpperCase();
@@ -1410,7 +1518,9 @@ function createPublicHandler(opts) {
1410
1518
  if (!found || !hasCredentials(found)) fail({ message: "This booking cannot be changed online right now. Please contact us." }, 409);
1411
1519
  credentials = found.credentials;
1412
1520
  }
1413
- const input = mapped(() => amendInput(request, bookingLookup(number, pin), String(local.id), supplierId, credentials, timeZone, amendNotification(local, request)));
1521
+ const input = mapped(() => amendInput(request, bookingLookup(number, pin), String(local.id), supplierId, credentials, timeZone, amendNotification(local, request), ctx.channel));
1522
+ const signedInAs = (await customerKeys(ctx))?.authUserId;
1523
+ if (signedInAs && input.customer && typeof input.customer === "object") input.customer.authUserId = signedInAs;
1414
1524
  const result = await forward(ctx, "bookings.amend", input);
1415
1525
  const booking = await bookingView(result?.data?.booking ?? null, number, pin);
1416
1526
  await hooks.onBookingAmended?.({ booking, price: plain(result?.data?.price ?? null) }).catch(() => void 0);
@@ -1730,9 +1840,109 @@ function createPublicHandler(opts) {
1730
1840
  notes: s(quote.notes)
1731
1841
  };
1732
1842
  }
1843
+ async function currentCustomer(ctx) {
1844
+ if (ctx.customer !== void 0) return ctx.customer;
1845
+ ctx.customer = null;
1846
+ if (!opts.getCustomer) return null;
1847
+ try {
1848
+ ctx.customer = await opts.getCustomer(ctx.request) ?? null;
1849
+ } catch (error) {
1850
+ log(`[FleetBridge] getCustomer failed: ${error instanceof Error ? error.message : String(error)}`);
1851
+ }
1852
+ return ctx.customer;
1853
+ }
1854
+ async function customerKeys(ctx) {
1855
+ const customer2 = await currentCustomer(ctx);
1856
+ if (!customer2) return null;
1857
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1858
+ const email = String(customer2.email ?? "").trim().toLowerCase();
1859
+ const keys = { ...authUserId ? { authUserId } : {}, ...isEmail(email) ? { email } : {} };
1860
+ return Object.keys(keys).length ? keys : null;
1861
+ }
1862
+ async function signedIn(ctx) {
1863
+ const customer2 = await currentCustomer(ctx);
1864
+ const email = String(customer2?.email ?? "").trim().toLowerCase();
1865
+ if (!customer2 || !isEmail(email)) fail({ message: SIGN_IN_MESSAGE, code: "SIGN_IN_REQUIRED" }, 401);
1866
+ return { ...customer2, email };
1867
+ }
1868
+ function appCoupon(coupon, claim) {
1869
+ const num = (value, fallback) => value === null || value === void 0 || value === "" || !Number.isFinite(Number(value)) ? fallback : Number(value);
1870
+ const text = (value) => value === null || value === void 0 || value === "" ? null : String(value);
1871
+ return {
1872
+ id: String(claim.couponId ?? coupon.id ?? ""),
1873
+ code: String(coupon.code ?? ""),
1874
+ description: coupon.description ? String(coupon.description) : null,
1875
+ discountType: String(coupon.discountType ?? "PERCENTAGE"),
1876
+ discountValue: num(coupon.discountValue, 0),
1877
+ startDate: coupon.startDate ? String(coupon.startDate) : null,
1878
+ endDate: coupon.endDate ? String(coupon.endDate) : null,
1879
+ usageLimit: num(coupon.usageLimit, null),
1880
+ usageCount: num(coupon.usageCount, 0),
1881
+ usesByCustomer: num(coupon.usesByCustomer, 0),
1882
+ perCustomerLimit: num(coupon.perCustomerLimit, null),
1883
+ remainingForCustomer: num(coupon.remainingForCustomer, null),
1884
+ requireClaim: coupon.requireClaim === true,
1885
+ supplierIdentifier: text(coupon.supplierIdentifier),
1886
+ supplierName: text(coupon.supplierName),
1887
+ unlocksSpecialRate: coupon.unlocksSpecialRate === true || text(coupon.cdpCodeId) !== null,
1888
+ isActive: coupon.isActive !== false,
1889
+ isLive: !!coupon.isLive,
1890
+ channels: Array.isArray(coupon.channels) ? coupon.channels.map(String) : [],
1891
+ channel: String(claim.channel ?? ""),
1892
+ claimType: claim.claimType ? String(claim.claimType) : null,
1893
+ claimedAt: String(claim.claimedAt ?? "")
1894
+ };
1895
+ }
1896
+ async function claimCoupon(ctx) {
1897
+ await start(ctx, "coupon_claim", 10);
1898
+ const customer2 = await signedIn(ctx);
1899
+ const code = field(ctx.fields, "code", 60);
1900
+ if (code === "") fail({ message: "Please enter a coupon code." }, 400);
1901
+ const claimType = field(ctx.fields, "claimType", 60);
1902
+ const channel = ctx.channel ?? "web";
1903
+ const who = { email: customer2.email };
1904
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1905
+ if (authUserId) who.authUserId = authUserId;
1906
+ for (const key of ["firstName", "lastName", "phone"]) {
1907
+ const value = cut(String(customer2[key] ?? "").trim(), key === "phone" ? 40 : 100);
1908
+ if (value !== "") who[key] = value;
1909
+ }
1910
+ let result;
1911
+ try {
1912
+ result = await opts.connector.forward("promotions.coupons.claim", { code, customer: who, channel, ...claimType ? { claimType } : {} });
1913
+ } catch (error) {
1914
+ const core = coreError(error);
1915
+ const known = core ? CLAIM_ERRORS[core.code] : void 0;
1916
+ if (core && known) fail({ message: known.message ?? core.message, code: core.code }, known.status);
1917
+ log(`[FleetBridge] promotions.coupons.claim failed: ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1918
+ await hooks.onError?.({ action: ctx.action, error }).catch(() => void 0);
1919
+ fail({ message: "Something went wrong. Please try again." }, 502);
1920
+ }
1921
+ const last = result.acks[result.acks.length - 1];
1922
+ if (last?.status === "conflict") fail({ message: CLAIM_ERRORS.COUPON_ALREADY_CLAIMED.message, code: "COUPON_ALREADY_CLAIMED" }, 409);
1923
+ if (last && last.status !== "applied") {
1924
+ log(`[FleetBridge] promotions.coupons.claim was not applied: ${last.status}`);
1925
+ fail({ message: "Something went wrong. Please try again." }, 502);
1926
+ }
1927
+ const data = result.data ?? {};
1928
+ if (!data.coupon || !data.claim) fail({ message: "Something went wrong. Please try again." }, 502);
1929
+ const coupon = appCoupon(data.coupon, data.claim);
1930
+ const owner = data.customer ?? {};
1931
+ await hooks.onCouponClaimed?.({ coupon, customer: { id: String(owner.id ?? ""), email: String(owner.email ?? customer2.email), isNew: !!owner.isNew }, channel, claimType: claimType || null }).catch(() => void 0);
1932
+ return success({ coupon });
1933
+ }
1934
+ async function myCoupons(ctx) {
1935
+ await start(ctx, "coupon_list", 60);
1936
+ const customer2 = await signedIn(ctx);
1937
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1938
+ const result = await forward(ctx, "promotions.coupons.claims", { email: customer2.email, ...authUserId ? { authUserId } : {} });
1939
+ const items = Array.isArray(result?.data?.items) ? result.data.items : [];
1940
+ return success({ coupons: items.map((item) => appCoupon(item, item)) });
1941
+ }
1733
1942
  const routes = {
1734
1943
  public_branches: publicBranches,
1735
1944
  search_sources: searchSources,
1945
+ cache_version: cacheVersion,
1736
1946
  search_availability: search,
1737
1947
  booking_request: book,
1738
1948
  lookup_booking: lookup,
@@ -1747,7 +1957,9 @@ function createPublicHandler(opts) {
1747
1957
  verify_payment: verifyPayment,
1748
1958
  request_quote: requestQuote,
1749
1959
  lookup_quote: lookupQuote,
1750
- confirm_quote: confirmQuote
1960
+ confirm_quote: confirmQuote,
1961
+ claim_coupon: claimCoupon,
1962
+ my_coupons: myCoupons
1751
1963
  };
1752
1964
  return async function handle(request) {
1753
1965
  if (request.method !== "POST") return json({ success: false, data: { message: "Use POST." } }, 405);
@@ -1760,8 +1972,11 @@ function createPublicHandler(opts) {
1760
1972
  const name = String(fields.action ?? "").replace(/^fleetbridge_/, "");
1761
1973
  const route = routes[name];
1762
1974
  if (!route) return json({ success: false, data: { message: "Unknown action." } }, 400);
1763
- const ctx = { action: name, fields, ip: getIp(request), request };
1975
+ if (CUSTOMER_ACTIONS.includes(name) && !opts.getCustomer) return json({ success: false, data: { message: "Unknown action." } }, 404);
1976
+ const ctx = { action: name, fields, ip: getIp(request), request, channel: null };
1764
1977
  try {
1978
+ ctx.channel = await getChannel(request) ?? null;
1979
+ if (ctx.channel !== null && !isCouponChannel(ctx.channel)) ctx.channel = null;
1765
1980
  const stop = await hooks.beforeAction?.({ action: name, fields, ip: ctx.ip, request });
1766
1981
  if (stop) return stop;
1767
1982
  return await route(ctx);
@@ -1858,10 +2073,12 @@ export {
1858
2073
  LOOKUP_ERROR,
1859
2074
  MemoryStateStore,
1860
2075
  OWN_FLEET,
1861
- PUBLIC_ACTIONS,
2076
+ PUBLIC_ACTIONS2 as PUBLIC_ACTIONS,
2077
+ SIGN_IN_MESSAGE,
1862
2078
  STAFF_ADMIN_ALLOW,
1863
2079
  STAFF_ONLY,
1864
2080
  adminMayRun,
2081
+ channelFromHeader,
1865
2082
  createAdminHandler,
1866
2083
  createPublicHandler,
1867
2084
  readSuppliersFromEnv