-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
393 lines (341 loc) · 11.3 KB
/
server.js
File metadata and controls
393 lines (341 loc) · 11.3 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
const express = require("express");
const multer = require("multer");
const csv = require("csv-parser");
const path = require("path");
const {
analyzeRfp,
extractLineItems,
chooseBestSku,
generateProposalHtml,
} = require("./ai");
const puppeteer = require("puppeteer-core");
const chromium = require("@sparticuz/chromium");
const HTMLtoDOCX = require("html-to-docx");
const app = express();
// Use memory storage for Vercel (ephemeral FS)
const upload = multer({ storage: multer.memoryStorage() });
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
// -- MANUAL CORS MIDDLEWARE --
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*"); // Allow any origin
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
// Handle preflight
if (req.method === "OPTIONS") {
return res.sendStatus(200);
}
next();
});
// --- IN-MEMORY DATA ---
let skus = []; // { id, skuCode, name, description, category, baseCost }
let rfps = []; // { id, ...data }
// Explicitly serve index.html for root to avoid "Cannot GET /"
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// --- API ENDPOINTS ---
// 0. Health Check (Debug Vercel Env Vars)
app.get("/api/health", (req, res) => {
res.json({
status: "ok",
timestamp: new Date().toISOString(),
groqConfigured: !!process.env.GROQ_API_KEY, // true if key exists
env: process.env.NODE_ENV || "development",
});
});
// 1. Upload SKU CSV
// 1. Upload SKU CSV
app.post("/api/skus/upload-csv", upload.single("file"), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: "No file uploaded" });
}
const results = [];
// Stream from buffer since we are using memory storage
const bufferStream = new require("stream").PassThrough();
bufferStream.end(req.file.buffer);
bufferStream
.pipe(csv())
.on("data", (data) => {
// Map CSV columns to our schema (handle loose naming)
const sku = {
id: Date.now().toString() + Math.random().toString(36).substr(2, 5),
skuCode: data.skuCode || data["SKU Code"] || data.id || "UNKNOWN",
name: data.name || data["Name"] || data["Product Name"] || "",
description: data.description || data["Description"] || "",
category: data.category || data["Category"] || "",
baseCost: parseFloat(
data.baseCost || data["Base Cost"] || data["Cost"] || 0
),
};
results.push(sku);
})
.on("end", () => {
skus = results;
res.json({
message: `Successfully loaded ${skus.length} SKUs`,
count: skus.length,
});
})
.on("error", (err) => {
console.error(err);
res.status(500).json({ error: "Failed to process CSV" });
});
});
// 2. Analyze RFP Text
app.post("/api/rfp/analyze", async (req, res) => {
try {
const { rfpText } = req.body;
if (!rfpText)
return res.status(400).json({ error: "No RFP text provided" });
// 1. Analyze high-level details
const details = await analyzeRfp(rfpText);
// 2. Extract line items
const rawLineItems = await extractLineItems(rfpText);
// Create new RFP object
const rfpId = Date.now().toString();
const newRfp = {
id: rfpId,
...details,
rawText: rfpText,
lineItems: rawLineItems.map((item, index) => ({
id: `${rfpId}-L${index}`,
...item,
matchedSkuId: null,
matchConfidence: null,
unitPrice: null,
totalPrice: null,
})),
};
rfps.push(newRfp);
res.json(newRfp);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Analysis failed" });
}
});
// --- HELPERS ---
function tokenize(text) {
return (text || "").toLowerCase().match(/[a-z0-9]+/g) || [];
}
function getSkuCandidatesForText(text, limit = 5) {
const tokens = new Set(tokenize(text));
if (tokens.size === 0) return skus.slice(0, limit);
const scored = skus.map((sku) => {
const skuTokens = tokenize(
`${sku.name} ${sku.description} ${sku.category} ${sku.packSize}`
);
let score = 0;
skuTokens.forEach((t) => {
if (tokens.has(t)) score++;
});
return { sku, score };
});
// Sort by score desc
scored.sort((a, b) => b.score - a.score);
// Filter those with at least 1 match, or fallback to generic top list if strictness is too high
// But for now, let's return top scorers even if score is low, to valid "no match"
// Better: only return score > 0. If none, return empty (so AI says "no match") or return generic?
// AI needs candidates to "reject". If we send nothing, it can't choose.
// So let's send top `limit` regardless, but useful ones first.
return scored.slice(0, limit).map((s) => s.sku);
}
// 3. Match SKUs for an RFP
app.post("/api/rfp/:id/match", async (req, res) => {
try {
const rfpId = req.params.id;
const rfp = rfps.find((r) => r.id === rfpId);
if (!rfp) return res.status(404).json({ error: "RFP not found" });
// Parallel matching
const tasks = rfp.lineItems.map(async (item) => {
// 1. Get Candidates
const candidates = getSkuCandidatesForText(item.description, 5);
// 2. Call AI
const matchResult = await chooseBestSku(item, candidates);
// 3. Update Item
if (matchResult.chosenSkuCode) {
const sku = skus.find((s) => s.skuCode === matchResult.chosenSkuCode);
if (sku) {
item.matchedSkuId = sku.id;
item.matchedSku = sku; // Persist for frontend
item.matchConfidence = matchResult.confidence;
item.rationale = matchResult.rationale;
} else {
// AI picked a code that doesn't exist (shouldn't happen with strict prompt)
item.matchedSkuId = null;
item.matchedSku = null;
}
} else {
item.matchedSkuId = null;
item.matchedSku = null;
}
return item;
});
await Promise.all(tasks);
// Return the updated RFP (or just line items)
res.json(rfp);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Matching failed" });
}
});
// 4. Generate Proposal
app.post("/api/rfp/:id/generate", async (req, res) => {
try {
const { marginPercent = 20 } = req.body;
const rfp = rfps.find((r) => r.id === req.params.id);
if (!rfp) return res.status(404).json({ error: "RFP not found" });
// ENRICH DATA HERE (Prevent AI Hallucination)
const enrichedLineItems = rfp.lineItems.map((li) => {
const sku = skus.find((s) => s.id === li.matchedSkuId);
let finalUnitPrice = null;
let finalTotalPrice = null;
let skuCode = null;
let skuName = null;
if (sku) {
skuCode = sku.skuCode;
skuName = sku.name;
const cost = sku.baseCost;
const price = cost * (1 + marginPercent / 100);
const qty = li.quantity || 1;
finalUnitPrice = price.toFixed(2);
finalTotalPrice = (price * qty).toFixed(2);
} else {
// Explicitly null if no match, so AI sees it's missing
finalUnitPrice = null;
finalTotalPrice = null;
}
return {
description: li.description,
quantity: li.quantity,
unit: li.unit,
notes: li.notes,
skuCode: skuCode,
skuName: skuName,
unitPrice: finalUnitPrice,
totalPrice: finalTotalPrice,
};
});
const html = await generateProposalHtml(
{
id: rfp.id,
name: rfp.name,
buyerName: rfp.buyerName,
deadline: rfp.deadline,
summary: rfp.summary,
keyRequirements: rfp.keyRequirements,
},
enrichedLineItems,
marginPercent
);
rfp.proposalHtml = html;
res.json({ html });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Generation failed" });
}
});
// 5. Download PDF
app.post("/api/rfp/:id/download/pdf", async (req, res) => {
try {
const rfp = rfps.find((r) => r.id === req.params.id);
if (!rfp || !rfp.proposalHtml) {
console.error(
"PDF Download: RFP not found or no HTML for ID:",
req.params.id
);
return res.status(404).json({ error: "Proposal not found" });
}
console.log(
`Generating PDF for RFP ${rfp.id}. HTML length: ${rfp.proposalHtml.length}`
);
// Wrap in standard HTML for better rendering
const fullHtml = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; }
th { background-color: #f4f4f4; text-align: left; }
</style>
</head>
<body>
${rfp.proposalHtml}
</body>
</html>
`;
const browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath(),
headless: chromium.headless,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setContent(fullHtml, { waitUntil: "networkidle0" });
const pdfBuffer = await page.pdf({
format: "A4",
printBackground: true,
margin: { top: "20px", bottom: "20px" },
});
await browser.close();
console.log(`PDF Generated. Size: ${pdfBuffer.length} bytes`);
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
`attachment; filename=proposal-${rfp.id}.pdf`
);
res.send(pdfBuffer);
} catch (error) {
console.error("PDF Generation Error:", error);
res.status(500).json({ error: "PDF generation failed" });
}
});
// 6. Download DOCX
app.post("/api/rfp/:id/download/docx", async (req, res) => {
try {
const rfp = rfps.find((r) => r.id === req.params.id);
if (!rfp || !rfp.proposalHtml) {
console.error(
"DOCX Download: RFP not found or no HTML for ID:",
req.params.id
);
return res.status(404).json({ error: "Proposal not found" });
}
console.log(
`Generating DOCX for RFP ${rfp.id}. HTML length: ${rfp.proposalHtml.length}`
);
// Wrap in standard HTML structure for DOCX
const fullHtml = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${rfp.proposalHtml}</body></html>`;
// Generate DOCX Buffer (Node.js compatible)
const docxBuffer = await HTMLtoDOCX(fullHtml, null, {
table: { row: { cantSplit: true } },
footer: true,
pageNumber: true,
});
console.log(`DOCX Generated. Size: ${docxBuffer.length} bytes`);
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
);
res.setHeader(
"Content-Disposition",
`attachment; filename=proposal-${rfp.id}.docx`
);
res.send(docxBuffer);
} catch (error) {
console.error("DOCX Generation Error:", error);
res.status(500).json({ error: "DOCX generation failed" });
}
});
const PORT = process.env.PORT || 3000;
// Only listen if run directly (local dev), NOT when imported by Vercel
if (require.main === module) {
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
}
module.exports = app;