@fleetbridge/ui 0.0.0-stage → 1.0.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 +207 -2
- package/index.d.ts +1937 -0
- package/index.js +14146 -0
- package/package.json +94 -4
- package/server.d.ts +199 -0
- package/server.js +1865 -0
- package/styles.css +2 -0
- package/theme.d.ts +170 -0
- package/theme.js +336 -0
package/server.js
ADDED
|
@@ -0,0 +1,1865 @@
|
|
|
1
|
+
// src/server/support.ts
|
|
2
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
|
+
var Stop = class extends Error {
|
|
4
|
+
constructor(response) {
|
|
5
|
+
super("stop");
|
|
6
|
+
this.response = response;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
function json(body, status = 200) {
|
|
10
|
+
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
11
|
+
}
|
|
12
|
+
function success(data) {
|
|
13
|
+
return json({ success: true, data });
|
|
14
|
+
}
|
|
15
|
+
function fail(data, status) {
|
|
16
|
+
throw new Stop(json({ success: false, data }, status));
|
|
17
|
+
}
|
|
18
|
+
async function readFields(request) {
|
|
19
|
+
const type = request.headers.get("content-type") ?? "";
|
|
20
|
+
const out = {};
|
|
21
|
+
if (type.includes("application/json")) {
|
|
22
|
+
const body = await request.json().catch(() => null);
|
|
23
|
+
if (body && typeof body === "object" && !Array.isArray(body)) {
|
|
24
|
+
const record = body;
|
|
25
|
+
const flat = record.fields && typeof record.fields === "object" ? { action: record.action, ...record.fields } : record;
|
|
26
|
+
for (const [key, value] of Object.entries(flat)) {
|
|
27
|
+
if (value === void 0 || value === null) continue;
|
|
28
|
+
out[key] = typeof value === "string" ? value : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
if (type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded")) {
|
|
34
|
+
const form = await request.formData();
|
|
35
|
+
form.forEach((value, key) => {
|
|
36
|
+
if (typeof value === "string") out[key] = value;
|
|
37
|
+
});
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
if (request.method === "GET") {
|
|
41
|
+
new URL(request.url).searchParams.forEach((value, key) => out[key] = value);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
function sanitizeText(value) {
|
|
46
|
+
return value.replace(/<[^>]*>?/g, "").replace(/%[a-f0-9]{2}/gi, "").replace(/[\r\n\t ]+/g, " ").trim();
|
|
47
|
+
}
|
|
48
|
+
function sanitizeTextarea(value) {
|
|
49
|
+
return value.replace(/<[^>]*>?/g, "").replace(/%[a-f0-9]{2}/gi, "").split("\n").map((line) => line.replace(/[\t ]+/g, " ").trim()).join("\n").trim();
|
|
50
|
+
}
|
|
51
|
+
function sanitizeEmail(value) {
|
|
52
|
+
return value.trim().replace(/[^A-Za-z0-9.!#$%&'*+/=?^_`{|}~@-]/g, "");
|
|
53
|
+
}
|
|
54
|
+
function isEmail(value) {
|
|
55
|
+
return /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(value) && value.length >= 6;
|
|
56
|
+
}
|
|
57
|
+
function field(fields, key, max) {
|
|
58
|
+
const value = fields[key] !== void 0 ? sanitizeText(fields[key]) : "";
|
|
59
|
+
return [...value].slice(0, max).join("");
|
|
60
|
+
}
|
|
61
|
+
function cut(value, max) {
|
|
62
|
+
return [...value].slice(0, max).join("");
|
|
63
|
+
}
|
|
64
|
+
function defaultIp(request) {
|
|
65
|
+
const forwarded = request.headers.get("x-forwarded-for");
|
|
66
|
+
if (forwarded) return forwarded.split(",")[0].trim() || null;
|
|
67
|
+
return request.headers.get("x-real-ip") ?? request.headers.get("cf-connecting-ip") ?? null;
|
|
68
|
+
}
|
|
69
|
+
var MemoryStateStore = class {
|
|
70
|
+
items = /* @__PURE__ */ new Map();
|
|
71
|
+
async get(key) {
|
|
72
|
+
const item = this.items.get(key);
|
|
73
|
+
if (!item) return null;
|
|
74
|
+
if (item.until < Date.now()) {
|
|
75
|
+
this.items.delete(key);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
return item.value;
|
|
79
|
+
}
|
|
80
|
+
async set(key, value, ttlSeconds) {
|
|
81
|
+
this.items.set(key, { value, until: Date.now() + ttlSeconds * 1e3 });
|
|
82
|
+
}
|
|
83
|
+
async delete(key) {
|
|
84
|
+
this.items.delete(key);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
async function guard(store, name, perHour, ip) {
|
|
88
|
+
if (!store) return;
|
|
89
|
+
const fingerprint = ip ? createHmac("md5", "fleetbridge").update(ip).digest("hex") : "unknown";
|
|
90
|
+
const key = `fleetbridge_${name}_${fingerprint}`;
|
|
91
|
+
const recent = Number(await store.get(key) ?? 0);
|
|
92
|
+
if (recent >= perHour) {
|
|
93
|
+
fail({ message: "Too many requests just now. Please try again shortly." }, 429);
|
|
94
|
+
}
|
|
95
|
+
await store.set(key, String(recent + 1), 3600);
|
|
96
|
+
}
|
|
97
|
+
function paymentToken(secret, bookingId) {
|
|
98
|
+
return `${bookingId}.${createHmac("sha256", secret).update(`fleetbridge-payment|${bookingId}`).digest("hex").slice(0, 32)}`;
|
|
99
|
+
}
|
|
100
|
+
function bookingFromToken(secret, token) {
|
|
101
|
+
const dot = token.indexOf(".");
|
|
102
|
+
if (dot <= 0) return null;
|
|
103
|
+
const id = token.slice(0, dot);
|
|
104
|
+
const expected = Buffer.from(paymentToken(secret, id));
|
|
105
|
+
const given = Buffer.from(token);
|
|
106
|
+
return expected.length === given.length && timingSafeEqual(expected, given) ? id : null;
|
|
107
|
+
}
|
|
108
|
+
function quoteToken() {
|
|
109
|
+
return randomBytes(20).toString("hex");
|
|
110
|
+
}
|
|
111
|
+
function uuid() {
|
|
112
|
+
return randomUUID();
|
|
113
|
+
}
|
|
114
|
+
function offsetAt(timeZone, utcMillis) {
|
|
115
|
+
const parts = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" }).formatToParts(new Date(utcMillis));
|
|
116
|
+
const name = parts.find((part) => part.type === "timeZoneName")?.value ?? "GMT";
|
|
117
|
+
const match = /GMT([+-]\d{1,2})(?::?(\d{2}))?/.exec(name);
|
|
118
|
+
if (!match) return "+00:00";
|
|
119
|
+
const hours = Number(match[1]);
|
|
120
|
+
const sign = hours < 0 || match[1].startsWith("-") ? "-" : "+";
|
|
121
|
+
return `${sign}${String(Math.abs(hours)).padStart(2, "0")}:${match[2] ?? "00"}`;
|
|
122
|
+
}
|
|
123
|
+
function offsetMinutes(offset) {
|
|
124
|
+
const sign = offset.startsWith("-") ? -1 : 1;
|
|
125
|
+
const [h, m] = offset.slice(1).split(":").map(Number);
|
|
126
|
+
return sign * ((h ?? 0) * 60 + (m ?? 0));
|
|
127
|
+
}
|
|
128
|
+
function isoTime(date, time, timeZone) {
|
|
129
|
+
const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date.trim());
|
|
130
|
+
const t = /^(\d{1,2}):(\d{2})$/.exec(time.trim());
|
|
131
|
+
if (!d || !t) throw new MappingError("Please choose a valid date and time");
|
|
132
|
+
const [year, month, day] = [Number(d[1]), Number(d[2]), Number(d[3])];
|
|
133
|
+
const [hour, minute] = [Number(t[1]), Number(t[2])];
|
|
134
|
+
if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) throw new MappingError("Please choose a valid date and time");
|
|
135
|
+
const asUtc = Date.UTC(year, month - 1, day, hour, minute);
|
|
136
|
+
const check = new Date(asUtc);
|
|
137
|
+
if (check.getUTCDate() !== day || check.getUTCMonth() !== month - 1) throw new MappingError("Please choose a valid date and time");
|
|
138
|
+
let offset = offsetAt(timeZone, asUtc);
|
|
139
|
+
offset = offsetAt(timeZone, asUtc - offsetMinutes(offset) * 6e4);
|
|
140
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
141
|
+
return `${year}-${pad(month)}-${pad(day)}T${pad(hour)}:${pad(minute)}:00${offset}`;
|
|
142
|
+
}
|
|
143
|
+
function shownTime(moment, timeZone) {
|
|
144
|
+
if (!moment) return "\u2014";
|
|
145
|
+
const date = new Date(moment);
|
|
146
|
+
if (Number.isNaN(date.getTime())) return "\u2014";
|
|
147
|
+
const parts = Object.fromEntries(
|
|
148
|
+
new Intl.DateTimeFormat("en-GB", { timeZone, weekday: "short", day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(date).map((part) => [part.type, part.value])
|
|
149
|
+
);
|
|
150
|
+
return `${parts.weekday}, ${parts.day} ${parts.month} ${parts.year} ${parts.hour}:${parts.minute}`;
|
|
151
|
+
}
|
|
152
|
+
function toIso(value) {
|
|
153
|
+
if (value === null || value === void 0 || value === "") return null;
|
|
154
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString();
|
|
155
|
+
const text = String(value).trim();
|
|
156
|
+
const naive = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(text);
|
|
157
|
+
const date = new Date(naive ? `${text.replace(" ", "T")}Z` : text);
|
|
158
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
159
|
+
}
|
|
160
|
+
function nowSql() {
|
|
161
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "");
|
|
162
|
+
}
|
|
163
|
+
function toSqlDatetime(date, time) {
|
|
164
|
+
const d = date.trim();
|
|
165
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) return null;
|
|
166
|
+
let t = time.trim();
|
|
167
|
+
if (!/^\d{1,2}:\d{2}$/.test(t)) t = "00:00";
|
|
168
|
+
const [h, m] = t.split(":").map(Number);
|
|
169
|
+
if (h > 23 || m > 59) return null;
|
|
170
|
+
return `${d} ${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:00.000`;
|
|
171
|
+
}
|
|
172
|
+
function splitSqlDatetime(value) {
|
|
173
|
+
const text = value instanceof Date ? value.toISOString() : String(value ?? "").trim();
|
|
174
|
+
const match = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}):(\d{2})/.exec(text);
|
|
175
|
+
return match ? [match[1], `${match[2]}:${match[3]}`] : ["", ""];
|
|
176
|
+
}
|
|
177
|
+
var MappingError = class extends Error {
|
|
178
|
+
};
|
|
179
|
+
function isWebAddress(value) {
|
|
180
|
+
if (typeof value !== "string" || value === "" || !/^https?:\/\//i.test(value)) return false;
|
|
181
|
+
try {
|
|
182
|
+
new URL(value);
|
|
183
|
+
return true;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function cents(rands) {
|
|
189
|
+
return Math.round(Number(rands || 0) * 100);
|
|
190
|
+
}
|
|
191
|
+
function bool(value) {
|
|
192
|
+
return value === true || value === 1 || value === "1" || value === "t" || value === "true";
|
|
193
|
+
}
|
|
194
|
+
function isNumeric(value) {
|
|
195
|
+
return typeof value === "number" ? Number.isFinite(value) : typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value));
|
|
196
|
+
}
|
|
197
|
+
function coreError(error) {
|
|
198
|
+
if (error instanceof Error && error.name === "FleetBridgeError" && typeof error.code === "string") {
|
|
199
|
+
return { code: error.code, status: Number(error.status) || 0, message: error.message };
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
function plain(value) {
|
|
204
|
+
return value === void 0 ? null : JSON.parse(JSON.stringify(value));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/server/request.mapper.ts
|
|
208
|
+
var OWN_FLEET = "own-fleet";
|
|
209
|
+
var MAX_EXTRAS = 20;
|
|
210
|
+
function trip(fields, timeZone) {
|
|
211
|
+
const out = {
|
|
212
|
+
pickupLocation: fields.pickupLocation,
|
|
213
|
+
returnLocation: fields.returnLocation !== "" ? fields.returnLocation : fields.pickupLocation,
|
|
214
|
+
pickupAt: isoTime(fields.pickupDate, fields.pickupTime, timeZone),
|
|
215
|
+
returnAt: isoTime(fields.returnDate, fields.returnTime, timeZone),
|
|
216
|
+
timeZone,
|
|
217
|
+
isInternational: !!fields.isInternational
|
|
218
|
+
};
|
|
219
|
+
if (fields.promoCode) out.promoCode = fields.promoCode;
|
|
220
|
+
const age = Number(fields.driverAge);
|
|
221
|
+
if (fields.driverAge && Number.isInteger(age) && age >= 16 && age <= 99) out.driverAge = age;
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
function bookingForm(post) {
|
|
225
|
+
const text = (key, max = 200) => cut(post[key] !== void 0 ? sanitizeText(String(post[key])) : "", max);
|
|
226
|
+
const number = (key) => post[key] !== void 0 && isNumeric(post[key]) ? Number(post[key]) : 0;
|
|
227
|
+
const email = (key) => post[key] !== void 0 ? sanitizeEmail(String(post[key])) : "";
|
|
228
|
+
const returnUrl = post.returnUrl !== void 0 ? String(post.returnUrl).trim() : "";
|
|
229
|
+
return {
|
|
230
|
+
identifier: text("identifier", 40),
|
|
231
|
+
pickup_code: text("pickupCode", 40),
|
|
232
|
+
dropoff_code: text("dropoffCode", 40),
|
|
233
|
+
vehicle_group: text("vehicleGroup", 40),
|
|
234
|
+
rate_id: text("rateId", 60),
|
|
235
|
+
quote_ref: text("quoteRef", 60),
|
|
236
|
+
cdp_code: text("cdpCode", 40),
|
|
237
|
+
payment_method_id: text("paymentMethodId", 64),
|
|
238
|
+
payment_purpose: text("paymentPurpose", 10) === "DEPOSIT" ? "DEPOSIT" : "FULL",
|
|
239
|
+
return_url: returnUrl.startsWith("/") || isWebAddress(returnUrl) ? returnUrl : "",
|
|
240
|
+
car_label: text("carLabel"),
|
|
241
|
+
supplier: text("supplier", 120),
|
|
242
|
+
car_image: text("carImage", 191),
|
|
243
|
+
supplier_logo: text("supplierLogo", 191),
|
|
244
|
+
seats: Math.trunc(number("seats")),
|
|
245
|
+
doors: Math.trunc(number("doors")),
|
|
246
|
+
transmission: text("transmission", 40),
|
|
247
|
+
fuel_type: text("fuelType", 40),
|
|
248
|
+
insurance_included: text("insuranceIncluded", 1) === "1",
|
|
249
|
+
unlimited_mileage: text("unlimitedMileage", 1) === "1",
|
|
250
|
+
km_per_day: Math.trunc(number("kmPerDay")),
|
|
251
|
+
daily_rate: number("dailyRate"),
|
|
252
|
+
currency: text("currency", 8).toUpperCase(),
|
|
253
|
+
days: Math.trunc(number("days")),
|
|
254
|
+
estimated_total: number("estimatedTotal"),
|
|
255
|
+
vehicle_amount: number("vehicleAmount"),
|
|
256
|
+
deposit: number("deposit"),
|
|
257
|
+
drop_off_fee: number("dropOffFee"),
|
|
258
|
+
rate_package_label: text("ratePackageLabel", 40),
|
|
259
|
+
terms_id: text("termsId", 64),
|
|
260
|
+
terms_version: Math.trunc(number("termsVersion")),
|
|
261
|
+
pickup_location: text("pickupLocation", 191),
|
|
262
|
+
dropoff_location: text("dropoffLocation", 191),
|
|
263
|
+
pickup_date: text("pickupDate", 10),
|
|
264
|
+
pickup_time: text("pickupTime", 5),
|
|
265
|
+
return_date: text("returnDate", 10),
|
|
266
|
+
return_time: text("returnTime", 5),
|
|
267
|
+
coupon: text("coupon", 40),
|
|
268
|
+
is_international: text("residency", 4) === "INT",
|
|
269
|
+
extras: extrasFromJson(post.extras ?? ""),
|
|
270
|
+
title: text("title", 20),
|
|
271
|
+
first_name: text("firstName", 80),
|
|
272
|
+
last_name: text("lastName", 80),
|
|
273
|
+
email: email("email"),
|
|
274
|
+
phone: text("phone", 40),
|
|
275
|
+
licence_number: text("licenceNumber", 60),
|
|
276
|
+
country: text("country", 80),
|
|
277
|
+
country_code: text("countryCode", 2).toUpperCase(),
|
|
278
|
+
dial_code: text("dialCode", 8),
|
|
279
|
+
id_number: text("idNumber", 40),
|
|
280
|
+
crossing_border: text("crossingBorder", 1) === "1",
|
|
281
|
+
street_address: text("streetAddress", 200),
|
|
282
|
+
city: text("city", 80),
|
|
283
|
+
suburb: text("suburb", 80),
|
|
284
|
+
province: text("province", 80),
|
|
285
|
+
postal_code: text("postalCode", 20),
|
|
286
|
+
additional_email: email("additionalEmail"),
|
|
287
|
+
notes: post.notes !== void 0 ? cut(sanitizeTextarea(String(post.notes)), 500) : ""
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
function extrasFromJson(raw) {
|
|
291
|
+
let decoded = null;
|
|
292
|
+
if (typeof raw === "string" && raw !== "") {
|
|
293
|
+
try {
|
|
294
|
+
decoded = JSON.parse(raw);
|
|
295
|
+
} catch {
|
|
296
|
+
decoded = null;
|
|
297
|
+
}
|
|
298
|
+
} else if (Array.isArray(raw)) {
|
|
299
|
+
decoded = raw;
|
|
300
|
+
}
|
|
301
|
+
if (!decoded || typeof decoded !== "object") return [];
|
|
302
|
+
const list2 = Array.isArray(decoded) ? decoded : Object.values(decoded);
|
|
303
|
+
const clean = [];
|
|
304
|
+
for (const entry of list2.slice(0, MAX_EXTRAS)) {
|
|
305
|
+
if (!entry || typeof entry !== "object" || !("code" in entry)) continue;
|
|
306
|
+
const item = entry;
|
|
307
|
+
const code = String(item.code).replace(/[^A-Za-z0-9_]/g, "").toUpperCase().slice(0, 40);
|
|
308
|
+
if (code === "") continue;
|
|
309
|
+
const quantity = Math.trunc(Number(item.quantity ?? 1)) || 0;
|
|
310
|
+
clean.push({
|
|
311
|
+
code,
|
|
312
|
+
name: item.name !== void 0 ? cut(sanitizeText(String(item.name)), 191) : "",
|
|
313
|
+
quantity: Math.max(1, Math.min(10, quantity)),
|
|
314
|
+
unitPrice: isNumeric(item.unitPrice) ? Number(item.unitPrice) : 0
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
return clean;
|
|
318
|
+
}
|
|
319
|
+
function searchAnswer(data, ownFleetName) {
|
|
320
|
+
const offers = [];
|
|
321
|
+
for (const supplier of data?.suppliers ?? []) {
|
|
322
|
+
const listings = supplier.listings && typeof supplier.listings === "object" ? JSON.parse(JSON.stringify(supplier.listings)) : {};
|
|
323
|
+
offers.push({ supplier: supplier.supplierName, discountCodes: Array.isArray(supplier.discountCodes) ? supplier.discountCodes : [], ...listings });
|
|
324
|
+
}
|
|
325
|
+
const own = JSON.parse(JSON.stringify(data?.ownFleet ?? []));
|
|
326
|
+
if (own.length > 0) offers.push(ownFleetOffer(own, ownFleetName));
|
|
327
|
+
return { offers, sources: JSON.parse(JSON.stringify(data?.sources ?? [])) };
|
|
328
|
+
}
|
|
329
|
+
function ownFleetOffer(classes, name) {
|
|
330
|
+
const fromCore = typeof classes[0]?.supplierName === "string" ? classes[0].supplierName.trim() : "";
|
|
331
|
+
const logo = typeof classes[0]?.supplierLogo === "string" ? classes[0].supplierLogo.trim() : "";
|
|
332
|
+
const supplier = { id: OWN_FLEET, name: fromCore !== "" ? fromCore : name };
|
|
333
|
+
if (logo !== "") supplier.logoUrl = logo;
|
|
334
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
335
|
+
for (const item of classes) {
|
|
336
|
+
const key = String(item.classId ?? "");
|
|
337
|
+
grouped.set(key, [...grouped.get(key) ?? [], item]);
|
|
338
|
+
}
|
|
339
|
+
const fleets = [];
|
|
340
|
+
const discountCodes = [];
|
|
341
|
+
for (const variants of grouped.values()) {
|
|
342
|
+
variants.sort((a, b) => Math.trunc(a.price?.total?.amount ?? 0) - Math.trunc(b.price?.total?.amount ?? 0));
|
|
343
|
+
const first = variants[0];
|
|
344
|
+
const categories = (first.categories ?? []).map((c) => String(c).trim()).filter(Boolean);
|
|
345
|
+
const rates = [];
|
|
346
|
+
for (const variant of variants) {
|
|
347
|
+
const rate = ownFleetRate(variant);
|
|
348
|
+
rates.push(rate);
|
|
349
|
+
if (rate.cdpCode && Number(rate.discount ?? 0) > 0) discountCodes.push(rate.cdpCode);
|
|
350
|
+
}
|
|
351
|
+
fleets.push({
|
|
352
|
+
code: String(first.classCode ?? ""),
|
|
353
|
+
carGroup: String(first.classCode ?? ""),
|
|
354
|
+
model: String(first.name ?? ""),
|
|
355
|
+
seat: Math.trunc(Number(first.seats ?? 0)),
|
|
356
|
+
door: Math.trunc(Number(first.doors ?? 0)),
|
|
357
|
+
luggage: first.bags !== void 0 && first.bags !== null ? Math.trunc(Number(first.bags)) : null,
|
|
358
|
+
carImage: String(first.images?.[0] ?? ""),
|
|
359
|
+
transmission: String(first.transmission ?? ""),
|
|
360
|
+
fuel: String(first.fuelType ?? ""),
|
|
361
|
+
category: categories.length === 1 ? categories[0] : "",
|
|
362
|
+
categories,
|
|
363
|
+
supplier,
|
|
364
|
+
pickUpBranch: String(first.pickupBranch ?? ""),
|
|
365
|
+
returnBranch: String(first.returnBranch ?? ""),
|
|
366
|
+
rates
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
return { supplier, available: true, discountCodes: [...new Set(discountCodes)], fleets };
|
|
370
|
+
}
|
|
371
|
+
function ownFleetRate(item) {
|
|
372
|
+
const total = Math.trunc(Number(item.price?.total?.amount ?? 0)) / 100;
|
|
373
|
+
const days = Math.max(1, Math.trunc(Number(item.days ?? 1)));
|
|
374
|
+
const deposit = Math.trunc(Number(item.standardCover?.depositCents ?? 0)) / 100;
|
|
375
|
+
const excess = Math.trunc(Number(item.standardCover?.excessCents ?? 0)) / 100;
|
|
376
|
+
const superTotal = item.superCover?.total?.amount !== void 0 ? Math.trunc(Number(item.superCover.total.amount)) / 100 : null;
|
|
377
|
+
let off = 0;
|
|
378
|
+
const percent = item.promotionPercent !== void 0 ? Number(item.promotionPercent) : 0;
|
|
379
|
+
if (percent > 0) {
|
|
380
|
+
off = total * (percent / 100);
|
|
381
|
+
} else {
|
|
382
|
+
for (const line of item.price?.lines ?? []) {
|
|
383
|
+
if (String(line.code ?? "").startsWith("discount.coupon.")) off += Math.abs(Math.trunc(Number(line.amount?.amount ?? 0))) / 100;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const cdp = typeof item.cdpCode === "string" ? item.cdpCode.trim() : "";
|
|
387
|
+
const rate = {
|
|
388
|
+
standardRate: total,
|
|
389
|
+
dailyRate: total / days,
|
|
390
|
+
rentalDays: days,
|
|
391
|
+
unlimitedMileage: !!item.mileage?.unlimited,
|
|
392
|
+
kmPerDay: Math.trunc(Number(item.mileage?.kmPerDay ?? 0)),
|
|
393
|
+
rateNo: String(item.classId ?? ""),
|
|
394
|
+
rateSrNo: String(item.ratePlanId ?? ""),
|
|
395
|
+
cdpCode: cdp,
|
|
396
|
+
discount: off,
|
|
397
|
+
kmSelectable: item.kmSelectable === void 0 || item.kmSelectable !== false,
|
|
398
|
+
cdpKmAllowance: item.cdpKmAllowance !== void 0 && item.cdpKmAllowance !== null ? Math.trunc(Number(item.cdpKmAllowance)) : null,
|
|
399
|
+
superDeposit: deposit,
|
|
400
|
+
liability: excess,
|
|
401
|
+
standardExcessRatePerKm: Math.trunc(Number(item.standardCover?.excessPerKmCents ?? 0)) / 100
|
|
402
|
+
};
|
|
403
|
+
if (superTotal !== null) {
|
|
404
|
+
rate.superRate = superTotal;
|
|
405
|
+
rate.superExcess = Math.trunc(Number(item.superCover?.excessCents ?? 0)) / 100;
|
|
406
|
+
rate.superCoverDeposit = Math.trunc(Number(item.superCover?.depositCents ?? 0)) / 100;
|
|
407
|
+
rate.superExcessRatePerKm = Math.trunc(Number(item.superCover?.excessPerKmCents ?? 0)) / 100;
|
|
408
|
+
}
|
|
409
|
+
return rate;
|
|
410
|
+
}
|
|
411
|
+
function bookingInput(request, supplierId, credentials, timeZone, notification2 = null) {
|
|
412
|
+
const input = {
|
|
413
|
+
trip: bookingTrip(request, timeZone),
|
|
414
|
+
source: source(request, supplierId, credentials),
|
|
415
|
+
customer: customer(request),
|
|
416
|
+
extras: extras(request),
|
|
417
|
+
crossBorder: !!request.crossing_border,
|
|
418
|
+
notes: notes(request)
|
|
419
|
+
};
|
|
420
|
+
if (notification2) input.notification = notification2;
|
|
421
|
+
if (request.terms_id !== "" && request.terms_version > 0) input.terms = { id: request.terms_id, version: request.terms_version };
|
|
422
|
+
return input;
|
|
423
|
+
}
|
|
424
|
+
function amendInput(request, booking, bookingId, supplierId, credentials, timeZone, notification2 = null) {
|
|
425
|
+
return { booking, bookingId: String(bookingId), ...bookingInput(request, supplierId, credentials, timeZone, notification2) };
|
|
426
|
+
}
|
|
427
|
+
function bookingTrip(request, timeZone) {
|
|
428
|
+
return trip(
|
|
429
|
+
{
|
|
430
|
+
pickupLocation: request.pickup_location,
|
|
431
|
+
returnLocation: request.dropoff_location,
|
|
432
|
+
pickupDate: request.pickup_date,
|
|
433
|
+
pickupTime: request.pickup_time,
|
|
434
|
+
returnDate: request.return_date,
|
|
435
|
+
returnTime: request.return_time,
|
|
436
|
+
promoCode: request.coupon,
|
|
437
|
+
isInternational: request.is_international
|
|
438
|
+
},
|
|
439
|
+
timeZone
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
function source(request, supplierId, credentials) {
|
|
443
|
+
if (request.identifier === OWN_FLEET) {
|
|
444
|
+
const cover = /super/i.test(request.rate_package_label) ? "super" : "standard";
|
|
445
|
+
const out2 = { kind: "ownFleet", classId: String(request.rate_id), cover };
|
|
446
|
+
if (request.quote_ref) out2.ratePlanId = String(request.quote_ref);
|
|
447
|
+
return out2;
|
|
448
|
+
}
|
|
449
|
+
const vehicle = {};
|
|
450
|
+
const candidates = {
|
|
451
|
+
name: request.car_label,
|
|
452
|
+
image: request.car_image,
|
|
453
|
+
seats: request.seats || null,
|
|
454
|
+
doors: request.doors || null,
|
|
455
|
+
transmission: request.transmission,
|
|
456
|
+
fuelType: request.fuel_type
|
|
457
|
+
};
|
|
458
|
+
for (const [key, value] of Object.entries(candidates)) if (value !== null && value !== "") vehicle[key] = value;
|
|
459
|
+
const out = {
|
|
460
|
+
kind: "supplier",
|
|
461
|
+
supplierId: String(supplierId),
|
|
462
|
+
pickupLocation: request.pickup_code,
|
|
463
|
+
returnLocation: request.dropoff_code !== "" ? request.dropoff_code : request.pickup_code,
|
|
464
|
+
credentials: { ...credentials ?? {} },
|
|
465
|
+
vehicleGroup: request.vehicle_group,
|
|
466
|
+
quotedTotalCents: cents(request.estimated_total),
|
|
467
|
+
currency: request.currency !== "" ? request.currency : "ZAR",
|
|
468
|
+
vehicle,
|
|
469
|
+
insuranceIncluded: !!request.insurance_included
|
|
470
|
+
};
|
|
471
|
+
const optional = [
|
|
472
|
+
["rate_id", "rateId"],
|
|
473
|
+
["quote_ref", "quoteRef"],
|
|
474
|
+
["cdp_code", "cdpCode"],
|
|
475
|
+
["supplier_logo", "supplierLogo"],
|
|
476
|
+
["rate_package_label", "ratePackageLabel"]
|
|
477
|
+
];
|
|
478
|
+
for (const [from, to] of optional) if (request[from]) out[to] = request[from];
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
481
|
+
function customer(request) {
|
|
482
|
+
const all = {
|
|
483
|
+
title: request.title !== "" ? request.title : "Mr",
|
|
484
|
+
firstName: request.first_name,
|
|
485
|
+
lastName: request.last_name,
|
|
486
|
+
email: request.email,
|
|
487
|
+
phone: request.phone,
|
|
488
|
+
idNumber: request.id_number,
|
|
489
|
+
idType: request.is_international ? "PASSPORT" : "ID",
|
|
490
|
+
countryCode: request.country_code,
|
|
491
|
+
dialCode: request.dial_code,
|
|
492
|
+
streetAddress: request.street_address,
|
|
493
|
+
suburb: request.suburb,
|
|
494
|
+
city: request.city,
|
|
495
|
+
province: request.province,
|
|
496
|
+
country: request.country,
|
|
497
|
+
postalCode: request.postal_code
|
|
498
|
+
};
|
|
499
|
+
return Object.fromEntries(Object.entries(all).filter(([, value]) => value !== ""));
|
|
500
|
+
}
|
|
501
|
+
function extras(request) {
|
|
502
|
+
return request.extras.map((extra) => ({
|
|
503
|
+
code: String(extra.code),
|
|
504
|
+
name: String(extra.name !== "" ? extra.name : extra.code),
|
|
505
|
+
quantity: Math.max(1, Math.trunc(extra.quantity)),
|
|
506
|
+
unitPriceCents: cents(extra.unitPrice)
|
|
507
|
+
}));
|
|
508
|
+
}
|
|
509
|
+
function notes(request) {
|
|
510
|
+
return [request.notes, request.additional_email ? `ADDITIONAL EMAIL: ${request.additional_email}` : "", request.coupon ? `COUPON: ${request.coupon}` : ""].filter(Boolean).join(" | ");
|
|
511
|
+
}
|
|
512
|
+
function notification(request, supplierName, timeZone) {
|
|
513
|
+
const out = {
|
|
514
|
+
customerEmail: request.email,
|
|
515
|
+
customerName: `${request.first_name} ${request.last_name}`.trim() || request.email,
|
|
516
|
+
supplierName,
|
|
517
|
+
vehicleName: request.car_label !== "" ? request.car_label : "Vehicle",
|
|
518
|
+
pickupDate: isoTime(request.pickup_date, request.pickup_time, timeZone),
|
|
519
|
+
dropoffDate: isoTime(request.return_date, request.return_time, timeZone),
|
|
520
|
+
totalPrice: cents(request.estimated_total),
|
|
521
|
+
currency: request.currency !== "" ? request.currency : "ZAR",
|
|
522
|
+
priceBreakdown: priceLines(request)
|
|
523
|
+
};
|
|
524
|
+
const optional = {
|
|
525
|
+
vehicleGroup: request.vehicle_group,
|
|
526
|
+
vehicleSeats: request.seats || null,
|
|
527
|
+
vehicleDoors: request.doors || null,
|
|
528
|
+
vehicleTransmission: request.transmission,
|
|
529
|
+
vehicleFuelType: request.fuel_type,
|
|
530
|
+
pickupBranchName: request.pickup_location,
|
|
531
|
+
dropoffBranchName: request.dropoff_location,
|
|
532
|
+
rentalDays: request.days || null,
|
|
533
|
+
ratePackageLabel: request.rate_package_label,
|
|
534
|
+
depositAmount: request.deposit > 0 ? cents(request.deposit) : null
|
|
535
|
+
};
|
|
536
|
+
for (const [key, value] of Object.entries(optional)) if (value !== null && value !== "") out[key] = value;
|
|
537
|
+
if (request.unlimited_mileage) out.unlimitedMileage = true;
|
|
538
|
+
else if (request.km_per_day > 0) out.kmPerDay = Math.trunc(request.km_per_day);
|
|
539
|
+
if (isWebAddress(request.car_image)) out.vehicleImage = request.car_image;
|
|
540
|
+
if (isWebAddress(request.supplier_logo)) out.supplierLogo = request.supplier_logo;
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
function priceLines(request) {
|
|
544
|
+
const lines = [];
|
|
545
|
+
if (request.vehicle_amount > 0) lines.push({ label: request.car_label !== "" ? request.car_label : "Vehicle", amount: cents(request.vehicle_amount) });
|
|
546
|
+
for (const extra of request.extras) {
|
|
547
|
+
const amount = Number(extra.unitPrice) * Math.trunc(extra.quantity);
|
|
548
|
+
if (amount > 0) lines.push({ label: extra.name !== "" ? extra.name : extra.code, amount: cents(amount) });
|
|
549
|
+
}
|
|
550
|
+
if (request.drop_off_fee > 0) lines.push({ label: "One-way drop-off", amount: cents(request.drop_off_fee) });
|
|
551
|
+
return lines;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// src/server/tenant.ts
|
|
555
|
+
var MAX_VARCHAR = 191;
|
|
556
|
+
var ONLINE_KINDS = ["PAYSTACK", "STITCH", "PAYFAST"];
|
|
557
|
+
function missing(error) {
|
|
558
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
559
|
+
return /doesn't exist|does not exist|no such table|no such column|unknown column|undefined column|undefined table/i.test(text);
|
|
560
|
+
}
|
|
561
|
+
function truncate(value, max = MAX_VARCHAR) {
|
|
562
|
+
const text = value === null || value === void 0 ? "" : String(value);
|
|
563
|
+
return text === "" ? null : cut(text, max);
|
|
564
|
+
}
|
|
565
|
+
function decodeJson(value) {
|
|
566
|
+
if (value === null || value === void 0 || value === "") return {};
|
|
567
|
+
if (typeof value === "object") return value;
|
|
568
|
+
try {
|
|
569
|
+
const decoded = JSON.parse(String(value));
|
|
570
|
+
return decoded && typeof decoded === "object" ? decoded : {};
|
|
571
|
+
} catch {
|
|
572
|
+
return {};
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
function list(value) {
|
|
576
|
+
const decoded = decodeJson(value);
|
|
577
|
+
return Array.isArray(decoded) ? decoded : Object.values(decoded);
|
|
578
|
+
}
|
|
579
|
+
var Tenant = class {
|
|
580
|
+
constructor(storage, siteUrl, manageBookingPath) {
|
|
581
|
+
this.storage = storage;
|
|
582
|
+
this.siteUrl = siteUrl;
|
|
583
|
+
this.manageBookingPath = manageBookingPath;
|
|
584
|
+
}
|
|
585
|
+
/** Quotes a table or column name for this database. */
|
|
586
|
+
q(name) {
|
|
587
|
+
return this.storage ? this.storage.dialect.quote(name) : name;
|
|
588
|
+
}
|
|
589
|
+
/** Builds SQL from a template where {Name} is a quoted identifier. */
|
|
590
|
+
sql(template) {
|
|
591
|
+
return template.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => this.q(name));
|
|
592
|
+
}
|
|
593
|
+
async rows(template, params = []) {
|
|
594
|
+
if (!this.storage) return [];
|
|
595
|
+
try {
|
|
596
|
+
return await this.storage.query(this.sql(template), params);
|
|
597
|
+
} catch (error) {
|
|
598
|
+
if (missing(error)) return [];
|
|
599
|
+
throw error;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
async exec(template, params = []) {
|
|
603
|
+
if (!this.storage) return 0;
|
|
604
|
+
return this.storage.exec(this.sql(template), params);
|
|
605
|
+
}
|
|
606
|
+
placeholders(count) {
|
|
607
|
+
return Array.from({ length: count }, () => "?").join(", ");
|
|
608
|
+
}
|
|
609
|
+
// ─── Branches ──────────────────────────────────────────────────────────────
|
|
610
|
+
/** Every place name once, for the search pickers (SearchController::ajax_public_branches). */
|
|
611
|
+
async pickerLocations() {
|
|
612
|
+
const rows = await this.rows(
|
|
613
|
+
"SELECT {name}, {groupingName}, {countryCode}, {isAirportBranch}, {isInternational} FROM {Branches} WHERE {isArchived} = ? ORDER BY {groupingName} ASC, {name} ASC",
|
|
614
|
+
[false]
|
|
615
|
+
);
|
|
616
|
+
const byName = /* @__PURE__ */ new Map();
|
|
617
|
+
for (const row of rows) {
|
|
618
|
+
const name = String(row.name ?? "");
|
|
619
|
+
const existing = byName.get(name);
|
|
620
|
+
if (!existing) {
|
|
621
|
+
byName.set(name, {
|
|
622
|
+
name,
|
|
623
|
+
region: String(row.groupingName || row.countryCode || ""),
|
|
624
|
+
isAirportBranch: bool(row.isAirportBranch),
|
|
625
|
+
isInternational: bool(row.isInternational)
|
|
626
|
+
});
|
|
627
|
+
} else if (bool(row.isAirportBranch)) {
|
|
628
|
+
existing.isAirportBranch = true;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
return [...byName.values()];
|
|
632
|
+
}
|
|
633
|
+
async codeForName(identifier, name) {
|
|
634
|
+
const trimmed = name.trim();
|
|
635
|
+
if (trimmed === "") return null;
|
|
636
|
+
const rows = await this.rows("SELECT {code} FROM {Branches} WHERE {supplierId} = ? AND {name} = ? AND {isArchived} = ? LIMIT 1", [identifier, trimmed, false]);
|
|
637
|
+
return rows[0]?.code ? String(rows[0].code) : null;
|
|
638
|
+
}
|
|
639
|
+
async branchIdFor(identifier, code) {
|
|
640
|
+
let rows = await this.rows("SELECT {id} FROM {Branches} WHERE {supplierId} = ? AND {code} = ? AND {isArchived} = ? LIMIT 1", [identifier, code, false]);
|
|
641
|
+
if (!rows[0] && identifier === "thrifty") {
|
|
642
|
+
rows = await this.rows("SELECT {id} FROM {Branches} WHERE {supplierId} = ? AND {code} = ? AND {isArchived} = ? LIMIT 1", ["hertz", code, false]);
|
|
643
|
+
}
|
|
644
|
+
return rows[0]?.id ? String(rows[0].id) : null;
|
|
645
|
+
}
|
|
646
|
+
async branchCodeById(branchId) {
|
|
647
|
+
if (!branchId) return null;
|
|
648
|
+
const rows = await this.rows("SELECT {code} FROM {Branches} WHERE {id} = ? LIMIT 1", [String(branchId)]);
|
|
649
|
+
return rows[0]?.code ? String(rows[0].code) : null;
|
|
650
|
+
}
|
|
651
|
+
async branchNames(ids) {
|
|
652
|
+
const unique = [...new Set(ids.filter(Boolean).map(String))];
|
|
653
|
+
if (unique.length === 0) return {};
|
|
654
|
+
const rows = await this.rows(`SELECT {id}, {name} FROM {Branches} WHERE {id} IN (${this.placeholders(unique.length)})`, unique);
|
|
655
|
+
return Object.fromEntries(rows.map((row) => [String(row.id), String(row.name)]));
|
|
656
|
+
}
|
|
657
|
+
// ─── Extras ────────────────────────────────────────────────────────────────
|
|
658
|
+
/** What a renter could add to this supplier's booking now (Extra::available_for). */
|
|
659
|
+
async extrasFor(identifier, categories = "") {
|
|
660
|
+
const wanted = [...new Set(categories.split(",").map((c) => c.trim()).filter(Boolean))];
|
|
661
|
+
const rows = await this.rows("SELECT * FROM {Extras} WHERE {supplierId} = ? AND {isArchived} = ? AND {isAvailable} = ? ORDER BY {name} ASC", [identifier, false, true]);
|
|
662
|
+
if (wanted.length === 0) return rows;
|
|
663
|
+
return rows.filter((row) => {
|
|
664
|
+
const category = typeof row.category === "string" ? row.category.trim() : "";
|
|
665
|
+
return category === "" || wanted.includes(category);
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
// ─── Payment methods ───────────────────────────────────────────────────────
|
|
669
|
+
/** The ways to pay at an own-fleet branch (PaymentMethods::for_branch). Never reads credentials. */
|
|
670
|
+
async paymentMethodsFor(branchCode) {
|
|
671
|
+
const select = (logo) => `SELECT m.{id}, m.{name}, m.{kind}, m.{instructions}, m.{usableForDeposit}${logo ? ", m.{logo}" : ""}
|
|
672
|
+
FROM {FleetPaymentMethods} m
|
|
673
|
+
LEFT JOIN {Branches} b ON b.{id} = m.{branchId}
|
|
674
|
+
WHERE m.{isActive} = ?
|
|
675
|
+
AND m.{deletedAt} IS NULL
|
|
676
|
+
AND (m.{branchId} IS NULL OR (b.{supplierId} = ? AND b.{code} = ?))
|
|
677
|
+
ORDER BY m.{displayOrder} ASC, m.{name} ASC`;
|
|
678
|
+
const params = [true, OWN_FLEET, branchCode];
|
|
679
|
+
let rows;
|
|
680
|
+
try {
|
|
681
|
+
rows = this.storage ? await this.storage.query(this.sql(select(true)), params) : [];
|
|
682
|
+
} catch (error) {
|
|
683
|
+
if (!missing(error)) throw error;
|
|
684
|
+
rows = await this.rows(select(false), params);
|
|
685
|
+
}
|
|
686
|
+
return rows.map((row) => {
|
|
687
|
+
const kind = String(row.kind ?? "");
|
|
688
|
+
const logos = list(row.logo);
|
|
689
|
+
const url = logos[0] !== void 0 ? String(logos[0]) : "";
|
|
690
|
+
return {
|
|
691
|
+
id: String(row.id),
|
|
692
|
+
name: String(row.name ?? ""),
|
|
693
|
+
kind,
|
|
694
|
+
instructions: String(row.instructions ?? ""),
|
|
695
|
+
usableForDeposit: bool(row.usableForDeposit),
|
|
696
|
+
online: ONLINE_KINDS.includes(kind),
|
|
697
|
+
logoUrl: isWebAddress(url) ? url : ""
|
|
698
|
+
};
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
// ─── Bookings ──────────────────────────────────────────────────────────────
|
|
702
|
+
async booking(id) {
|
|
703
|
+
const rows = await this.rows("SELECT * FROM {Bookings} WHERE {id} = ? LIMIT 1", [id]);
|
|
704
|
+
return rows[0] ? this.formatBooking(rows[0]) : null;
|
|
705
|
+
}
|
|
706
|
+
/** The booking for a number and PIN; "GBPCMB" and "OF-GBPCMB" are the same booking. */
|
|
707
|
+
async bookingByNumberAndPin(reservation, pin) {
|
|
708
|
+
const number = reservation.trim().replace(/^[\s.]+|[\s.]+$/g, "");
|
|
709
|
+
const upperPin = pin.trim().toUpperCase();
|
|
710
|
+
if (number === "" || upperPin === "") return null;
|
|
711
|
+
const upper = number.toUpperCase();
|
|
712
|
+
let numbers;
|
|
713
|
+
const prefixed = /^OF-([A-HJ-NP-Z2-9]{6})$/.exec(upper);
|
|
714
|
+
if (prefixed) numbers = [number, prefixed[1], `OF-${prefixed[1]}`];
|
|
715
|
+
else if (/^[A-HJ-NP-Z2-9]{6}$/.test(upper)) numbers = [number, upper, `OF-${upper}`];
|
|
716
|
+
else numbers = [number];
|
|
717
|
+
numbers = [...new Set(numbers)];
|
|
718
|
+
const marks = this.placeholders(numbers.length);
|
|
719
|
+
const rows = await this.rows(
|
|
720
|
+
`SELECT * FROM {Bookings} WHERE ({supplierRef} IN (${marks}) OR {bookingRef} IN (${marks})) AND {bookingPin} = ? LIMIT 1`,
|
|
721
|
+
[...numbers, ...numbers, upperPin]
|
|
722
|
+
);
|
|
723
|
+
return rows[0] ? this.formatBooking(rows[0]) : null;
|
|
724
|
+
}
|
|
725
|
+
async formatBooking(row) {
|
|
726
|
+
const id = String(row.id);
|
|
727
|
+
const [extraRows, rateRows, names] = await Promise.all([
|
|
728
|
+
this.rows("SELECT {bookingId}, {code}, {name}, {quantity}, {unitPrice}, {currency} FROM {BookingExtras} WHERE {bookingId} = ? ORDER BY {createdAt} ASC", [id]),
|
|
729
|
+
this.rows(
|
|
730
|
+
"SELECT {bookingId}, {customerId}, {amount}, {dailyRate}, {days}, {ratePackageLabel}, {extrasTotal}, {dropOffFee}, {deposit}, {total}, {currency} FROM {BookingRates} WHERE {bookingId} = ?",
|
|
731
|
+
[id]
|
|
732
|
+
),
|
|
733
|
+
this.branchNames([row.pickupBranchId, row.dropoffBranchId])
|
|
734
|
+
]);
|
|
735
|
+
const rateRow = rateRows[0];
|
|
736
|
+
const rate = rateRow ? {
|
|
737
|
+
customerId: rateRow.customerId,
|
|
738
|
+
amount: Number(rateRow.amount) / 100,
|
|
739
|
+
dailyRate: Number(rateRow.dailyRate) / 100,
|
|
740
|
+
days: Math.trunc(Number(rateRow.days)),
|
|
741
|
+
ratePackageLabel: rateRow.ratePackageLabel,
|
|
742
|
+
extrasTotal: Number(rateRow.extrasTotal) / 100,
|
|
743
|
+
dropOffFee: rateRow.dropOffFee !== null && rateRow.dropOffFee !== void 0 ? Number(rateRow.dropOffFee) / 100 : null,
|
|
744
|
+
deposit: rateRow.deposit !== null && rateRow.deposit !== void 0 ? Number(rateRow.deposit) / 100 : null,
|
|
745
|
+
total: Number(rateRow.total) / 100,
|
|
746
|
+
currency: rateRow.currency
|
|
747
|
+
} : null;
|
|
748
|
+
const meta = decodeJson(row.metadata);
|
|
749
|
+
const request = meta.request && typeof meta.request === "object" ? meta.request : {};
|
|
750
|
+
const unlimited = "unlimitedMileage" in meta ? !!meta.unlimitedMileage : !!request.unlimited_mileage;
|
|
751
|
+
const kmPerDay = "kmPerDay" in meta ? Math.trunc(Number(meta.kmPerDay)) : Math.trunc(Number(request.km_per_day ?? 0));
|
|
752
|
+
const n = (value) => value !== null && value !== void 0 ? Math.trunc(Number(value)) : null;
|
|
753
|
+
return {
|
|
754
|
+
id,
|
|
755
|
+
bookingRef: row.bookingRef ?? null,
|
|
756
|
+
bookingPin: row.bookingPin ?? null,
|
|
757
|
+
supplierRef: row.supplierRef ?? null,
|
|
758
|
+
status: row.status ?? null,
|
|
759
|
+
supplierStatus: row.supplierStatus ?? null,
|
|
760
|
+
failureReason: row.failureReason ?? null,
|
|
761
|
+
supplierId: row.supplierId ?? null,
|
|
762
|
+
supplierIdentifier: row.supplierIdentifier ?? null,
|
|
763
|
+
supplierName: row.supplierName ?? null,
|
|
764
|
+
customerId: row.customerId ?? null,
|
|
765
|
+
vehicle: {
|
|
766
|
+
group: row.vehicleGroup ?? null,
|
|
767
|
+
name: row.vehicleName ?? null,
|
|
768
|
+
image: row.vehicleImage ?? null,
|
|
769
|
+
supplierLogo: row.supplierLogo ?? null,
|
|
770
|
+
seats: n(row.vehicleSeats),
|
|
771
|
+
doors: n(row.vehicleDoors),
|
|
772
|
+
transmission: row.vehicleTransmission ?? null,
|
|
773
|
+
fuelType: row.vehicleFuelType ?? null,
|
|
774
|
+
insuranceIncluded: row.insuranceIncluded !== null && row.insuranceIncluded !== void 0 ? bool(row.insuranceIncluded) : null,
|
|
775
|
+
ratePackageLabel: row.ratePackageLabel ?? null,
|
|
776
|
+
unlimitedMileage: unlimited,
|
|
777
|
+
kmPerDay: kmPerDay > 0 ? kmPerDay : null
|
|
778
|
+
},
|
|
779
|
+
pickupBranchId: row.pickupBranchId ?? null,
|
|
780
|
+
dropoffBranchId: row.dropoffBranchId ?? null,
|
|
781
|
+
pickupLocation: row.pickupBranchId ? names[String(row.pickupBranchId)] ?? null : null,
|
|
782
|
+
dropoffLocation: row.dropoffBranchId ? names[String(row.dropoffBranchId)] ?? null : null,
|
|
783
|
+
pickupDate: toIso(row.pickupDate),
|
|
784
|
+
dropoffDate: toIso(row.dropoffDate),
|
|
785
|
+
rentalDays: n(row.rentalDays),
|
|
786
|
+
extras: extraRows.map((extra) => ({
|
|
787
|
+
code: extra.code,
|
|
788
|
+
name: extra.name,
|
|
789
|
+
quantity: Math.trunc(Number(extra.quantity)),
|
|
790
|
+
unitPrice: extra.unitPrice !== null && extra.unitPrice !== void 0 ? Number(extra.unitPrice) / 100 : null,
|
|
791
|
+
currency: extra.currency
|
|
792
|
+
})),
|
|
793
|
+
rate,
|
|
794
|
+
totalPrice: Number(row.totalPrice ?? 0) / 100,
|
|
795
|
+
currency: row.currency ?? null,
|
|
796
|
+
customer: { name: row.customerName ?? null, email: row.customerEmail ?? null, phone: row.customerPhone ?? null },
|
|
797
|
+
cdpCode: row.cdpCode ?? null,
|
|
798
|
+
quoteRef: row.quoteRef ?? null,
|
|
799
|
+
rateId: row.rateId ?? null,
|
|
800
|
+
crossBorder: bool(row.crossBorder),
|
|
801
|
+
notes: row.notes ?? null,
|
|
802
|
+
source: row.source ?? null,
|
|
803
|
+
cancelledAt: toIso(row.cancelledAt),
|
|
804
|
+
cancellationReason: row.cancellationReason ?? null,
|
|
805
|
+
createdAt: toIso(row.createdAt),
|
|
806
|
+
updatedAt: toIso(row.updatedAt)
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
/** The "Manage reservation" link for emails: a hash, so redirects and link trackers keep it. */
|
|
810
|
+
manageBookingUrl(reservation, pin) {
|
|
811
|
+
if (!reservation.trim() || !pin.trim()) return null;
|
|
812
|
+
return `${this.siteUrl.replace(/\/+$/, "")}${this.manageBookingPath}#manage=booking/${encodeURIComponent(reservation.trim())}/${encodeURIComponent(pin.trim())}`;
|
|
813
|
+
}
|
|
814
|
+
/** The booking email fields from a booking row (Booking::to_email_notification). Null when something it needs is missing. */
|
|
815
|
+
toEmailNotification(booking, overrides = {}) {
|
|
816
|
+
const email = String(booking.customer?.email ?? "").trim();
|
|
817
|
+
const bookingRef = String(booking.bookingRef ?? "").trim();
|
|
818
|
+
const bookingNumber = String(booking.supplierRef ?? "").trim();
|
|
819
|
+
const supplierName = String(booking.supplierName ?? "").trim();
|
|
820
|
+
const vehicleName = String(booking.vehicle?.name ?? "").trim();
|
|
821
|
+
const currency = String(booking.currency ?? "").trim();
|
|
822
|
+
if (!isEmail(email) || supplierName === "" || vehicleName === "" || currency === "" || booking.totalPrice === void 0 || booking.totalPrice === null) return null;
|
|
823
|
+
const out = {
|
|
824
|
+
customerEmail: email,
|
|
825
|
+
customerName: String(booking.customer?.name ?? email).trim(),
|
|
826
|
+
bookingRef,
|
|
827
|
+
supplierName,
|
|
828
|
+
vehicleName,
|
|
829
|
+
pickupDate: booking.pickupDate,
|
|
830
|
+
dropoffDate: booking.dropoffDate,
|
|
831
|
+
totalPrice: Math.round(Number(booking.totalPrice) * 100),
|
|
832
|
+
currency
|
|
833
|
+
};
|
|
834
|
+
const vehicle = booking.vehicle ?? {};
|
|
835
|
+
if (isWebAddress(vehicle.supplierLogo)) out.supplierLogo = vehicle.supplierLogo;
|
|
836
|
+
if (isWebAddress(vehicle.image)) out.vehicleImage = vehicle.image;
|
|
837
|
+
if (vehicle.group) out.vehicleGroup = String(vehicle.group);
|
|
838
|
+
if (vehicle.seats !== null && vehicle.seats !== void 0) out.vehicleSeats = Math.trunc(vehicle.seats);
|
|
839
|
+
if (vehicle.doors !== null && vehicle.doors !== void 0) out.vehicleDoors = Math.trunc(vehicle.doors);
|
|
840
|
+
if (vehicle.transmission) out.vehicleTransmission = String(vehicle.transmission);
|
|
841
|
+
if (vehicle.fuelType) out.vehicleFuelType = String(vehicle.fuelType);
|
|
842
|
+
if (vehicle.unlimitedMileage) out.unlimitedMileage = true;
|
|
843
|
+
else if (Number(vehicle.kmPerDay) > 0) out.kmPerDay = Math.trunc(vehicle.kmPerDay);
|
|
844
|
+
if (vehicle.ratePackageLabel) out.ratePackageLabel = String(vehicle.ratePackageLabel);
|
|
845
|
+
if (booking.pickupLocation) out.pickupBranchName = String(booking.pickupLocation);
|
|
846
|
+
if (booking.dropoffLocation) out.dropoffBranchName = String(booking.dropoffLocation);
|
|
847
|
+
if (booking.rentalDays !== null && booking.rentalDays !== void 0) out.rentalDays = Math.trunc(booking.rentalDays);
|
|
848
|
+
const pin = String(booking.bookingPin ?? "").trim();
|
|
849
|
+
if (pin !== "") out.bookingPin = pin;
|
|
850
|
+
if (bookingNumber !== "") out.bookingNumber = bookingNumber;
|
|
851
|
+
if (pin !== "") {
|
|
852
|
+
const url = this.manageBookingUrl(bookingNumber !== "" ? bookingNumber : "__RESERVATION__", pin);
|
|
853
|
+
if (isWebAddress(url)) out.manageBookingUrl = url;
|
|
854
|
+
}
|
|
855
|
+
return { ...out, ...overrides };
|
|
856
|
+
}
|
|
857
|
+
// ─── Customers ─────────────────────────────────────────────────────────────
|
|
858
|
+
/** Records or updates the renter, keyed on (accountId, email). Gives back the row id. */
|
|
859
|
+
async upsertCustomer(accountId, customer2) {
|
|
860
|
+
const email = String(customer2.email ?? "");
|
|
861
|
+
if (!email || !this.storage) return null;
|
|
862
|
+
const existing = accountId ? await this.rows("SELECT {id} FROM {Customers} WHERE {accountId} = ? AND {email} = ? LIMIT 1", [accountId, email]) : [];
|
|
863
|
+
const fields = {
|
|
864
|
+
name: truncate(customer2.name),
|
|
865
|
+
firstName: truncate(customer2.firstName),
|
|
866
|
+
lastName: truncate(customer2.lastName),
|
|
867
|
+
title: truncate(customer2.title),
|
|
868
|
+
email: truncate(email),
|
|
869
|
+
additionalEmail: truncate(customer2.additionalEmail),
|
|
870
|
+
phone: truncate(customer2.phone),
|
|
871
|
+
countryCode: truncate(customer2.countryCode),
|
|
872
|
+
dialCode: truncate(customer2.dialCode),
|
|
873
|
+
licenseNumber: truncate(customer2.licenseNumber),
|
|
874
|
+
idNumber: truncate(customer2.idNumber),
|
|
875
|
+
idType: truncate(customer2.idType),
|
|
876
|
+
streetAddress: truncate(customer2.streetAddress),
|
|
877
|
+
suburb: truncate(customer2.suburb),
|
|
878
|
+
city: truncate(customer2.city),
|
|
879
|
+
province: truncate(customer2.province),
|
|
880
|
+
postalCode: truncate(customer2.postalCode),
|
|
881
|
+
country: truncate(customer2.country),
|
|
882
|
+
updatedAt: nowSql()
|
|
883
|
+
};
|
|
884
|
+
if (existing[0]?.id) {
|
|
885
|
+
const id2 = String(existing[0].id);
|
|
886
|
+
const keys = Object.keys(fields);
|
|
887
|
+
await this.exec(`UPDATE {Customers} SET ${keys.map((key) => `${this.q(key)} = ?`).join(", ")} WHERE {id} = ?`, [...keys.map((key) => fields[key]), id2]);
|
|
888
|
+
return id2;
|
|
889
|
+
}
|
|
890
|
+
const id = uuid();
|
|
891
|
+
const row = { ...fields, id, accountId: accountId ? truncate(accountId) : null, createdAt: nowSql() };
|
|
892
|
+
return await this.insert("Customers", row) ? id : null;
|
|
893
|
+
}
|
|
894
|
+
async customer(customerId) {
|
|
895
|
+
if (!customerId) return null;
|
|
896
|
+
const rows = await this.rows(
|
|
897
|
+
"SELECT {name}, {email}, {additionalEmail}, {phone}, {firstName}, {lastName}, {title}, {idNumber}, {idType}, {licenseNumber}, {countryCode}, {dialCode}, {streetAddress}, {suburb}, {city}, {province}, {postalCode}, {country} FROM {Customers} WHERE {id} = ? LIMIT 1",
|
|
898
|
+
[String(customerId)]
|
|
899
|
+
);
|
|
900
|
+
return rows[0] ?? null;
|
|
901
|
+
}
|
|
902
|
+
/** Identity and address the renter may see once they proved the booking is theirs. */
|
|
903
|
+
async publicRenter(customerId) {
|
|
904
|
+
const row = await this.customer(customerId);
|
|
905
|
+
if (!row) return null;
|
|
906
|
+
const keys = ["name", "firstName", "lastName", "title", "email", "additionalEmail", "phone", "dialCode", "idNumber", "idType", "licenseNumber", "country", "streetAddress", "suburb", "city", "province", "postalCode"];
|
|
907
|
+
return Object.fromEntries(
|
|
908
|
+
keys.map((key) => {
|
|
909
|
+
const value = row[key] !== null && row[key] !== void 0 ? String(row[key]).trim() : "";
|
|
910
|
+
return [key, value !== "" ? value : null];
|
|
911
|
+
})
|
|
912
|
+
);
|
|
913
|
+
}
|
|
914
|
+
// ─── Quotes ────────────────────────────────────────────────────────────────
|
|
915
|
+
async createQuote(quote, ttlSeconds = 3600) {
|
|
916
|
+
if (!this.storage) return null;
|
|
917
|
+
const id = uuid();
|
|
918
|
+
const token = quoteToken();
|
|
919
|
+
const now = nowSql();
|
|
920
|
+
const centsOf = (value) => Math.round(Number(value ?? 0) * 100);
|
|
921
|
+
const row = {
|
|
922
|
+
id,
|
|
923
|
+
token,
|
|
924
|
+
// The column may not be empty (null). A site that signs in with its own
|
|
925
|
+
// secret has no API key, so it is saved as an empty text instead.
|
|
926
|
+
apiKey: truncate(quote.apiKey) ?? "",
|
|
927
|
+
customerId: quote.customerId ?? null,
|
|
928
|
+
supplierId: truncate(quote.supplierId),
|
|
929
|
+
supplierIdentifier: truncate(quote.supplierIdentifier),
|
|
930
|
+
supplierName: truncate(quote.supplierName),
|
|
931
|
+
vehicleGroup: truncate(quote.vehicleGroup),
|
|
932
|
+
vehicleName: truncate(quote.vehicleName),
|
|
933
|
+
vehicleImage: truncate(quote.vehicleImage),
|
|
934
|
+
supplierLogo: truncate(quote.supplierLogo),
|
|
935
|
+
vehicleSeats: quote.vehicleSeats ? Math.trunc(quote.vehicleSeats) : null,
|
|
936
|
+
vehicleDoors: quote.vehicleDoors ? Math.trunc(quote.vehicleDoors) : null,
|
|
937
|
+
vehicleTransmission: truncate(quote.vehicleTransmission),
|
|
938
|
+
vehicleFuelType: truncate(quote.vehicleFuelType),
|
|
939
|
+
insuranceIncluded: quote.insuranceIncluded === void 0 ? null : !!quote.insuranceIncluded,
|
|
940
|
+
ratePackageLabel: truncate(quote.ratePackageLabel),
|
|
941
|
+
pickupBranchId: quote.pickupBranchId ?? null,
|
|
942
|
+
dropoffBranchId: quote.dropoffBranchId ?? null,
|
|
943
|
+
pickupDate: quote.pickupDate,
|
|
944
|
+
dropoffDate: quote.dropoffDate,
|
|
945
|
+
rentalDays: quote.rentalDays ? Math.trunc(quote.rentalDays) : null,
|
|
946
|
+
isInternational: !!quote.isInternational,
|
|
947
|
+
cdpCode: truncate(quote.cdpCode),
|
|
948
|
+
quoteRef: truncate(quote.quoteRef),
|
|
949
|
+
rateId: truncate(quote.rateId),
|
|
950
|
+
vehicleAmount: centsOf(quote.vehicleAmount),
|
|
951
|
+
dailyRate: centsOf(quote.dailyRate),
|
|
952
|
+
dropOffFee: Number(quote.dropOffFee) > 0 ? centsOf(quote.dropOffFee) : null,
|
|
953
|
+
deposit: Number(quote.deposit) > 0 ? centsOf(quote.deposit) : null,
|
|
954
|
+
crossBorder: !!quote.crossBorder,
|
|
955
|
+
notes: truncate(quote.notes, 500),
|
|
956
|
+
extras: JSON.stringify(quote.extras ?? []),
|
|
957
|
+
priceBreakdown: JSON.stringify(quote.priceBreakdown ?? []),
|
|
958
|
+
totalPrice: centsOf(quote.totalPrice),
|
|
959
|
+
currency: truncate(quote.currency ?? "ZAR", 8),
|
|
960
|
+
status: "PENDING",
|
|
961
|
+
expiresAt: new Date(Date.now() + Math.max(60, ttlSeconds) * 1e3).toISOString().replace("T", " ").replace("Z", ""),
|
|
962
|
+
metadata: JSON.stringify(quote.metadata ?? {}),
|
|
963
|
+
createdAt: now,
|
|
964
|
+
updatedAt: now
|
|
965
|
+
};
|
|
966
|
+
return await this.insert("Quotes", row) ? { id, token } : null;
|
|
967
|
+
}
|
|
968
|
+
async quoteByToken(token) {
|
|
969
|
+
const trimmed = token.trim();
|
|
970
|
+
if (trimmed === "") return null;
|
|
971
|
+
const rows = await this.rows("SELECT * FROM {Quotes} WHERE {token} = ? LIMIT 1", [trimmed]);
|
|
972
|
+
const row = rows[0];
|
|
973
|
+
if (!row) return null;
|
|
974
|
+
if (row.status === "PENDING") {
|
|
975
|
+
const expires = toIso(row.expiresAt);
|
|
976
|
+
if (expires && new Date(expires).getTime() < Date.now()) {
|
|
977
|
+
await this.updateQuote(String(row.id), { status: "EXPIRED" });
|
|
978
|
+
row.status = "EXPIRED";
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
const [names, customer2] = await Promise.all([this.branchNames([row.pickupBranchId, row.dropoffBranchId]), this.customer(row.customerId)]);
|
|
982
|
+
const meta = decodeJson(row.metadata);
|
|
983
|
+
const kmPerDay = meta.kmPerDay !== void 0 ? Math.trunc(Number(meta.kmPerDay)) : 0;
|
|
984
|
+
const n = (value) => value !== null && value !== void 0 ? Math.trunc(Number(value)) : null;
|
|
985
|
+
return {
|
|
986
|
+
id: String(row.id),
|
|
987
|
+
token: row.token,
|
|
988
|
+
status: row.status,
|
|
989
|
+
apiKey: row.apiKey ?? null,
|
|
990
|
+
customerId: row.customerId ?? null,
|
|
991
|
+
customer: { name: customer2?.name ?? null, email: customer2?.email ?? null, phone: customer2?.phone ?? null },
|
|
992
|
+
supplierId: row.supplierId ?? null,
|
|
993
|
+
supplierIdentifier: row.supplierIdentifier ?? null,
|
|
994
|
+
supplierName: row.supplierName ?? null,
|
|
995
|
+
vehicle: {
|
|
996
|
+
group: row.vehicleGroup ?? null,
|
|
997
|
+
name: row.vehicleName ?? null,
|
|
998
|
+
image: row.vehicleImage ?? null,
|
|
999
|
+
supplierLogo: row.supplierLogo ?? null,
|
|
1000
|
+
seats: n(row.vehicleSeats),
|
|
1001
|
+
doors: n(row.vehicleDoors),
|
|
1002
|
+
transmission: row.vehicleTransmission ?? null,
|
|
1003
|
+
fuelType: row.vehicleFuelType ?? null,
|
|
1004
|
+
insuranceIncluded: row.insuranceIncluded !== null && row.insuranceIncluded !== void 0 ? bool(row.insuranceIncluded) : null,
|
|
1005
|
+
ratePackageLabel: row.ratePackageLabel ?? null,
|
|
1006
|
+
unlimitedMileage: !!meta.unlimitedMileage,
|
|
1007
|
+
kmPerDay: kmPerDay > 0 ? kmPerDay : null
|
|
1008
|
+
},
|
|
1009
|
+
pickupBranchId: row.pickupBranchId ?? null,
|
|
1010
|
+
dropoffBranchId: row.dropoffBranchId ?? null,
|
|
1011
|
+
pickupLocation: names[String(row.pickupBranchId)] ?? null,
|
|
1012
|
+
dropoffLocation: names[String(row.dropoffBranchId)] ?? null,
|
|
1013
|
+
pickupDate: toIso(row.pickupDate),
|
|
1014
|
+
dropoffDate: toIso(row.dropoffDate),
|
|
1015
|
+
pickupDateRaw: row.pickupDate,
|
|
1016
|
+
dropoffDateRaw: row.dropoffDate,
|
|
1017
|
+
rentalDays: n(row.rentalDays),
|
|
1018
|
+
isInternational: bool(row.isInternational),
|
|
1019
|
+
cdpCode: row.cdpCode ?? null,
|
|
1020
|
+
quoteRef: row.quoteRef ?? null,
|
|
1021
|
+
rateId: row.rateId ?? null,
|
|
1022
|
+
vehicleAmount: Number(row.vehicleAmount ?? 0) / 100,
|
|
1023
|
+
dailyRate: Number(row.dailyRate ?? 0) / 100,
|
|
1024
|
+
dropOffFee: row.dropOffFee !== null && row.dropOffFee !== void 0 ? Number(row.dropOffFee) / 100 : null,
|
|
1025
|
+
deposit: row.deposit !== null && row.deposit !== void 0 ? Number(row.deposit) / 100 : null,
|
|
1026
|
+
crossBorder: bool(row.crossBorder),
|
|
1027
|
+
notes: row.notes ?? null,
|
|
1028
|
+
extras: list(row.extras),
|
|
1029
|
+
priceBreakdown: list(row.priceBreakdown),
|
|
1030
|
+
totalPrice: Number(row.totalPrice ?? 0) / 100,
|
|
1031
|
+
currency: row.currency ?? null,
|
|
1032
|
+
expiresAt: toIso(row.expiresAt),
|
|
1033
|
+
bookingId: row.bookingId ?? null,
|
|
1034
|
+
createdAt: toIso(row.createdAt)
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
async markQuoteConfirmed(id, bookingId) {
|
|
1038
|
+
await this.updateQuote(id, { status: "CONFIRMED", bookingId: truncate(bookingId), confirmedAt: nowSql() });
|
|
1039
|
+
}
|
|
1040
|
+
async updateQuote(id, fields) {
|
|
1041
|
+
const keys = Object.keys({ ...fields, updatedAt: "" });
|
|
1042
|
+
const values = { ...fields, updatedAt: nowSql() };
|
|
1043
|
+
await this.exec(`UPDATE {Quotes} SET ${keys.map((key) => `${this.q(key)} = ?`).join(", ")} WHERE {id} = ?`, [...keys.map((key) => values[key]), id]);
|
|
1044
|
+
}
|
|
1045
|
+
async insert(table, row) {
|
|
1046
|
+
const keys = Object.keys(row);
|
|
1047
|
+
try {
|
|
1048
|
+
await this.exec(`INSERT INTO ${this.q(table)} (${keys.map((key) => this.q(key)).join(", ")}) VALUES (${this.placeholders(keys.length)})`, keys.map((key) => row[key]));
|
|
1049
|
+
return true;
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
console.error(`[FleetBridge] Could not record ${table}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1052
|
+
return false;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
|
|
1057
|
+
// src/server/public.handler.ts
|
|
1058
|
+
var CUSTOMER_ERRORS = ["VALIDATION_ERROR", "INVALID_DATE", "UNAVAILABLE", "NOT_FOUND", "MIN_DAYS"];
|
|
1059
|
+
var LOOKUP_ERROR = "We could not find a booking with that booking number and PIN. Please check both and try again.";
|
|
1060
|
+
var STAFF_ONLY = ["id", "bookingRef", "bookingPin", "supplierId", "customerId", "pickupBranchId", "dropoffBranchId", "updatedAt"];
|
|
1061
|
+
var PUBLIC_ACTIONS = [
|
|
1062
|
+
"public_branches",
|
|
1063
|
+
"search_sources",
|
|
1064
|
+
"search_availability",
|
|
1065
|
+
"booking_request",
|
|
1066
|
+
"lookup_booking",
|
|
1067
|
+
"cancel_my_booking",
|
|
1068
|
+
"amend_my_booking",
|
|
1069
|
+
"get_estimation",
|
|
1070
|
+
"get_extras",
|
|
1071
|
+
"get_one_way_fee",
|
|
1072
|
+
"supplier_terms",
|
|
1073
|
+
"payment_methods",
|
|
1074
|
+
"start_payment",
|
|
1075
|
+
"verify_payment",
|
|
1076
|
+
"request_quote",
|
|
1077
|
+
"lookup_quote",
|
|
1078
|
+
"confirm_quote"
|
|
1079
|
+
];
|
|
1080
|
+
function createPublicHandler(opts) {
|
|
1081
|
+
const env = opts.env ?? (globalThis.process?.env ?? {});
|
|
1082
|
+
const timeZone = opts.timeZone ?? "Africa/Johannesburg";
|
|
1083
|
+
const siteUrl = opts.siteUrl.replace(/\/+$/, "");
|
|
1084
|
+
const manageBookingPath = opts.manageBookingPath ?? "/manage-booking";
|
|
1085
|
+
const paymentReturnPath = opts.paymentReturnPath ?? "/booking/payment-return";
|
|
1086
|
+
const secret = opts.secret ?? env.FLEETBRIDGE_SITE_SECRET ?? "";
|
|
1087
|
+
const accountId = opts.accountId ?? env.FLEETBRIDGE_ACCOUNT_ID ?? "";
|
|
1088
|
+
const log = opts.log ?? ((message) => console.error(message));
|
|
1089
|
+
const store = opts.rateLimit === false ? null : opts.rateLimit?.store ?? new MemoryStateStore();
|
|
1090
|
+
const storage = opts.storage ?? (opts.connector.executor?.storage ?? null);
|
|
1091
|
+
const tenant = new Tenant(storage ?? null, siteUrl, manageBookingPath);
|
|
1092
|
+
const hooks = opts.hooks ?? {};
|
|
1093
|
+
const getIp = opts.getIp ?? defaultIp;
|
|
1094
|
+
async function connected() {
|
|
1095
|
+
return (await opts.suppliers()).filter((s) => s.enabled !== false && s.supplierId && s.identifier);
|
|
1096
|
+
}
|
|
1097
|
+
const hasCredentials = (s) => !!s.credentials && Object.keys(s.credentials).length > 0;
|
|
1098
|
+
async function searchable() {
|
|
1099
|
+
return (await connected()).filter((s) => s.identifier !== OWN_FLEET && hasCredentials(s));
|
|
1100
|
+
}
|
|
1101
|
+
async function supplier(identifier) {
|
|
1102
|
+
if (identifier === "") return null;
|
|
1103
|
+
return (await searchable()).find((s) => s.identifier === identifier) ?? null;
|
|
1104
|
+
}
|
|
1105
|
+
async function supplierById(supplierId) {
|
|
1106
|
+
return (await connected()).find((s) => s.supplierId === String(supplierId ?? "")) ?? null;
|
|
1107
|
+
}
|
|
1108
|
+
async function ownFleetConnection() {
|
|
1109
|
+
const own = (await connected()).find((s) => s.identifier === OWN_FLEET);
|
|
1110
|
+
if (own) return own;
|
|
1111
|
+
return opts.ownFleet ? { supplierId: OWN_FLEET, identifier: OWN_FLEET, name: ownFleetName(), credentials: {} } : null;
|
|
1112
|
+
}
|
|
1113
|
+
function ownFleetName() {
|
|
1114
|
+
return (opts.ownFleetName ?? env.FLEETBRIDGE_ACCOUNT_NAME ?? "").trim() || "Our fleet";
|
|
1115
|
+
}
|
|
1116
|
+
async function supplierWithLogin(identifier) {
|
|
1117
|
+
const found = identifier !== OWN_FLEET ? await supplier(identifier) : null;
|
|
1118
|
+
if (!found) fail({ message: "Supplier not available." }, 404);
|
|
1119
|
+
return found;
|
|
1120
|
+
}
|
|
1121
|
+
async function forward(ctx, action, input, quiet = false) {
|
|
1122
|
+
try {
|
|
1123
|
+
return await opts.connector.forward(action, input);
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
const core = coreError(error);
|
|
1126
|
+
log(`[FleetBridge] ${action} failed: ${core ? `${core.code} ${core.message}` : error instanceof Error ? error.message : String(error)}`);
|
|
1127
|
+
await hooks.onError?.({ action: ctx.action, error }).catch(() => void 0);
|
|
1128
|
+
if (quiet) return null;
|
|
1129
|
+
if (core) {
|
|
1130
|
+
const shown = CUSTOMER_ERRORS.includes(core.code);
|
|
1131
|
+
fail({ message: shown ? core.message : "Something went wrong. Please try again.", code: core.code }, core.status || 502);
|
|
1132
|
+
}
|
|
1133
|
+
fail({ message: "Something went wrong. Please try again." }, 502);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
function mapped(map) {
|
|
1137
|
+
try {
|
|
1138
|
+
return map();
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
if (error instanceof MappingError) fail({ message: error.message }, 400);
|
|
1141
|
+
throw error;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
const start = (ctx, name, perHour) => guard(store, name, perHour, ctx.ip);
|
|
1145
|
+
async function publicBranches() {
|
|
1146
|
+
return success({ locations: await tenant.pickerLocations() });
|
|
1147
|
+
}
|
|
1148
|
+
async function searchSources(ctx) {
|
|
1149
|
+
await start(ctx, "search", 60);
|
|
1150
|
+
const sources = [];
|
|
1151
|
+
let ownFleet = false;
|
|
1152
|
+
for (const row of await connected()) {
|
|
1153
|
+
if (row.identifier === OWN_FLEET) {
|
|
1154
|
+
ownFleet = true;
|
|
1155
|
+
continue;
|
|
1156
|
+
}
|
|
1157
|
+
if (hasCredentials(row)) sources.push({ source: row.identifier, supplierName: row.name || row.identifier.charAt(0).toUpperCase() + row.identifier.slice(1) });
|
|
1158
|
+
}
|
|
1159
|
+
if (ownFleet || opts.ownFleet) sources.push({ source: OWN_FLEET, supplierName: ownFleetName() });
|
|
1160
|
+
return success({ sources });
|
|
1161
|
+
}
|
|
1162
|
+
async function search(ctx) {
|
|
1163
|
+
const only = field(ctx.fields, "supplier", 40);
|
|
1164
|
+
await start(ctx, only === "" ? "search" : "search_source", only === "" ? 60 : 600);
|
|
1165
|
+
const suppliers = (await searchable()).filter((row) => only === "" || row.identifier === only).map((row) => ({ supplierId: row.supplierId, credentials: row.credentials }));
|
|
1166
|
+
const trip2 = mapped(
|
|
1167
|
+
() => trip(
|
|
1168
|
+
{
|
|
1169
|
+
pickupLocation: field(ctx.fields, "pickupLocation", 191),
|
|
1170
|
+
returnLocation: field(ctx.fields, "returnLocation", 191),
|
|
1171
|
+
pickupDate: field(ctx.fields, "pickupDate", 10),
|
|
1172
|
+
pickupTime: field(ctx.fields, "pickupTime", 5),
|
|
1173
|
+
returnDate: field(ctx.fields, "returnDate", 10),
|
|
1174
|
+
returnTime: field(ctx.fields, "returnTime", 5),
|
|
1175
|
+
promoCode: field(ctx.fields, "promoCode", 40),
|
|
1176
|
+
isInternational: field(ctx.fields, "isInternational", 5) === "true",
|
|
1177
|
+
driverAge: field(ctx.fields, "driverAge", 3)
|
|
1178
|
+
},
|
|
1179
|
+
timeZone
|
|
1180
|
+
)
|
|
1181
|
+
);
|
|
1182
|
+
const ownFleetOn = await ownFleetConnection() !== null;
|
|
1183
|
+
const result = await forward(ctx, "search.availability", {
|
|
1184
|
+
trip: trip2,
|
|
1185
|
+
includeOwnFleet: ownFleetOn && (only === "" || only === OWN_FLEET),
|
|
1186
|
+
suppliers
|
|
1187
|
+
});
|
|
1188
|
+
const answer = searchAnswer(result?.data, ownFleetName());
|
|
1189
|
+
const count = answer.offers.reduce((sum, offer) => sum + (Array.isArray(offer.fleets) ? offer.fleets.length : 0), 0);
|
|
1190
|
+
await hooks.onSearch?.({ trip: trip2, resultCount: count, sources: answer.sources }).catch(() => void 0);
|
|
1191
|
+
if (answer.offers.length === 0) {
|
|
1192
|
+
const first = answer.sources.find((source2) => source2.message)?.message;
|
|
1193
|
+
fail({ message: first || "No cars for those dates and places.", sources: answer.sources }, 404);
|
|
1194
|
+
}
|
|
1195
|
+
return success(answer);
|
|
1196
|
+
}
|
|
1197
|
+
async function book(ctx) {
|
|
1198
|
+
await start(ctx, "booking", 10);
|
|
1199
|
+
const request = bookingForm(ctx.fields);
|
|
1200
|
+
const method = await paymentChoice(request);
|
|
1201
|
+
request.pay_online = method !== null && method.online;
|
|
1202
|
+
const booked = await bookRequest(ctx, request);
|
|
1203
|
+
if (!request.pay_online) return success(booked.answer);
|
|
1204
|
+
const token = paymentToken(secret, booked.bookingId);
|
|
1205
|
+
const checkout = await startCheckout(ctx, booked.bookingId, method.id, request.payment_purpose, request.return_url, token, true);
|
|
1206
|
+
return success({ ...booked.answer, paymentToken: token, ...checkout });
|
|
1207
|
+
}
|
|
1208
|
+
async function bookRequest(ctx, request) {
|
|
1209
|
+
if (request.first_name === "" || request.last_name === "" || !isEmail(request.email) || request.phone === "") {
|
|
1210
|
+
fail({ message: "Please fill in your name, email address and phone number." }, 400);
|
|
1211
|
+
}
|
|
1212
|
+
let supplierId = "";
|
|
1213
|
+
let credentials = null;
|
|
1214
|
+
let note = null;
|
|
1215
|
+
let supplierName = request.supplier;
|
|
1216
|
+
if (request.identifier !== OWN_FLEET) {
|
|
1217
|
+
const found = await supplier(request.identifier);
|
|
1218
|
+
if (!found || !hasCredentials(found)) fail({ message: "That car can no longer be booked. Please search again." }, 409);
|
|
1219
|
+
supplierId = found.supplierId;
|
|
1220
|
+
credentials = found.credentials;
|
|
1221
|
+
supplierName = found.name || supplierName;
|
|
1222
|
+
note = mapped(() => notification(request, supplierName, timeZone));
|
|
1223
|
+
} else if (isEmail(request.email)) {
|
|
1224
|
+
note = mapped(() => notification(request, supplierName, timeZone));
|
|
1225
|
+
}
|
|
1226
|
+
const input = mapped(() => bookingInput(request, supplierId, credentials, timeZone, note));
|
|
1227
|
+
if (request.pay_online) input.payOnline = true;
|
|
1228
|
+
const result = await forward(ctx, "bookings.create", input);
|
|
1229
|
+
const booking = result?.data?.booking ?? null;
|
|
1230
|
+
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) };
|
|
1231
|
+
if (request.pay_online && booking && booking.status === "PAYMENT_PENDING") {
|
|
1232
|
+
await hooks.onBookingCreated?.(created).catch(() => void 0);
|
|
1233
|
+
return {
|
|
1234
|
+
bookingId: String(booking.id),
|
|
1235
|
+
answer: { reference: booking.id, reservationId: "", bookingPin: booking.pin, supplier: supplierName, status: "PAYMENT_PENDING" }
|
|
1236
|
+
};
|
|
1237
|
+
}
|
|
1238
|
+
if (!booking || booking.status !== "CONFIRMED") {
|
|
1239
|
+
const message = booking?.message ?? "The booking was not confirmed. Nothing has been charged.";
|
|
1240
|
+
log(`[FleetBridge] booking not confirmed: ${message}`);
|
|
1241
|
+
fail({ message, bookingPin: booking?.pin ?? null, reference: booking?.id ?? null }, 502);
|
|
1242
|
+
}
|
|
1243
|
+
await hooks.onBookingCreated?.(created).catch(() => void 0);
|
|
1244
|
+
return {
|
|
1245
|
+
bookingId: String(booking.id),
|
|
1246
|
+
answer: { reference: booking.id, reservationId: booking.bookingNumber, bookingPin: booking.pin, supplier: supplierName, status: "CONFIRMED" }
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
async function paymentMethods(ctx) {
|
|
1250
|
+
await start(ctx, "payment_methods", 120);
|
|
1251
|
+
const code = cut(field(ctx.fields, "branchCode", 40), 40);
|
|
1252
|
+
return success({ methods: await tenant.paymentMethodsFor(code) });
|
|
1253
|
+
}
|
|
1254
|
+
async function startPayment(ctx) {
|
|
1255
|
+
await start(ctx, "payment", 10);
|
|
1256
|
+
const bookingId = tokenBooking(ctx);
|
|
1257
|
+
const methodId = field(ctx.fields, "paymentMethodId", 64);
|
|
1258
|
+
const purpose = field(ctx.fields, "paymentPurpose", 10) || "FULL";
|
|
1259
|
+
const returnUrl = String(ctx.fields.returnUrl ?? "").trim();
|
|
1260
|
+
if (methodId === "") fail({ message: "Please choose how you would like to pay." }, 400);
|
|
1261
|
+
const checkout = await startCheckout(ctx, bookingId, methodId, purpose, returnUrl, paymentToken(secret, bookingId), false);
|
|
1262
|
+
if ("paymentError" in checkout) fail({ message: checkout.paymentError }, 409);
|
|
1263
|
+
return success(checkout);
|
|
1264
|
+
}
|
|
1265
|
+
async function verifyPayment(ctx) {
|
|
1266
|
+
await start(ctx, "payment_check", 60);
|
|
1267
|
+
const bookingId = tokenBooking(ctx);
|
|
1268
|
+
const result = await forward(ctx, "payments.verify", { bookingId });
|
|
1269
|
+
const data = result?.data ?? null;
|
|
1270
|
+
const status = String(data?.booking?.status ?? "");
|
|
1271
|
+
const row = await tenant.booking(bookingId);
|
|
1272
|
+
const answer = {
|
|
1273
|
+
status,
|
|
1274
|
+
paymentStatus: String(data?.payment?.status ?? ""),
|
|
1275
|
+
outcome: String(data?.outcome ?? ""),
|
|
1276
|
+
supplier: String(row?.supplierName ?? "")
|
|
1277
|
+
};
|
|
1278
|
+
if (status === "CONFIRMED") {
|
|
1279
|
+
answer.reservationId = String(data?.booking?.bookingNumber ?? row?.bookingRef ?? "");
|
|
1280
|
+
answer.bookingPin = String(row?.bookingPin ?? "");
|
|
1281
|
+
answer.reference = bookingId;
|
|
1282
|
+
}
|
|
1283
|
+
await hooks.onPaymentVerified?.({ bookingId, status, payment: plain(data?.payment ?? null) }).catch(() => void 0);
|
|
1284
|
+
return success(answer);
|
|
1285
|
+
}
|
|
1286
|
+
async function paymentChoice(request) {
|
|
1287
|
+
if (request.identifier !== OWN_FLEET) return null;
|
|
1288
|
+
const methods = await tenant.paymentMethodsFor(request.pickup_code);
|
|
1289
|
+
if (methods.length === 0) return null;
|
|
1290
|
+
if (request.payment_method_id === "") fail({ message: "Please choose how you would like to pay." }, 400);
|
|
1291
|
+
const method = methods.find((m) => m.id === request.payment_method_id);
|
|
1292
|
+
if (!method) fail({ message: "That way of paying is not offered at this branch any more. Please choose another one." }, 409);
|
|
1293
|
+
return method;
|
|
1294
|
+
}
|
|
1295
|
+
function safeReturnPage(raw) {
|
|
1296
|
+
const fallback = new URL(`${siteUrl}${paymentReturnPath}`);
|
|
1297
|
+
if (!raw) return fallback;
|
|
1298
|
+
try {
|
|
1299
|
+
const url = new URL(raw, `${siteUrl}/`);
|
|
1300
|
+
if (url.origin !== new URL(siteUrl).origin) return fallback;
|
|
1301
|
+
url.searchParams.delete("fb_payment");
|
|
1302
|
+
return url;
|
|
1303
|
+
} catch {
|
|
1304
|
+
return fallback;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
async function startCheckout(ctx, bookingId, methodId, purpose, returnUrl, token, quiet) {
|
|
1308
|
+
const back = safeReturnPage(returnUrl);
|
|
1309
|
+
back.searchParams.set("fb_payment", token);
|
|
1310
|
+
const result = await forward(ctx, "payments.checkout", { bookingId: String(bookingId), methodId: String(methodId), purpose: purpose === "DEPOSIT" ? "DEPOSIT" : "FULL", returnUrl: back.toString() }, quiet);
|
|
1311
|
+
const payment = result?.data?.payment ?? null;
|
|
1312
|
+
if (payment && payment.redirectUrl) {
|
|
1313
|
+
await hooks.onPaymentStarted?.({ bookingId, methodId, redirectUrl: String(payment.redirectUrl) }).catch(() => void 0);
|
|
1314
|
+
return { redirectUrl: String(payment.redirectUrl) };
|
|
1315
|
+
}
|
|
1316
|
+
return { paymentError: String(payment?.message ?? "We could not open the payment page. Please try again.") };
|
|
1317
|
+
}
|
|
1318
|
+
function tokenBooking(ctx) {
|
|
1319
|
+
const token = field(ctx.fields, "paymentToken", 200);
|
|
1320
|
+
const id = secret ? bookingFromToken(secret, token) : null;
|
|
1321
|
+
if (!id) fail({ message: "This payment link is not valid. Please contact us with your booking details." }, 400);
|
|
1322
|
+
return id;
|
|
1323
|
+
}
|
|
1324
|
+
function bookingLookup(number, pin) {
|
|
1325
|
+
const typed = number.trim().replace(/^[\s.]+|[\s.]+$/g, "");
|
|
1326
|
+
const upper = typed.toUpperCase();
|
|
1327
|
+
const prefixed = /^OF-([A-HJ-NP-Z2-9]{6})$/.exec(upper);
|
|
1328
|
+
const alternate = prefixed ? prefixed[1] : /^[A-HJ-NP-Z2-9]{6}$/.test(upper) ? `OF-${upper}` : upper;
|
|
1329
|
+
return { bookingNumber: typed, alternateNumber: alternate, pin };
|
|
1330
|
+
}
|
|
1331
|
+
function numberAndPin(ctx) {
|
|
1332
|
+
const number = field(ctx.fields, "reservationNumber", 191);
|
|
1333
|
+
const pin = field(ctx.fields, "booking_pin", 32).toUpperCase();
|
|
1334
|
+
if (number === "" || pin === "") fail({ message: LOOKUP_ERROR }, 404);
|
|
1335
|
+
return [number, pin];
|
|
1336
|
+
}
|
|
1337
|
+
async function ownBooking(number, pin) {
|
|
1338
|
+
const local = await tenant.bookingByNumberAndPin(number, pin);
|
|
1339
|
+
if (!local) fail({ message: LOOKUP_ERROR }, 404);
|
|
1340
|
+
return local;
|
|
1341
|
+
}
|
|
1342
|
+
async function bookingView(core, number, pin) {
|
|
1343
|
+
const local = await tenant.bookingByNumberAndPin(number, pin);
|
|
1344
|
+
if (!local) return plain(core);
|
|
1345
|
+
const view = Object.fromEntries(Object.entries(local).filter(([key]) => !STAFF_ONLY.includes(key)));
|
|
1346
|
+
if (view.rate && typeof view.rate === "object") {
|
|
1347
|
+
view.rate = { ...view.rate };
|
|
1348
|
+
delete view.rate.customerId;
|
|
1349
|
+
}
|
|
1350
|
+
const allowed = !!core?.canCancel;
|
|
1351
|
+
view.canCancel = allowed;
|
|
1352
|
+
view.canAmend = allowed;
|
|
1353
|
+
const renter = await tenant.publicRenter(local.customerId);
|
|
1354
|
+
if (renter) view.customer = { ...view.customer && typeof view.customer === "object" ? view.customer : {}, ...renter };
|
|
1355
|
+
return view;
|
|
1356
|
+
}
|
|
1357
|
+
async function lookup(ctx) {
|
|
1358
|
+
await start(ctx, "booking_lookup", 8);
|
|
1359
|
+
const [number, pin] = numberAndPin(ctx);
|
|
1360
|
+
let result;
|
|
1361
|
+
try {
|
|
1362
|
+
result = await forward(ctx, "bookings.lookup", { booking: bookingLookup(number, pin) });
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
await hooks.onLookup?.({ bookingNumber: number, found: false, ip: ctx.ip }).catch(() => void 0);
|
|
1365
|
+
throw error;
|
|
1366
|
+
}
|
|
1367
|
+
await hooks.onLookup?.({ bookingNumber: number, found: true, ip: ctx.ip }).catch(() => void 0);
|
|
1368
|
+
return success({ booking: await bookingView(result?.data?.booking ?? null, number, pin) });
|
|
1369
|
+
}
|
|
1370
|
+
async function cancelExtras(local, reason) {
|
|
1371
|
+
const input = {};
|
|
1372
|
+
if (reason !== "") input.reason = reason;
|
|
1373
|
+
if ((local.supplierIdentifier ?? "") !== OWN_FLEET) {
|
|
1374
|
+
const found = await supplierById(local.supplierId);
|
|
1375
|
+
if (found && hasCredentials(found)) input.credentials = found.credentials;
|
|
1376
|
+
}
|
|
1377
|
+
const note = tenant.toEmailNotification(local, reason !== "" ? { cancellationReason: reason } : {});
|
|
1378
|
+
if (note && note.bookingNumber) input.notification = note;
|
|
1379
|
+
return input;
|
|
1380
|
+
}
|
|
1381
|
+
async function cancel(ctx) {
|
|
1382
|
+
await start(ctx, "booking_cancel", 8);
|
|
1383
|
+
const [number, pin] = numberAndPin(ctx);
|
|
1384
|
+
const local = await ownBooking(number, pin);
|
|
1385
|
+
const reason = ctx.fields.reason !== void 0 ? cut(sanitizeTextarea(ctx.fields.reason), 500) : "";
|
|
1386
|
+
const input = { booking: bookingLookup(number, pin), ...await cancelExtras(local, reason) };
|
|
1387
|
+
const result = await forward(ctx, "bookings.cancel", input);
|
|
1388
|
+
const booking = await bookingView(result?.data?.booking ?? null, number, pin);
|
|
1389
|
+
await hooks.onBookingCancelled?.({ booking }).catch(() => void 0);
|
|
1390
|
+
return success({ booking, refundPercent: result?.data?.refundPercent ?? null });
|
|
1391
|
+
}
|
|
1392
|
+
async function amend(ctx) {
|
|
1393
|
+
await start(ctx, "booking_amend", 8);
|
|
1394
|
+
const [number, pin] = numberAndPin(ctx);
|
|
1395
|
+
const local = await ownBooking(number, pin);
|
|
1396
|
+
const request = bookingForm(ctx.fields);
|
|
1397
|
+
if (request.identifier === "" || request.identifier !== String(local.supplierIdentifier ?? "")) {
|
|
1398
|
+
fail({ message: `This change has to stay with ${local.supplierName || "the same supplier"}. Please search again.` }, 409);
|
|
1399
|
+
}
|
|
1400
|
+
if (request.pickup_location === "") request.pickup_location = String(local.pickupLocation ?? "");
|
|
1401
|
+
if (request.dropoff_location === "") request.dropoff_location = String(local.dropoffLocation || request.pickup_location);
|
|
1402
|
+
let supplierId = "";
|
|
1403
|
+
let credentials = null;
|
|
1404
|
+
if (request.identifier !== OWN_FLEET) {
|
|
1405
|
+
supplierId = String(local.supplierId ?? "");
|
|
1406
|
+
const found = await supplierById(supplierId);
|
|
1407
|
+
if (!found || !hasCredentials(found)) fail({ message: "This booking cannot be changed online right now. Please contact us." }, 409);
|
|
1408
|
+
credentials = found.credentials;
|
|
1409
|
+
}
|
|
1410
|
+
const input = mapped(() => amendInput(request, bookingLookup(number, pin), String(local.id), supplierId, credentials, timeZone, amendNotification(local, request)));
|
|
1411
|
+
const result = await forward(ctx, "bookings.amend", input);
|
|
1412
|
+
const booking = await bookingView(result?.data?.booking ?? null, number, pin);
|
|
1413
|
+
await hooks.onBookingAmended?.({ booking, price: plain(result?.data?.price ?? null) }).catch(() => void 0);
|
|
1414
|
+
return success({ booking });
|
|
1415
|
+
}
|
|
1416
|
+
function amendNotification(local, request) {
|
|
1417
|
+
const newPickup = isoTime(request.pickup_date, request.pickup_time, timeZone);
|
|
1418
|
+
const newReturn = isoTime(request.return_date, request.return_time, timeZone);
|
|
1419
|
+
const changes = [];
|
|
1420
|
+
for (const [label, previous, next] of [
|
|
1421
|
+
["Pick-up", local.pickupDate, newPickup],
|
|
1422
|
+
["Drop-off", local.dropoffDate, newReturn]
|
|
1423
|
+
]) {
|
|
1424
|
+
if (shownTime(previous, timeZone) !== shownTime(next, timeZone)) changes.push({ label, previous: shownTime(previous, timeZone), next: shownTime(next, timeZone) });
|
|
1425
|
+
}
|
|
1426
|
+
const oldCar = String(local.vehicle?.name ?? "");
|
|
1427
|
+
if (request.car_label !== "" && request.car_label !== oldCar) changes.push({ label: "Vehicle", previous: oldCar || "\u2014", next: request.car_label });
|
|
1428
|
+
const fresh = notification(request, String(local.supplierName ?? ""), timeZone);
|
|
1429
|
+
delete fresh.customerEmail;
|
|
1430
|
+
delete fresh.customerName;
|
|
1431
|
+
delete fresh.supplierName;
|
|
1432
|
+
return tenant.toEmailNotification(local, { ...fresh, changes });
|
|
1433
|
+
}
|
|
1434
|
+
async function supplierCall(ctx, action, found, params, fallback) {
|
|
1435
|
+
const result = await forward(ctx, action, { supplierId: found.supplierId, credentials: found.credentials, params });
|
|
1436
|
+
const data = result?.data;
|
|
1437
|
+
if (!data || typeof data !== "object" || "success" in data && !data.success) {
|
|
1438
|
+
const message = data && typeof data === "object" && typeof data.error === "string" && data.error !== "" ? data.error : fallback;
|
|
1439
|
+
fail({ message }, 502);
|
|
1440
|
+
}
|
|
1441
|
+
return data;
|
|
1442
|
+
}
|
|
1443
|
+
async function estimation(ctx) {
|
|
1444
|
+
await start(ctx, "estimation", 600);
|
|
1445
|
+
const found = await supplierWithLogin(field(ctx.fields, "identifier", 40));
|
|
1446
|
+
const params = {
|
|
1447
|
+
pickupLocation: field(ctx.fields, "pickupLocation", 40),
|
|
1448
|
+
returnLocation: field(ctx.fields, "returnLocation", 40),
|
|
1449
|
+
pickupDate: field(ctx.fields, "pickupDate", 10),
|
|
1450
|
+
pickupTime: field(ctx.fields, "pickupTime", 5),
|
|
1451
|
+
returnDate: field(ctx.fields, "returnDate", 10),
|
|
1452
|
+
returnTime: field(ctx.fields, "returnTime", 5),
|
|
1453
|
+
vehicleGroup: field(ctx.fields, "vehicleGroup", 40)
|
|
1454
|
+
};
|
|
1455
|
+
const rateId = field(ctx.fields, "rateId", 40);
|
|
1456
|
+
if (rateId !== "") params.rateId = rateId;
|
|
1457
|
+
const extras3 = extrasFromJson(ctx.fields.extras ?? "").filter((extra) => extra.name !== "").map((extra) => ({ code: extra.code, name: extra.name, quantity: extra.quantity }));
|
|
1458
|
+
if (extras3.length) params.extras = extras3;
|
|
1459
|
+
const data = await supplierCall(ctx, "suppliers.estimation", found, params, "Could not get a live price right now.");
|
|
1460
|
+
const n = (value) => value !== void 0 && value !== null ? Number(value) : null;
|
|
1461
|
+
return success({
|
|
1462
|
+
totalPrice: n(data.totalPrice),
|
|
1463
|
+
deposit: n(data.deposit),
|
|
1464
|
+
dropOffFee: n(data.dropOffFee),
|
|
1465
|
+
breakdown: data.breakdown !== void 0 && data.breakdown !== null ? data.breakdown : {},
|
|
1466
|
+
quoteRef: data.quoteRef ?? null
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
async function oneWayFee(ctx) {
|
|
1470
|
+
await start(ctx, "one_way_fee", 600);
|
|
1471
|
+
const found = await supplierWithLogin(field(ctx.fields, "identifier", 40));
|
|
1472
|
+
const data = await supplierCall(
|
|
1473
|
+
ctx,
|
|
1474
|
+
"suppliers.oneWayFee",
|
|
1475
|
+
found,
|
|
1476
|
+
{
|
|
1477
|
+
pickupLocation: field(ctx.fields, "pickupLocation", 40),
|
|
1478
|
+
returnLocation: field(ctx.fields, "returnLocation", 40),
|
|
1479
|
+
pickupDate: field(ctx.fields, "pickupDate", 10),
|
|
1480
|
+
pickupTime: field(ctx.fields, "pickupTime", 5)
|
|
1481
|
+
},
|
|
1482
|
+
"Could not get a live one-way fee right now."
|
|
1483
|
+
);
|
|
1484
|
+
return success({
|
|
1485
|
+
fee: data.fee !== void 0 && data.fee !== null ? Number(data.fee) : null,
|
|
1486
|
+
allowed: data.allowed !== void 0 && data.allowed !== null ? !!data.allowed : null
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
async function extras2(ctx) {
|
|
1490
|
+
await start(ctx, "extras", 600);
|
|
1491
|
+
const identifier = field(ctx.fields, "identifier", 40);
|
|
1492
|
+
if (identifier === "") fail({ message: "Missing supplier identifier." }, 400);
|
|
1493
|
+
const category = identifier === OWN_FLEET ? field(ctx.fields, "category", 200) : "";
|
|
1494
|
+
const rows = await tenant.extrasFor(identifier, category);
|
|
1495
|
+
if (rows.length > 0) {
|
|
1496
|
+
return success({ extras: rows.map((row) => ({ ...row, price: Number(row.price ?? 0), isFree: !!row.isFree && row.isFree !== "0", isAvailable: !!row.isAvailable && row.isAvailable !== "0" })) });
|
|
1497
|
+
}
|
|
1498
|
+
const found = identifier !== OWN_FLEET ? await supplier(identifier) : null;
|
|
1499
|
+
const result = found ? await forward(ctx, "suppliers.extras", { supplierId: found.supplierId, credentials: found.credentials, params: {} }, true) : null;
|
|
1500
|
+
const items = Array.isArray(result?.data) ? result.data : result?.data && typeof result.data === "object" ? Object.values(result.data) : [];
|
|
1501
|
+
return success({
|
|
1502
|
+
extras: items.map((item) => ({
|
|
1503
|
+
code: String(item?.code ?? ""),
|
|
1504
|
+
name: String(item?.name ?? ""),
|
|
1505
|
+
description: "",
|
|
1506
|
+
serviceType: String(item?.type ?? ""),
|
|
1507
|
+
price: Number(item?.price ?? 0),
|
|
1508
|
+
currency: String(item?.currency ?? "ZAR"),
|
|
1509
|
+
isFree: !!item?.isFree,
|
|
1510
|
+
isAvailable: true
|
|
1511
|
+
}))
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
async function supplierTerms(ctx) {
|
|
1515
|
+
await start(ctx, "supplier_terms", 60);
|
|
1516
|
+
const identifier = field(ctx.fields, "identifier", 40);
|
|
1517
|
+
if (identifier === "") fail({ message: "Missing supplier." }, 400);
|
|
1518
|
+
const result = await forward(ctx, "suppliers.terms.current", { supplierId: identifier }, true);
|
|
1519
|
+
const data = result?.data ?? null;
|
|
1520
|
+
return success({ terms: data && typeof data === "object" ? data.terms ?? null : null });
|
|
1521
|
+
}
|
|
1522
|
+
async function requestQuote(ctx) {
|
|
1523
|
+
await start(ctx, "quote", 10);
|
|
1524
|
+
const request = bookingForm(ctx.fields);
|
|
1525
|
+
if (request.first_name === "" || request.last_name === "" || request.phone === "" || !isEmail(request.email)) {
|
|
1526
|
+
fail({ message: "Please check your name, email and phone number." }, 400);
|
|
1527
|
+
}
|
|
1528
|
+
const pickupAt = toSqlDatetime(request.pickup_date, request.pickup_time);
|
|
1529
|
+
const dropoffAt = toSqlDatetime(request.return_date, request.return_time);
|
|
1530
|
+
if (!pickupAt || !dropoffAt) fail({ message: "Please choose your pick-up and drop-off dates." }, 400);
|
|
1531
|
+
let found;
|
|
1532
|
+
if (request.identifier === OWN_FLEET) {
|
|
1533
|
+
found = await ownFleetConnection();
|
|
1534
|
+
if (request.pickup_code === "") request.pickup_code = await tenant.codeForName(OWN_FLEET, request.pickup_location) ?? "";
|
|
1535
|
+
if (request.dropoff_code === "") request.dropoff_code = await tenant.codeForName(OWN_FLEET, request.dropoff_location) ?? request.pickup_code;
|
|
1536
|
+
} else {
|
|
1537
|
+
found = request.identifier !== "" ? await supplier(request.identifier) : null;
|
|
1538
|
+
}
|
|
1539
|
+
if (!found || request.pickup_code === "" || request.vehicle_group === "") fail({ message: "That vehicle is no longer available. Please search again." }, 409);
|
|
1540
|
+
const pickupBranchId = await tenant.branchIdFor(request.identifier, request.pickup_code);
|
|
1541
|
+
const dropoffBranchId = await tenant.branchIdFor(request.identifier, request.dropoff_code || request.pickup_code);
|
|
1542
|
+
if (!pickupBranchId || !dropoffBranchId) {
|
|
1543
|
+
fail({ message: "That location has not been synced to this site yet. Please sync branches in the FleetBridge admin and try again." }, 409);
|
|
1544
|
+
}
|
|
1545
|
+
const supplierName = found.name || request.identifier;
|
|
1546
|
+
const customerId = await tenant.upsertCustomer(accountId, {
|
|
1547
|
+
name: `${request.first_name} ${request.last_name}`.trim(),
|
|
1548
|
+
firstName: request.first_name,
|
|
1549
|
+
lastName: request.last_name,
|
|
1550
|
+
title: request.title,
|
|
1551
|
+
email: request.email,
|
|
1552
|
+
phone: request.phone,
|
|
1553
|
+
idNumber: request.id_number,
|
|
1554
|
+
idType: request.is_international ? "PASSPORT" : "ID",
|
|
1555
|
+
countryCode: request.country_code,
|
|
1556
|
+
dialCode: request.dial_code,
|
|
1557
|
+
streetAddress: request.street_address,
|
|
1558
|
+
suburb: request.suburb,
|
|
1559
|
+
city: request.city,
|
|
1560
|
+
province: request.province,
|
|
1561
|
+
postalCode: request.postal_code,
|
|
1562
|
+
country: request.country,
|
|
1563
|
+
licenseNumber: request.licence_number,
|
|
1564
|
+
additionalEmail: request.additional_email
|
|
1565
|
+
});
|
|
1566
|
+
const quote = await tenant.createQuote({
|
|
1567
|
+
apiKey: "",
|
|
1568
|
+
customerId,
|
|
1569
|
+
supplierId: found.supplierId,
|
|
1570
|
+
supplierIdentifier: request.identifier,
|
|
1571
|
+
supplierName,
|
|
1572
|
+
vehicleGroup: request.vehicle_group,
|
|
1573
|
+
vehicleName: request.car_label,
|
|
1574
|
+
vehicleImage: request.car_image,
|
|
1575
|
+
supplierLogo: request.supplier_logo,
|
|
1576
|
+
vehicleSeats: request.seats || null,
|
|
1577
|
+
vehicleDoors: request.doors || null,
|
|
1578
|
+
vehicleTransmission: request.transmission,
|
|
1579
|
+
vehicleFuelType: request.fuel_type,
|
|
1580
|
+
insuranceIncluded: request.insurance_included,
|
|
1581
|
+
ratePackageLabel: request.rate_package_label,
|
|
1582
|
+
pickupBranchId,
|
|
1583
|
+
dropoffBranchId,
|
|
1584
|
+
pickupDate: pickupAt,
|
|
1585
|
+
dropoffDate: dropoffAt,
|
|
1586
|
+
rentalDays: request.days,
|
|
1587
|
+
isInternational: request.is_international,
|
|
1588
|
+
cdpCode: request.cdp_code,
|
|
1589
|
+
quoteRef: request.quote_ref,
|
|
1590
|
+
rateId: request.rate_id,
|
|
1591
|
+
vehicleAmount: request.vehicle_amount,
|
|
1592
|
+
dailyRate: request.daily_rate,
|
|
1593
|
+
dropOffFee: request.drop_off_fee,
|
|
1594
|
+
deposit: request.deposit,
|
|
1595
|
+
crossBorder: request.crossing_border,
|
|
1596
|
+
notes: request.notes,
|
|
1597
|
+
extras: request.extras,
|
|
1598
|
+
priceBreakdown: priceLines(request),
|
|
1599
|
+
totalPrice: request.estimated_total,
|
|
1600
|
+
currency: request.currency || "ZAR",
|
|
1601
|
+
metadata: { unlimitedMileage: !!request.unlimited_mileage, kmPerDay: Math.trunc(request.km_per_day) }
|
|
1602
|
+
});
|
|
1603
|
+
if (!quote) fail({ message: "Could not record your quote. Please try again." }, 500);
|
|
1604
|
+
const note = {
|
|
1605
|
+
...mapped(() => notification(request, supplierName, timeZone)),
|
|
1606
|
+
quoteRef: quote.id.slice(0, 8),
|
|
1607
|
+
confirmUrl: `${siteUrl}${manageBookingPath}#manage=quote/${encodeURIComponent(quote.token)}`,
|
|
1608
|
+
expiresAt: new Date(Date.now() + 3600 * 1e3).toISOString().replace(/\.\d{3}Z$/, "+00:00")
|
|
1609
|
+
};
|
|
1610
|
+
await forward(ctx, "suppliers.bookings.quotation", { supplierId: found.supplierId, notification: note });
|
|
1611
|
+
return success({ message: "Check your email for your quote.", customerId });
|
|
1612
|
+
}
|
|
1613
|
+
async function pendingQuote(ctx) {
|
|
1614
|
+
const token = field(ctx.fields, "token", 128);
|
|
1615
|
+
if (token === "") fail({ message: "Missing quote reference." }, 400);
|
|
1616
|
+
const quote = await tenant.quoteByToken(token);
|
|
1617
|
+
if (!quote) fail({ message: "We couldn't find that quote." }, 404);
|
|
1618
|
+
if (quote.status === "CONFIRMED") fail({ message: "This quote has already been booked.", bookingId: quote.bookingId }, 409);
|
|
1619
|
+
if (quote.status !== "PENDING") fail({ message: "This quote has expired. Please search again for current pricing." }, 410);
|
|
1620
|
+
return quote;
|
|
1621
|
+
}
|
|
1622
|
+
async function lookupQuote(ctx) {
|
|
1623
|
+
await start(ctx, "lookup_quote", 30);
|
|
1624
|
+
const quote = await pendingQuote(ctx);
|
|
1625
|
+
const extrasView = (quote.extras ?? []).map((extra) => ({
|
|
1626
|
+
code: String(extra.code ?? ""),
|
|
1627
|
+
name: String(extra.name ?? extra.code ?? "Extra"),
|
|
1628
|
+
quantity: Math.trunc(Number(extra.quantity ?? 1)),
|
|
1629
|
+
unitPrice: extra.unitPrice !== void 0 && extra.unitPrice !== null ? Number(extra.unitPrice) : null,
|
|
1630
|
+
currency: String(quote.currency ?? "ZAR")
|
|
1631
|
+
}));
|
|
1632
|
+
const breakdown = (quote.priceBreakdown ?? []).filter((line) => String(line.label ?? "").trim() !== "").map((line) => ({ label: String(line.label).trim(), amount: Math.trunc(Number(line.amount ?? 0)) / 100 }));
|
|
1633
|
+
const renter = await tenant.publicRenter(quote.customerId);
|
|
1634
|
+
return success({
|
|
1635
|
+
quote: {
|
|
1636
|
+
quoteRef: String(quote.id).slice(0, 8),
|
|
1637
|
+
status: quote.status,
|
|
1638
|
+
expiresAt: quote.expiresAt,
|
|
1639
|
+
supplierName: quote.supplierName,
|
|
1640
|
+
vehicle: quote.vehicle,
|
|
1641
|
+
pickupLocation: quote.pickupLocation,
|
|
1642
|
+
dropoffLocation: quote.dropoffLocation,
|
|
1643
|
+
pickupDate: quote.pickupDate,
|
|
1644
|
+
dropoffDate: quote.dropoffDate,
|
|
1645
|
+
rentalDays: quote.rentalDays,
|
|
1646
|
+
extras: extrasView,
|
|
1647
|
+
priceBreakdown: breakdown,
|
|
1648
|
+
totalPrice: Number(quote.totalPrice),
|
|
1649
|
+
currency: quote.currency,
|
|
1650
|
+
deposit: quote.deposit !== null ? Number(quote.deposit) : null,
|
|
1651
|
+
customer: renter ?? { name: null, email: null, phone: null },
|
|
1652
|
+
notes: quote.notes,
|
|
1653
|
+
crossBorder: !!quote.crossBorder
|
|
1654
|
+
}
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
async function confirmQuote(ctx) {
|
|
1658
|
+
await start(ctx, "confirm_quote", 10);
|
|
1659
|
+
const quote = await pendingQuote(ctx);
|
|
1660
|
+
const request = await requestFromQuote(quote);
|
|
1661
|
+
if (!request) fail({ message: "This quote is missing information needed to complete the booking. Please search again." }, 409);
|
|
1662
|
+
const booked = await bookRequest(ctx, request);
|
|
1663
|
+
await tenant.markQuoteConfirmed(String(quote.id), booked.bookingId);
|
|
1664
|
+
return success(booked.answer);
|
|
1665
|
+
}
|
|
1666
|
+
async function requestFromQuote(quote) {
|
|
1667
|
+
const customer2 = await tenant.customer(quote.customerId);
|
|
1668
|
+
const pickupCode = await tenant.branchCodeById(quote.pickupBranchId);
|
|
1669
|
+
const dropoffCode = await tenant.branchCodeById(quote.dropoffBranchId);
|
|
1670
|
+
if (!customer2 || !quote.supplierIdentifier || !pickupCode || !dropoffCode) return null;
|
|
1671
|
+
const [pickupDate, pickupTime] = splitSqlDatetime(quote.pickupDateRaw);
|
|
1672
|
+
const [returnDate, returnTime] = splitSqlDatetime(quote.dropoffDateRaw);
|
|
1673
|
+
const vehicle = quote.vehicle;
|
|
1674
|
+
const s = (value) => value === null || value === void 0 ? "" : String(value);
|
|
1675
|
+
return {
|
|
1676
|
+
...bookingForm({}),
|
|
1677
|
+
identifier: s(quote.supplierIdentifier),
|
|
1678
|
+
pickup_code: pickupCode,
|
|
1679
|
+
dropoff_code: dropoffCode,
|
|
1680
|
+
vehicle_group: s(vehicle.group),
|
|
1681
|
+
rate_id: s(quote.rateId),
|
|
1682
|
+
quote_ref: s(quote.quoteRef),
|
|
1683
|
+
cdp_code: s(quote.cdpCode),
|
|
1684
|
+
car_label: s(vehicle.name),
|
|
1685
|
+
supplier: s(quote.supplierName),
|
|
1686
|
+
car_image: s(vehicle.image),
|
|
1687
|
+
supplier_logo: s(vehicle.supplierLogo),
|
|
1688
|
+
seats: Math.trunc(Number(vehicle.seats ?? 0)),
|
|
1689
|
+
doors: Math.trunc(Number(vehicle.doors ?? 0)),
|
|
1690
|
+
transmission: s(vehicle.transmission),
|
|
1691
|
+
fuel_type: s(vehicle.fuelType),
|
|
1692
|
+
insurance_included: !!vehicle.insuranceIncluded,
|
|
1693
|
+
unlimited_mileage: !!vehicle.unlimitedMileage,
|
|
1694
|
+
km_per_day: Math.trunc(Number(vehicle.kmPerDay ?? 0)),
|
|
1695
|
+
daily_rate: Number(quote.dailyRate ?? 0),
|
|
1696
|
+
currency: s(quote.currency) || "ZAR",
|
|
1697
|
+
days: Math.trunc(Number(quote.rentalDays ?? 0)),
|
|
1698
|
+
estimated_total: Number(quote.totalPrice ?? 0),
|
|
1699
|
+
vehicle_amount: Number(quote.vehicleAmount ?? 0),
|
|
1700
|
+
deposit: Number(quote.deposit ?? 0),
|
|
1701
|
+
drop_off_fee: Number(quote.dropOffFee ?? 0),
|
|
1702
|
+
rate_package_label: s(vehicle.ratePackageLabel),
|
|
1703
|
+
pickup_location: s(quote.pickupLocation),
|
|
1704
|
+
dropoff_location: s(quote.dropoffLocation),
|
|
1705
|
+
pickup_date: pickupDate,
|
|
1706
|
+
pickup_time: pickupTime,
|
|
1707
|
+
return_date: returnDate,
|
|
1708
|
+
return_time: returnTime,
|
|
1709
|
+
is_international: !!quote.isInternational,
|
|
1710
|
+
extras: extrasFromJson(JSON.stringify(quote.extras ?? [])),
|
|
1711
|
+
title: s(customer2.title),
|
|
1712
|
+
first_name: s(customer2.firstName),
|
|
1713
|
+
last_name: s(customer2.lastName),
|
|
1714
|
+
email: s(customer2.email),
|
|
1715
|
+
phone: s(customer2.phone),
|
|
1716
|
+
licence_number: s(customer2.licenseNumber),
|
|
1717
|
+
country: s(customer2.country),
|
|
1718
|
+
country_code: s(customer2.countryCode),
|
|
1719
|
+
dial_code: s(customer2.dialCode),
|
|
1720
|
+
id_number: s(customer2.idNumber),
|
|
1721
|
+
crossing_border: !!quote.crossBorder,
|
|
1722
|
+
street_address: s(customer2.streetAddress),
|
|
1723
|
+
city: s(customer2.city),
|
|
1724
|
+
suburb: s(customer2.suburb),
|
|
1725
|
+
province: s(customer2.province),
|
|
1726
|
+
postal_code: s(customer2.postalCode),
|
|
1727
|
+
notes: s(quote.notes)
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
const routes = {
|
|
1731
|
+
public_branches: publicBranches,
|
|
1732
|
+
search_sources: searchSources,
|
|
1733
|
+
search_availability: search,
|
|
1734
|
+
booking_request: book,
|
|
1735
|
+
lookup_booking: lookup,
|
|
1736
|
+
cancel_my_booking: cancel,
|
|
1737
|
+
amend_my_booking: amend,
|
|
1738
|
+
get_estimation: estimation,
|
|
1739
|
+
get_extras: extras2,
|
|
1740
|
+
get_one_way_fee: oneWayFee,
|
|
1741
|
+
supplier_terms: supplierTerms,
|
|
1742
|
+
payment_methods: paymentMethods,
|
|
1743
|
+
start_payment: startPayment,
|
|
1744
|
+
verify_payment: verifyPayment,
|
|
1745
|
+
request_quote: requestQuote,
|
|
1746
|
+
lookup_quote: lookupQuote,
|
|
1747
|
+
confirm_quote: confirmQuote
|
|
1748
|
+
};
|
|
1749
|
+
return async function handle(request) {
|
|
1750
|
+
if (request.method !== "POST") return json({ success: false, data: { message: "Use POST." } }, 405);
|
|
1751
|
+
let fields;
|
|
1752
|
+
try {
|
|
1753
|
+
fields = await readFields(request);
|
|
1754
|
+
} catch {
|
|
1755
|
+
return json({ success: false, data: { message: "Something went wrong. Please try again." } }, 400);
|
|
1756
|
+
}
|
|
1757
|
+
const name = String(fields.action ?? "").replace(/^fleetbridge_/, "");
|
|
1758
|
+
const route = routes[name];
|
|
1759
|
+
if (!route) return json({ success: false, data: { message: "Unknown action." } }, 400);
|
|
1760
|
+
const ctx = { action: name, fields, ip: getIp(request), request };
|
|
1761
|
+
try {
|
|
1762
|
+
const stop = await hooks.beforeAction?.({ action: name, fields, ip: ctx.ip, request });
|
|
1763
|
+
if (stop) return stop;
|
|
1764
|
+
return await route(ctx);
|
|
1765
|
+
} catch (error) {
|
|
1766
|
+
if (error instanceof Stop) return error.response;
|
|
1767
|
+
log(`[FleetBridge] ${name} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1768
|
+
await hooks.onError?.({ action: name, error }).catch(() => void 0);
|
|
1769
|
+
return json({ success: false, data: { message: "Something went wrong. Please try again." } }, 500);
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
// src/server/admin.handler.ts
|
|
1775
|
+
var DEFAULT_ADMIN_ALLOW = ["fleet.", "promotions.", "suppliers.terms.", "sites.list", "payments.refund", "payments.verify"];
|
|
1776
|
+
var STAFF_ADMIN_ALLOW = [...DEFAULT_ADMIN_ALLOW, "bookings.list", "bookings.staffCancel", "suppliers.branches", "suppliers.extras"];
|
|
1777
|
+
var ADMIN_MAX_INPUT_BYTES = 65536;
|
|
1778
|
+
var TERMS_MAX_INPUT_BYTES = 5242880;
|
|
1779
|
+
function adminMayRun(action, allow = DEFAULT_ADMIN_ALLOW) {
|
|
1780
|
+
if (typeof action !== "string" || !/^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/.test(action)) return false;
|
|
1781
|
+
return allow.some((entry) => entry.endsWith(".") ? action.startsWith(entry) : action === entry);
|
|
1782
|
+
}
|
|
1783
|
+
function createAdminHandler(opts) {
|
|
1784
|
+
const allow = opts.allow ?? DEFAULT_ADMIN_ALLOW;
|
|
1785
|
+
const log = opts.log ?? ((message) => console.error(message));
|
|
1786
|
+
const problem = (error, status, code) => json({ ok: false, error, ...code ? { code } : {}, status }, status);
|
|
1787
|
+
return async function handle(request) {
|
|
1788
|
+
if (request.method !== "POST") return problem("Use POST.", 405);
|
|
1789
|
+
const who = await opts.authorize(request).catch(() => ({ ok: false, status: 401, message: "Permission denied" }));
|
|
1790
|
+
if (!who.ok) return problem(who.message ?? "Permission denied", who.status ?? 403);
|
|
1791
|
+
const raw = await request.text();
|
|
1792
|
+
let body;
|
|
1793
|
+
try {
|
|
1794
|
+
body = raw === "" ? {} : JSON.parse(raw);
|
|
1795
|
+
} catch {
|
|
1796
|
+
return problem("The input must be a JSON object", 400);
|
|
1797
|
+
}
|
|
1798
|
+
const record = body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
|
1799
|
+
const action = record.action ?? record.fb_action;
|
|
1800
|
+
if (!adminMayRun(action, allow)) return problem("This action is not allowed here", 400);
|
|
1801
|
+
let input = record.input ?? {};
|
|
1802
|
+
if (typeof input === "string") {
|
|
1803
|
+
try {
|
|
1804
|
+
input = input === "" ? {} : JSON.parse(input);
|
|
1805
|
+
} catch {
|
|
1806
|
+
return problem("The input must be a JSON object", 400);
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return problem("The input must be a JSON object", 400);
|
|
1810
|
+
const maxBytes = action === "suppliers.terms.publish" ? TERMS_MAX_INPUT_BYTES : ADMIN_MAX_INPUT_BYTES;
|
|
1811
|
+
if (new TextEncoder().encode(JSON.stringify(input)).length > maxBytes) return problem("That is too much to send at once", 413);
|
|
1812
|
+
try {
|
|
1813
|
+
const result = opts.connector ? await opts.connector.forward(action, input) : { data: await opts.client.call(action, input), acks: [] };
|
|
1814
|
+
await opts.hooks?.onAction?.({ action, actor: who.actor, ok: true }).catch(() => void 0);
|
|
1815
|
+
return json({ ok: true, data: result.data, changeSets: result.acks });
|
|
1816
|
+
} catch (error) {
|
|
1817
|
+
await opts.hooks?.onAction?.({ action, actor: who.actor, ok: false }).catch(() => void 0);
|
|
1818
|
+
const core = coreError(error);
|
|
1819
|
+
if (core) return problem(core.message, core.status || 502, core.code);
|
|
1820
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
1821
|
+
log(`[FleetBridge] ${action} failed: ${text}`);
|
|
1822
|
+
if (/doesn't exist|does not exist|no such table|unknown column|undefined column/i.test(text)) {
|
|
1823
|
+
return problem("Your FleetBridge tables are out of date. Update the tables, then try again.", 502, "SCHEMA_UPGRADE_REQUIRED");
|
|
1824
|
+
}
|
|
1825
|
+
return problem("Something went wrong. Please try again.", 502);
|
|
1826
|
+
}
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
// src/server/suppliers.ts
|
|
1831
|
+
function readSuppliersFromEnv(env) {
|
|
1832
|
+
const source2 = env ?? (globalThis.process?.env ?? {});
|
|
1833
|
+
const raw = source2.FLEETBRIDGE_SUPPLIERS;
|
|
1834
|
+
if (!raw || raw.trim() === "") return [];
|
|
1835
|
+
let parsed;
|
|
1836
|
+
try {
|
|
1837
|
+
parsed = JSON.parse(raw);
|
|
1838
|
+
} catch {
|
|
1839
|
+
console.error("[FleetBridge] FLEETBRIDGE_SUPPLIERS is not valid JSON");
|
|
1840
|
+
return [];
|
|
1841
|
+
}
|
|
1842
|
+
if (!Array.isArray(parsed)) return [];
|
|
1843
|
+
return parsed.filter((item) => !!item && typeof item === "object").filter((item) => typeof item.supplierId === "string" && typeof item.identifier === "string" && item.supplierId !== "" && item.identifier !== "").map((item) => ({
|
|
1844
|
+
supplierId: String(item.supplierId),
|
|
1845
|
+
identifier: String(item.identifier),
|
|
1846
|
+
name: typeof item.name === "string" && item.name !== "" ? item.name : String(item.identifier),
|
|
1847
|
+
...typeof item.logo === "string" ? { logo: item.logo } : {},
|
|
1848
|
+
credentials: item.credentials && typeof item.credentials === "object" && !Array.isArray(item.credentials) ? item.credentials : {},
|
|
1849
|
+
enabled: item.enabled !== false
|
|
1850
|
+
}));
|
|
1851
|
+
}
|
|
1852
|
+
export {
|
|
1853
|
+
CUSTOMER_ERRORS,
|
|
1854
|
+
DEFAULT_ADMIN_ALLOW,
|
|
1855
|
+
LOOKUP_ERROR,
|
|
1856
|
+
MemoryStateStore,
|
|
1857
|
+
OWN_FLEET,
|
|
1858
|
+
PUBLIC_ACTIONS,
|
|
1859
|
+
STAFF_ADMIN_ALLOW,
|
|
1860
|
+
STAFF_ONLY,
|
|
1861
|
+
adminMayRun,
|
|
1862
|
+
createAdminHandler,
|
|
1863
|
+
createPublicHandler,
|
|
1864
|
+
readSuppliersFromEnv
|
|
1865
|
+
};
|