-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
431 lines (385 loc) · 16.1 KB
/
Copy pathserver.ts
File metadata and controls
431 lines (385 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import express from "express";
import path from "path";
import fs from "fs";
import { createServer as createViteServer } from "vite";
import { GoogleGenAI } from "@google/genai";
const app = express();
const PORT = 3000;
// Body parser middleware (support large base64 uploads for license/medical cards)
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
// Express JSON Error Handler for body-parser or payload size limits
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
if (err) {
console.error("[Express Error Middleware]:", err.message || err);
return res.status(err.status || 400).json({
success: false,
error: err.message || "Failed to process uploaded file or request payload."
});
}
next();
});
// Initialize Gemini Client safely
let ai: GoogleGenAI | null = null;
function getGeminiClient(): GoogleGenAI {
if (!ai) {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.warn("GEMINI_API_KEY is not configured yet. AI features will respond with fallback mode.");
}
ai = new GoogleGenAI({
apiKey: apiKey || "dummy-key-for-init",
httpOptions: {
headers: {
"User-Agent": "aistudio-build",
},
},
});
}
return ai;
}
// Data persistence setup
const DATA_DIR = path.join(process.cwd(), "data");
const APPLICATIONS_FILE = path.join(DATA_DIR, "applications.json");
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
// Initial Sample Data for Recruiter CRM
const initialApplications = [
{
id: "CDL-2026-1001",
submittedAt: new Date(Date.now() - 3600000 * 2).toISOString(),
firstName: "Marcus",
lastName: "Vance",
email: "m.vance.driver@example.com",
phone: "(312) 555-0198",
cdlClass: "Class A",
licenseState: "IL",
licenseNumber: "V123-4567-8910",
licenseExpiration: "2028-09-15",
endorsements: ["Hazmat (H)", "Tanker (N)", "Doubles/Triples (T)"],
experienceYears: "7-10",
routePreference: "Regional Dedicated",
violationsLast3Years: "None",
status: "Under Review",
recruiterNotes: "Solid candidate with 8 yrs OTR & Hazmat. Called candidate, scheduled screening for tomorrow at 10 AM.",
licenseFront: "https://images.unsplash.com/photo-1589829545856-d10d557cf95f?auto=format&fit=crop&w=600&q=80",
licenseBack: "https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?auto=format&fit=crop&w=600&q=80",
medicalCardFront: "https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?auto=format&fit=crop&w=600&q=80",
medicalCardBack: "https://images.unsplash.com/photo-1584515979956-d9f6e5d09982?auto=format&fit=crop&w=600&q=80",
emailsDispatched: [
{
to: "recruiters@cdldriveragency.com",
subject: "[NEW CANDIDATE] Marcus Vance - Class A (Hazmat, Tanker)",
timestamp: new Date(Date.now() - 3600000 * 2).toISOString(),
},
{
to: "m.vance.driver@example.com",
subject: "Application Received - CDL Driver Agency Recruiting",
timestamp: new Date(Date.now() - 3600000 * 2).toISOString(),
}
]
},
{
id: "CDL-2026-1002",
submittedAt: new Date(Date.now() - 3600000 * 18).toISOString(),
firstName: "Carlos",
lastName: "Mendoza",
email: "carlos.m.trucking@example.com",
phone: "(214) 555-8832",
cdlClass: "Class A",
licenseState: "TX",
licenseNumber: "TX-9988112",
licenseExpiration: "2027-04-20",
endorsements: ["Tanker (N)", "Combination (X)"],
experienceYears: "5-7",
routePreference: "Solo OTR",
violationsLast3Years: "None",
status: "License Verified",
recruiterNotes: "CDL license and DOT medical card checked and verified. Ready for carrier match.",
licenseFront: "https://images.unsplash.com/photo-1589829545856-d10d557cf95f?auto=format&fit=crop&w=600&q=80",
licenseBack: "https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?auto=format&fit=crop&w=600&q=80",
medicalCardFront: "https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?auto=format&fit=crop&w=600&q=80",
medicalCardBack: "https://images.unsplash.com/photo-1584515979956-d9f6e5d09982?auto=format&fit=crop&w=600&q=80",
emailsDispatched: [
{
to: "recruiters@cdldriveragency.com",
subject: "[NEW CANDIDATE] Carlos Mendoza - Class A (Solo OTR)",
timestamp: new Date(Date.now() - 3600000 * 18).toISOString(),
}
]
},
{
id: "CDL-2026-1003",
submittedAt: new Date(Date.now() - 3600000 * 42).toISOString(),
firstName: "Dmitry",
lastName: "Kovalenko",
email: "dmitry.k@example.com",
phone: "(206) 555-4321",
cdlClass: "Class A",
licenseState: "WA",
licenseNumber: "WA-8831092",
licenseExpiration: "2029-01-10",
endorsements: ["Doubles/Triples (T)"],
experienceYears: "3-5",
routePreference: "Local Dedicated",
violationsLast3Years: "1 Speeding (10 mph over in 2024)",
status: "Interview Scheduled",
recruiterNotes: "Prefers Pacific Northwest local routes. Minor MVR speed violation cleared by carrier safety dept.",
licenseFront: "https://images.unsplash.com/photo-1589829545856-d10d557cf95f?auto=format&fit=crop&w=600&q=80",
licenseBack: "https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?auto=format&fit=crop&w=600&q=80",
medicalCardFront: "https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?auto=format&fit=crop&w=600&q=80",
medicalCardBack: "https://images.unsplash.com/photo-1584515979956-d9f6e5d09982?auto=format&fit=crop&w=600&q=80",
emailsDispatched: [
{
to: "recruiters@cdldriveragency.com",
subject: "[NEW CANDIDATE] Dmitry Kovalenko - Class A (Local Dedicated)",
timestamp: new Date(Date.now() - 3600000 * 42).toISOString(),
}
]
}
];
function readApplications() {
try {
if (!fs.existsSync(APPLICATIONS_FILE)) {
fs.writeFileSync(APPLICATIONS_FILE, JSON.stringify(initialApplications, null, 2));
return initialApplications;
}
const data = fs.readFileSync(APPLICATIONS_FILE, "utf-8");
return JSON.parse(data);
} catch (err) {
console.error("Error reading applications file:", err);
return initialApplications;
}
}
function writeApplications(apps: any[]) {
try {
fs.writeFileSync(APPLICATIONS_FILE, JSON.stringify(apps, null, 2));
} catch (err) {
console.error("Error writing applications file:", err);
}
}
// ---------------- API ENDPOINTS ----------------
// GET all applications for Recruiter CRM
app.get("/api/applications", (req, res) => {
const apps = readApplications();
res.json({ success: true, count: apps.length, applications: apps });
});
// POST submit new CDL driver application
app.post("/api/applications", (req, res) => {
try {
const {
firstName,
lastName,
email,
phone,
cdlClass,
licenseState,
licenseNumber,
licenseExpiration,
endorsements,
experienceYears,
routePreference,
violationsLast3Years,
licenseFront,
licenseBack,
medicalCardFront,
medicalCardBack,
additionalComments
} = req.body;
if (!firstName || !lastName || !email || !phone) {
return res.status(400).json({
success: false,
error: "First Name, Last Name, Email, and Phone are required."
});
}
const newId = `CDL-${new Date().getFullYear()}-${Math.floor(1000 + Math.random() * 9000)}`;
const now = new Date().toISOString();
const emailRecruiter = {
to: "MantasChicago36@Gmail.Com",
subject: `[URGENT NEW APPLICATION] ${firstName} ${lastName} - ${cdlClass || 'CDL Driver'} (${routePreference || 'General'})`,
timestamp: now,
contentPreview: `Candidate ${firstName} ${lastName} (${phone}, ${email}) submitted CDL application. License and Medical card documents attached.`
};
const emailCandidate = {
to: email,
subject: `Application Confirmation - CDL Driver Agency (Ref: ${newId})`,
timestamp: now,
contentPreview: `Dear ${firstName}, thank you for applying with CDL Driver Agency. A senior recruiter will review your CDL license and medical record card within 24 hours.`
};
const newApp = {
id: newId,
submittedAt: now,
firstName,
lastName,
email,
phone,
cdlClass: cdlClass || "Class A",
licenseState: licenseState || "Unspecified",
licenseNumber: licenseNumber || "Provided in uploads",
licenseExpiration: licenseExpiration || "2027-12-31",
endorsements: Array.isArray(endorsements) ? endorsements : [],
experienceYears: experienceYears || "1-3",
routePreference: routePreference || "Solo OTR",
violationsLast3Years: violationsLast3Years || "None",
additionalComments: additionalComments || "",
status: "New Applicant",
recruiterNotes: "Newly submitted application. CDL License & Medical Card uploaded. Pending recruiter audit.",
licenseFront: licenseFront || null,
licenseBack: licenseBack || null,
medicalCardFront: medicalCardFront || null,
medicalCardBack: medicalCardBack || null,
emailsDispatched: [emailRecruiter, emailCandidate]
};
const apps = readApplications();
apps.unshift(newApp);
writeApplications(apps);
console.log(`[CDL Driver Agency] New Application ${newId} saved and emails dispatched to recruiter & candidate.`);
res.status(201).json({
success: true,
message: "Application submitted successfully! Recruiter notification and CRM record created.",
applicationId: newId,
application: newApp
});
} catch (err: any) {
console.error("Error creating application:", err);
res.status(500).json({ success: false, error: err.message || "Failed to submit application." });
}
});
// PATCH update candidate status / notes
app.patch("/api/applications/:id", (req, res) => {
try {
const { id } = req.params;
const { status, recruiterNotes } = req.body;
const apps = readApplications();
const appIndex = apps.findIndex((a: any) => a.id === id);
if (appIndex === -1) {
return res.status(404).json({ success: false, error: "Application not found." });
}
if (status) apps[appIndex].status = status;
if (recruiterNotes !== undefined) apps[appIndex].recruiterNotes = recruiterNotes;
apps[appIndex].updatedAt = new Date().toISOString();
writeApplications(apps);
res.json({
success: true,
message: "Candidate application updated.",
application: apps[appIndex]
});
} catch (err: any) {
res.status(500).json({ success: false, error: err.message || "Failed to update candidate." });
}
});
// DELETE candidate application
app.delete("/api/applications/:id", (req, res) => {
try {
const { id } = req.params;
let apps = readApplications();
const initialLen = apps.length;
apps = apps.filter((a: any) => a.id !== id);
if (apps.length === initialLen) {
return res.status(404).json({ success: false, error: "Application not found." });
}
writeApplications(apps);
res.json({ success: true, message: `Application ${id} removed from CRM.` });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message || "Failed to delete candidate." });
}
});
// POST AI Support Chat endpoint (Gemini API server-side call)
app.post("/api/chat", async (req, res) => {
try {
const { message, language = "English", conversationHistory = [] } = req.body;
if (!message) {
return res.status(400).json({ success: false, error: "Message prompt is required." });
}
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
// Fallback helpful response when API key is not yet set up
return res.json({
success: true,
reply: `Thank you for reaching out to CDL Driver Agency! I am your AI Recruiter Assistant. I can answer questions about CDL Class A/B jobs, CPM pay ($0.65 - $0.85/mi), required documents (CDL license front/back & DOT medical card), and help you complete your application. (Language selected: ${language}). Please submit your application using our form on this page or ask me any question!`,
source: "fallback"
});
}
const genAI = getGeminiClient();
const systemInstruction = `You are "FleetAssist AI", the official 24/7 AI Recruiter and Candidate Support Assistant for "CDL Driver Agency".
Your goal is to assist CDL truck drivers, answer questions in real time, guide them through uploading their valid CDL Driver's License (front & back) and Medical Record Card, and explain job opportunities.
Agency Key Info:
- Company Name: CDL Driver Agency
- Recruiter Direct Phone: (312) 385-9229
- Recruiter Direct Email: MantasChicago36@Gmail.Com
- Target Drivers: Class A, Class B, Class C CDL drivers across the USA (OTR, Regional, Local Dedicated, Team, Owner Operators).
- Top Benefits:
* Pay Rates: $0.65 - $0.85 CPM for Solo OTR ($1,500 - $2,200+/week), $0.78 - $0.92 CPM for Team OTR ($3,500 - $4,800+/week team), Local $28 - $36/hour.
* Sign-On Bonuses: $3,000 to $5,000 depending on endorsements (Hazmat & Tanker get higher rates!).
* Equipment: Late-model 2023-2026 Freightliner Cascadia, Kenworth T680, Peterbilt 579, Volvo VNL with APUs, inverters, fridges, and automatic transmissions.
* Home Time: OTR (weekly/bi-weekly), Regional (home weekly), Local (home daily).
* Medical/Dental/Vision, 401(k) match, paid orientation ($500-$1,000), rider and pet policies available.
- Requirements for Drivers:
* Valid Commercial Driver's License (CDL Class A or B).
* Valid DOT Medical Examiner's Card (Medical Record Card).
* Clean Driving Record (MVR) or manageable minor violations.
* Willingness to upload clear photos of BOTH sides of valid CDL License and Medical Card.
Multi-language Requirement:
- Current Candidate Selected Language: "${language}".
- IMPORTANT: You MUST reply politely, professionally, and clearly in the candidate's selected language (${language}), while maintaining a warm, supportive, recruiter-focused tone.
- If the candidate speaks in Spanish, Polish, Ukrainian, Russian, Punjabi, or English, converse fluently in that language.
- Format responses nicely with bullet points and bold headers when helpful. Keep answers clear and concise.`;
// Construct prompt with system instruction and history
const contents: any[] = [];
// Format conversation history
if (Array.isArray(conversationHistory) && conversationHistory.length > 0) {
conversationHistory.slice(-6).forEach((item: any) => {
contents.push({
role: item.role === "user" ? "user" : "model",
parts: [{ text: item.text }]
});
});
}
contents.push({
role: "user",
parts: [{ text: `Candidate Language: ${language}\nCandidate Message: ${message}` }]
});
const response = await genAI.models.generateContent({
model: "gemini-3.6-flash",
contents: contents,
config: {
systemInstruction: systemInstruction,
temperature: 0.7,
}
});
const reply = response.text || "Thank you for contacting CDL Driver Agency. How else can I assist your trucking career today?";
res.json({
success: true,
reply: reply,
source: "gemini"
});
} catch (err: any) {
console.error("Gemini Chat Error:", err);
res.json({
success: true,
reply: `Thank you for contacting CDL Driver Agency! I am here to help you apply for CDL Class A/B driving jobs ($0.65-$0.85/mi, $3,000 sign-on bonus) and guide you through uploading your CDL license and DOT medical card. Please feel free to fill out the form or ask any questions!`,
source: "error-fallback"
});
}
});
// ---------------- VITE & SERVER BOOT ----------------
async function startServer() {
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), "dist");
app.use(express.static(distPath));
app.get("*all", (req, res) => {
res.sendFile(path.join(distPath, "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`CDL Driver Agency server running on http://0.0.0.0:${PORT}`);
});
}
startServer();