@fleetbridge/ui 1.1.1 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fleetbridge/ui",
3
- "version": "1.1.1",
3
+ "version": "1.4.0",
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;
@@ -324,7 +325,8 @@ function searchAnswer(data, ownFleetName) {
324
325
  }
325
326
  const own = JSON.parse(JSON.stringify(data?.ownFleet ?? []));
326
327
  if (own.length > 0) offers.push(ownFleetOffer(own, ownFleetName));
327
- return { offers, sources: JSON.parse(JSON.stringify(data?.sources ?? [])) };
328
+ const notice = data?.couponNotice && typeof data.couponNotice === "object" ? JSON.parse(JSON.stringify(data.couponNotice)) : void 0;
329
+ return { offers, sources: JSON.parse(JSON.stringify(data?.sources ?? [])), ...notice ? { couponNotice: notice } : {} };
328
330
  }
329
331
  function ownFleetOffer(classes, name) {
330
332
  const fromCore = typeof classes[0]?.supplierName === "string" ? classes[0].supplierName.trim() : "";
@@ -408,9 +410,9 @@ function ownFleetRate(item) {
408
410
  }
409
411
  return rate;
410
412
  }
411
- function bookingInput(request, supplierId, credentials, timeZone, notification2 = null) {
413
+ function bookingInput(request, supplierId, credentials, timeZone, notification2 = null, channel = null) {
412
414
  const input = {
413
- trip: bookingTrip(request, timeZone),
415
+ trip: bookingTrip(request, timeZone, channel),
414
416
  source: source(request, supplierId, credentials),
415
417
  customer: customer(request),
416
418
  extras: extras(request),
@@ -421,10 +423,10 @@ function bookingInput(request, supplierId, credentials, timeZone, notification2
421
423
  if (request.terms_id !== "" && request.terms_version > 0) input.terms = { id: request.terms_id, version: request.terms_version };
422
424
  return input;
423
425
  }
424
- function amendInput(request, booking, bookingId, supplierId, credentials, timeZone, notification2 = null) {
425
- return { booking, bookingId: String(bookingId), ...bookingInput(request, supplierId, credentials, timeZone, notification2) };
426
+ function amendInput(request, booking, bookingId, supplierId, credentials, timeZone, notification2 = null, channel = null) {
427
+ return { booking, bookingId: String(bookingId), ...bookingInput(request, supplierId, credentials, timeZone, notification2, channel) };
426
428
  }
427
- function bookingTrip(request, timeZone) {
429
+ function bookingTrip(request, timeZone, channel = null) {
428
430
  return trip(
429
431
  {
430
432
  pickupLocation: request.pickup_location,
@@ -434,7 +436,8 @@ function bookingTrip(request, timeZone) {
434
436
  returnDate: request.return_date,
435
437
  returnTime: request.return_time,
436
438
  promoCode: request.coupon,
437
- isInternational: request.is_international
439
+ isInternational: request.is_international,
440
+ channel
438
441
  },
439
442
  timeZone
440
443
  );
@@ -551,6 +554,9 @@ function priceLines(request) {
551
554
  return lines;
552
555
  }
553
556
 
557
+ // src/server/public.handler.ts
558
+ import { createHash } from "node:crypto";
559
+
554
560
  // src/server/tenant.ts
555
561
  var MAX_VARCHAR = 191;
556
562
  var ONLINE_KINDS = ["PAYSTACK", "STITCH", "PAYFAST"];
@@ -633,6 +639,21 @@ var Tenant = class {
633
639
  }
634
640
  return [...byName.values()];
635
641
  }
642
+ /**
643
+ * A cheap summary of the live branches for cache_version: how many there
644
+ * are and when the newest one changed. A site whose Branches table has no
645
+ * updatedAt column yet gives the count alone.
646
+ */
647
+ async branchSummary() {
648
+ let rows = await this.rows("SELECT COUNT(*) AS {n}, MAX({updatedAt}) AS {lastUpdated} FROM {Branches} WHERE {isArchived} = ?", [false]);
649
+ if (!rows[0]) rows = await this.rows("SELECT COUNT(*) AS {n} FROM {Branches} WHERE {isArchived} = ?", [false]);
650
+ const row = rows[0] ?? {};
651
+ const last = row.lastUpdated;
652
+ return {
653
+ count: Number(row.n ?? 0) || 0,
654
+ lastUpdated: last === null || last === void 0 || last === "" ? null : last instanceof Date ? last.toISOString() : String(last)
655
+ };
656
+ }
636
657
  async codeForName(identifier, name) {
637
658
  const trimmed = name.trim();
638
659
  if (trimmed === "") return null;
@@ -1057,13 +1078,45 @@ var Tenant = class {
1057
1078
  }
1058
1079
  };
1059
1080
 
1081
+ // ../client/src/transport.ts
1082
+ var COUPON_CHANNELS = ["web", "app", "whatsapp"];
1083
+ function isCouponChannel(value) {
1084
+ return typeof value === "string" && COUPON_CHANNELS.includes(value);
1085
+ }
1086
+ var CHANNEL_HEADER = "x-fleetbridge-channel";
1087
+
1060
1088
  // src/server/public.handler.ts
1061
- var CUSTOMER_ERRORS = ["VALIDATION_ERROR", "INVALID_DATE", "UNAVAILABLE", "NOT_FOUND", "MIN_DAYS"];
1089
+ var CUSTOMER_ERRORS = [
1090
+ "VALIDATION_ERROR",
1091
+ "INVALID_DATE",
1092
+ "UNAVAILABLE",
1093
+ "NOT_FOUND",
1094
+ "MIN_DAYS",
1095
+ "COUPON_WRONG_CHANNEL",
1096
+ "COUPON_EXPIRED",
1097
+ "COUPON_REQUIRED",
1098
+ "COUPON_LIMIT_REACHED",
1099
+ "COUPON_CUSTOMER_LIMIT",
1100
+ "COUPON_NOT_CLAIMED"
1101
+ ];
1102
+ var SIGN_IN_MESSAGE = "Please sign in to claim a coupon.";
1103
+ var CLAIM_ERRORS = {
1104
+ COUPON_NOT_FOUND: { status: 404, message: "We could not find a coupon with that code." },
1105
+ COUPON_WRONG_CHANNEL: { status: 403 },
1106
+ COUPON_ALREADY_CLAIMED: { status: 409, message: "You have already claimed this coupon." },
1107
+ COUPON_EXPIRED: { status: 410 },
1108
+ VALIDATION_ERROR: { status: 422, message: "Please check the coupon code and try again." }
1109
+ };
1110
+ function channelFromHeader(request) {
1111
+ const value = request.headers.get(CHANNEL_HEADER)?.trim().toLowerCase() ?? "";
1112
+ return isCouponChannel(value) ? value : null;
1113
+ }
1062
1114
  var LOOKUP_ERROR = "We could not find a booking with that booking number and PIN. Please check both and try again.";
1063
1115
  var STAFF_ONLY = ["id", "bookingRef", "bookingPin", "supplierId", "customerId", "pickupBranchId", "dropoffBranchId", "updatedAt"];
1064
- var PUBLIC_ACTIONS = [
1116
+ var PUBLIC_ACTIONS2 = [
1065
1117
  "public_branches",
1066
1118
  "search_sources",
1119
+ "cache_version",
1067
1120
  "search_availability",
1068
1121
  "booking_request",
1069
1122
  "lookup_booking",
@@ -1078,8 +1131,11 @@ var PUBLIC_ACTIONS = [
1078
1131
  "verify_payment",
1079
1132
  "request_quote",
1080
1133
  "lookup_quote",
1081
- "confirm_quote"
1134
+ "confirm_quote",
1135
+ "claim_coupon",
1136
+ "my_coupons"
1082
1137
  ];
1138
+ var CUSTOMER_ACTIONS = ["claim_coupon", "my_coupons"];
1083
1139
  function createPublicHandler(opts) {
1084
1140
  const env = opts.env ?? (globalThis.process?.env ?? {});
1085
1141
  const timeZone = opts.timeZone ?? "Africa/Johannesburg";
@@ -1094,6 +1150,7 @@ function createPublicHandler(opts) {
1094
1150
  const tenant = new Tenant(storage ?? null, siteUrl, manageBookingPath);
1095
1151
  const hooks = opts.hooks ?? {};
1096
1152
  const getIp = opts.getIp ?? defaultIp;
1153
+ const getChannel = opts.getChannel ?? channelFromHeader;
1097
1154
  async function connected() {
1098
1155
  return (await opts.suppliers()).filter((s) => s.enabled !== false && s.supplierId && s.identifier);
1099
1156
  }
@@ -1126,14 +1183,18 @@ function createPublicHandler(opts) {
1126
1183
  return await opts.connector.forward(action, input);
1127
1184
  } catch (error) {
1128
1185
  const core = coreError(error);
1129
- log(`[FleetBridge] ${action} failed: ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1186
+ const ref = Math.random().toString(36).slice(2, 8).toUpperCase();
1187
+ log(`[FleetBridge] ${action} failed (ref ${ref}): ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1130
1188
  await hooks.onError?.({ action: ctx.action, error }).catch(() => void 0);
1131
1189
  if (quiet) return null;
1132
1190
  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);
1191
+ if (CUSTOMER_ERRORS.includes(core.code)) fail({ message: core.message, code: core.code }, core.status || 502);
1192
+ if (core.code === "SCHEMA_UPGRADE_REQUIRED") {
1193
+ fail({ message: `Online booking is being updated. Please try again shortly, or contact us (ref ${ref}).`, code: core.code, ref }, 503);
1194
+ }
1195
+ fail({ message: `We couldn't complete that just now. Please try again (ref ${ref}).`, code: core.code, ref }, core.status || 502);
1135
1196
  }
1136
- fail({ message: "Something went wrong. Please try again." }, 502);
1197
+ 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
1198
  }
1138
1199
  }
1139
1200
  function mapped(map) {
@@ -1148,6 +1209,39 @@ function createPublicHandler(opts) {
1148
1209
  async function publicBranches() {
1149
1210
  return success({ locations: await tenant.pickerLocations() });
1150
1211
  }
1212
+ const cacheTtlMs = Math.max(0, opts.cacheVersionTtlSeconds ?? 30) * 1e3;
1213
+ let cachedVersion = null;
1214
+ let computingVersion = null;
1215
+ async function computeCacheVersion() {
1216
+ const [summary, locations, accounts, stamp] = await Promise.all([
1217
+ tenant.branchSummary(),
1218
+ tenant.pickerLocations(),
1219
+ opts.suppliers(),
1220
+ opts.extraCacheStamp ? opts.extraCacheStamp().catch((error) => {
1221
+ log(`[FleetBridge] extraCacheStamp failed: ${error instanceof Error ? error.message : String(error)}`);
1222
+ return null;
1223
+ }) : Promise.resolve(null)
1224
+ ]);
1225
+ 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));
1226
+ const source2 = JSON.stringify({
1227
+ branches: summary,
1228
+ locations,
1229
+ suppliers,
1230
+ ownFleet: { on: !!opts.ownFleet, name: ownFleetName() },
1231
+ stamp: stamp ?? null
1232
+ });
1233
+ return { version: createHash("sha1").update(source2).digest("hex").slice(0, 16), generatedAt: (/* @__PURE__ */ new Date()).toISOString() };
1234
+ }
1235
+ async function cacheVersion(ctx) {
1236
+ await start(ctx, "cache_version", 600);
1237
+ if (cachedVersion && Date.now() - cachedVersion.at < cacheTtlMs) return success(cachedVersion.value);
1238
+ computingVersion ??= computeCacheVersion().finally(() => {
1239
+ computingVersion = null;
1240
+ });
1241
+ const value = await computingVersion;
1242
+ if (cacheTtlMs > 0) cachedVersion = { value, at: Date.now() };
1243
+ return success(value);
1244
+ }
1151
1245
  async function searchSources(ctx) {
1152
1246
  await start(ctx, "search", 60);
1153
1247
  const sources = [];
@@ -1157,7 +1251,9 @@ function createPublicHandler(opts) {
1157
1251
  ownFleet = true;
1158
1252
  continue;
1159
1253
  }
1160
- if (hasCredentials(row)) sources.push({ source: row.identifier, supplierName: row.name || row.identifier.charAt(0).toUpperCase() + row.identifier.slice(1) });
1254
+ if (!hasCredentials(row)) continue;
1255
+ const logoUrl = typeof row.logo === "string" && /^https?:\/\//i.test(row.logo) ? row.logo : void 0;
1256
+ sources.push({ source: row.identifier, supplierName: row.name || row.identifier.charAt(0).toUpperCase() + row.identifier.slice(1), ...logoUrl ? { logoUrl } : {} });
1161
1257
  }
1162
1258
  if (ownFleet || opts.ownFleet) sources.push({ source: OWN_FLEET, supplierName: ownFleetName() });
1163
1259
  return success({ sources });
@@ -1177,11 +1273,14 @@ function createPublicHandler(opts) {
1177
1273
  returnTime: field(ctx.fields, "returnTime", 5),
1178
1274
  promoCode: field(ctx.fields, "promoCode", 40),
1179
1275
  isInternational: field(ctx.fields, "isInternational", 5) === "true",
1180
- driverAge: field(ctx.fields, "driverAge", 3)
1276
+ driverAge: field(ctx.fields, "driverAge", 3),
1277
+ channel: ctx.channel
1181
1278
  },
1182
1279
  timeZone
1183
1280
  )
1184
1281
  );
1282
+ const who = trip2.promoCode ? await customerKeys(ctx) : null;
1283
+ if (who) trip2.customer = who;
1185
1284
  const ownFleetOn = await ownFleetConnection() !== null;
1186
1285
  const result = await forward(ctx, "search.availability", {
1187
1286
  trip: trip2,
@@ -1190,10 +1289,11 @@ function createPublicHandler(opts) {
1190
1289
  });
1191
1290
  const answer = searchAnswer(result?.data, ownFleetName());
1192
1291
  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);
1292
+ const { customer: _searcher, ...searched } = trip2;
1293
+ await hooks.onSearch?.({ trip: searched, resultCount: count, sources: answer.sources }).catch(() => void 0);
1194
1294
  if (answer.offers.length === 0) {
1195
1295
  const first = answer.sources.find((source2) => source2.message)?.message;
1196
- fail({ message: first || "No cars for those dates and places.", sources: answer.sources }, 404);
1296
+ fail({ message: first || "No cars for those dates and places.", sources: answer.sources, ...answer.couponNotice ? { couponNotice: answer.couponNotice } : {} }, 404);
1197
1297
  }
1198
1298
  return success(answer);
1199
1299
  }
@@ -1226,8 +1326,10 @@ function createPublicHandler(opts) {
1226
1326
  } else if (isEmail(request.email)) {
1227
1327
  note = mapped(() => notification(request, supplierName, timeZone));
1228
1328
  }
1229
- const input = mapped(() => bookingInput(request, supplierId, credentials, timeZone, note));
1329
+ const input = mapped(() => bookingInput(request, supplierId, credentials, timeZone, note, ctx.channel));
1230
1330
  if (request.pay_online) input.payOnline = true;
1331
+ const signedInAs = (await customerKeys(ctx))?.authUserId;
1332
+ if (signedInAs) input.customer.authUserId = signedInAs;
1231
1333
  const result = await forward(ctx, "bookings.create", input);
1232
1334
  const booking = result?.data?.booking ?? null;
1233
1335
  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) };
@@ -1410,7 +1512,9 @@ function createPublicHandler(opts) {
1410
1512
  if (!found || !hasCredentials(found)) fail({ message: "This booking cannot be changed online right now. Please contact us." }, 409);
1411
1513
  credentials = found.credentials;
1412
1514
  }
1413
- const input = mapped(() => amendInput(request, bookingLookup(number, pin), String(local.id), supplierId, credentials, timeZone, amendNotification(local, request)));
1515
+ const input = mapped(() => amendInput(request, bookingLookup(number, pin), String(local.id), supplierId, credentials, timeZone, amendNotification(local, request), ctx.channel));
1516
+ const signedInAs = (await customerKeys(ctx))?.authUserId;
1517
+ if (signedInAs && input.customer && typeof input.customer === "object") input.customer.authUserId = signedInAs;
1414
1518
  const result = await forward(ctx, "bookings.amend", input);
1415
1519
  const booking = await bookingView(result?.data?.booking ?? null, number, pin);
1416
1520
  await hooks.onBookingAmended?.({ booking, price: plain(result?.data?.price ?? null) }).catch(() => void 0);
@@ -1730,9 +1834,109 @@ function createPublicHandler(opts) {
1730
1834
  notes: s(quote.notes)
1731
1835
  };
1732
1836
  }
1837
+ async function currentCustomer(ctx) {
1838
+ if (ctx.customer !== void 0) return ctx.customer;
1839
+ ctx.customer = null;
1840
+ if (!opts.getCustomer) return null;
1841
+ try {
1842
+ ctx.customer = await opts.getCustomer(ctx.request) ?? null;
1843
+ } catch (error) {
1844
+ log(`[FleetBridge] getCustomer failed: ${error instanceof Error ? error.message : String(error)}`);
1845
+ }
1846
+ return ctx.customer;
1847
+ }
1848
+ async function customerKeys(ctx) {
1849
+ const customer2 = await currentCustomer(ctx);
1850
+ if (!customer2) return null;
1851
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1852
+ const email = String(customer2.email ?? "").trim().toLowerCase();
1853
+ const keys = { ...authUserId ? { authUserId } : {}, ...isEmail(email) ? { email } : {} };
1854
+ return Object.keys(keys).length ? keys : null;
1855
+ }
1856
+ async function signedIn(ctx) {
1857
+ const customer2 = await currentCustomer(ctx);
1858
+ const email = String(customer2?.email ?? "").trim().toLowerCase();
1859
+ if (!customer2 || !isEmail(email)) fail({ message: SIGN_IN_MESSAGE, code: "SIGN_IN_REQUIRED" }, 401);
1860
+ return { ...customer2, email };
1861
+ }
1862
+ function appCoupon(coupon, claim) {
1863
+ const num = (value, fallback) => value === null || value === void 0 || value === "" || !Number.isFinite(Number(value)) ? fallback : Number(value);
1864
+ const text = (value) => value === null || value === void 0 || value === "" ? null : String(value);
1865
+ return {
1866
+ id: String(claim.couponId ?? coupon.id ?? ""),
1867
+ code: String(coupon.code ?? ""),
1868
+ description: coupon.description ? String(coupon.description) : null,
1869
+ discountType: String(coupon.discountType ?? "PERCENTAGE"),
1870
+ discountValue: num(coupon.discountValue, 0),
1871
+ startDate: coupon.startDate ? String(coupon.startDate) : null,
1872
+ endDate: coupon.endDate ? String(coupon.endDate) : null,
1873
+ usageLimit: num(coupon.usageLimit, null),
1874
+ usageCount: num(coupon.usageCount, 0),
1875
+ usesByCustomer: num(coupon.usesByCustomer, 0),
1876
+ perCustomerLimit: num(coupon.perCustomerLimit, null),
1877
+ remainingForCustomer: num(coupon.remainingForCustomer, null),
1878
+ requireClaim: coupon.requireClaim === true,
1879
+ supplierIdentifier: text(coupon.supplierIdentifier),
1880
+ supplierName: text(coupon.supplierName),
1881
+ unlocksSpecialRate: coupon.unlocksSpecialRate === true || text(coupon.cdpCodeId) !== null,
1882
+ isActive: coupon.isActive !== false,
1883
+ isLive: !!coupon.isLive,
1884
+ channels: Array.isArray(coupon.channels) ? coupon.channels.map(String) : [],
1885
+ channel: String(claim.channel ?? ""),
1886
+ claimType: claim.claimType ? String(claim.claimType) : null,
1887
+ claimedAt: String(claim.claimedAt ?? "")
1888
+ };
1889
+ }
1890
+ async function claimCoupon(ctx) {
1891
+ await start(ctx, "coupon_claim", 10);
1892
+ const customer2 = await signedIn(ctx);
1893
+ const code = field(ctx.fields, "code", 60);
1894
+ if (code === "") fail({ message: "Please enter a coupon code." }, 400);
1895
+ const claimType = field(ctx.fields, "claimType", 60);
1896
+ const channel = ctx.channel ?? "web";
1897
+ const who = { email: customer2.email };
1898
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1899
+ if (authUserId) who.authUserId = authUserId;
1900
+ for (const key of ["firstName", "lastName", "phone"]) {
1901
+ const value = cut(String(customer2[key] ?? "").trim(), key === "phone" ? 40 : 100);
1902
+ if (value !== "") who[key] = value;
1903
+ }
1904
+ let result;
1905
+ try {
1906
+ result = await opts.connector.forward("promotions.coupons.claim", { code, customer: who, channel, ...claimType ? { claimType } : {} });
1907
+ } catch (error) {
1908
+ const core = coreError(error);
1909
+ const known = core ? CLAIM_ERRORS[core.code] : void 0;
1910
+ if (core && known) fail({ message: known.message ?? core.message, code: core.code }, known.status);
1911
+ log(`[FleetBridge] promotions.coupons.claim failed: ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
1912
+ await hooks.onError?.({ action: ctx.action, error }).catch(() => void 0);
1913
+ fail({ message: "Something went wrong. Please try again." }, 502);
1914
+ }
1915
+ const last = result.acks[result.acks.length - 1];
1916
+ if (last?.status === "conflict") fail({ message: CLAIM_ERRORS.COUPON_ALREADY_CLAIMED.message, code: "COUPON_ALREADY_CLAIMED" }, 409);
1917
+ if (last && last.status !== "applied") {
1918
+ log(`[FleetBridge] promotions.coupons.claim was not applied: ${last.status}`);
1919
+ fail({ message: "Something went wrong. Please try again." }, 502);
1920
+ }
1921
+ const data = result.data ?? {};
1922
+ if (!data.coupon || !data.claim) fail({ message: "Something went wrong. Please try again." }, 502);
1923
+ const coupon = appCoupon(data.coupon, data.claim);
1924
+ const owner = data.customer ?? {};
1925
+ 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);
1926
+ return success({ coupon });
1927
+ }
1928
+ async function myCoupons(ctx) {
1929
+ await start(ctx, "coupon_list", 60);
1930
+ const customer2 = await signedIn(ctx);
1931
+ const authUserId = cut(String(customer2.authUserId ?? "").trim(), 191);
1932
+ const result = await forward(ctx, "promotions.coupons.claims", { email: customer2.email, ...authUserId ? { authUserId } : {} });
1933
+ const items = Array.isArray(result?.data?.items) ? result.data.items : [];
1934
+ return success({ coupons: items.map((item) => appCoupon(item, item)) });
1935
+ }
1733
1936
  const routes = {
1734
1937
  public_branches: publicBranches,
1735
1938
  search_sources: searchSources,
1939
+ cache_version: cacheVersion,
1736
1940
  search_availability: search,
1737
1941
  booking_request: book,
1738
1942
  lookup_booking: lookup,
@@ -1747,7 +1951,9 @@ function createPublicHandler(opts) {
1747
1951
  verify_payment: verifyPayment,
1748
1952
  request_quote: requestQuote,
1749
1953
  lookup_quote: lookupQuote,
1750
- confirm_quote: confirmQuote
1954
+ confirm_quote: confirmQuote,
1955
+ claim_coupon: claimCoupon,
1956
+ my_coupons: myCoupons
1751
1957
  };
1752
1958
  return async function handle(request) {
1753
1959
  if (request.method !== "POST") return json({ success: false, data: { message: "Use POST." } }, 405);
@@ -1760,8 +1966,11 @@ function createPublicHandler(opts) {
1760
1966
  const name = String(fields.action ?? "").replace(/^fleetbridge_/, "");
1761
1967
  const route = routes[name];
1762
1968
  if (!route) return json({ success: false, data: { message: "Unknown action." } }, 400);
1763
- const ctx = { action: name, fields, ip: getIp(request), request };
1969
+ if (CUSTOMER_ACTIONS.includes(name) && !opts.getCustomer) return json({ success: false, data: { message: "Unknown action." } }, 404);
1970
+ const ctx = { action: name, fields, ip: getIp(request), request, channel: null };
1764
1971
  try {
1972
+ ctx.channel = await getChannel(request) ?? null;
1973
+ if (ctx.channel !== null && !isCouponChannel(ctx.channel)) ctx.channel = null;
1765
1974
  const stop = await hooks.beforeAction?.({ action: name, fields, ip: ctx.ip, request });
1766
1975
  if (stop) return stop;
1767
1976
  return await route(ctx);
@@ -1858,10 +2067,12 @@ export {
1858
2067
  LOOKUP_ERROR,
1859
2068
  MemoryStateStore,
1860
2069
  OWN_FLEET,
1861
- PUBLIC_ACTIONS,
2070
+ PUBLIC_ACTIONS2 as PUBLIC_ACTIONS,
2071
+ SIGN_IN_MESSAGE,
1862
2072
  STAFF_ADMIN_ALLOW,
1863
2073
  STAFF_ONLY,
1864
2074
  adminMayRun,
2075
+ channelFromHeader,
1865
2076
  createAdminHandler,
1866
2077
  createPublicHandler,
1867
2078
  readSuppliersFromEnv