Spaces:
Paused
Paused
Download src/services/aiService.js from ismizo/tenderizer: direct link, hf CLI and curl.
- Browser
- Download file 59.3 kB
-
https://huggingface.co/spaces/ismizo/tenderizer/resolve/main/src/services/aiService.js
- Command line
-
hf download hf://spaces/ismizo/tenderizer/src/services/aiService.js
-
curl -L -o aiService.js https://huggingface.co/spaces/ismizo/tenderizer/resolve/main/src/services/aiService.js
59.3 kB
import { GoogleGenerativeAI } from '@google/generative-ai';
import { getFileObject } from '../utils/storageUtils.js';
import * as cheerio from 'cheerio';
import { convertToPdf } from '../utils/docConverter.js';
// Initialize Gemini
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
export const quickModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });
export const powerfulModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });
// βββ DIAGRAM / DRAWING INTELLIGENCE ββββββββββββββββββββββββββββββββββββββββ
/**
* Keywords that trigger full A4 architectural/technical drawing mode.
*/
const ARCH_DRAWING_KEYWORDS = [
'architectural drawing', 'floor plan', 'site plan', 'structural drawing',
'elevation drawing', 'section drawing', 'building plan', 'layout plan',
'construction drawing', 'civil drawing', 'electrical layout', 'plumbing layout',
'landscape plan', 'master plan', 'plot plan', 'foundation plan'
];
/**
* Analyses a plan item and tender context to determine diagram needs.
* Returns { needsSvg, needs3d, isArchitecturalDrawing }
*/
const detectDiagramNeeds = (planItem, tender) => {
const text = [
planItem.docName || '',
planItem.purpose || '',
(planItem.outline?.sections || []).join(' '),
(planItem.outline?.keyPoints || []).join(' '),
tender?.analysis?.announcementType || '',
tender?.userPrompt || ''
].join(' ').toLowerCase();
const isArchitecturalDrawing = ARCH_DRAWING_KEYWORDS.some(kw => text.includes(kw));
const needsSvg = isArchitecturalDrawing || [
'org chart', 'organisational chart', 'organizational chart', 'organogram',
'gantt', 'timeline', 'work plan', 'schedule', 'flowchart', 'process flow',
'workflow', 'methodology diagram', 'logical framework', 'logframe',
'results framework', 'theory of change', 'network diagram',
'site layout', 'infrastructure', 'system architecture', 'data flow'
].some(kw => text.includes(kw));
const needs3d = isArchitecturalDrawing || [
'3d model', 'three-dimensional', 'perspective view', 'isometric',
'building model', 'structural model', '3d render'
].some(kw => text.includes(kw));
return { needsSvg, needs3d, isArchitecturalDrawing };
};
/**
* The Three.js importmap injected into every generated document <head>.
* Allows AI-generated <script type="module"> blocks to import from 'three'.
*/
const THREE_IMPORTMAP = `
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.165.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.165.0/examples/jsm/"
}
}
</script>`;
/**
* Extra CSS injected into every generated document for diagrams/drawings.
*/
const DIAGRAM_CSS = `
/* ββ Diagram / Drawing Styles ββ */
.diagram-block { margin: 28px 0; text-align: center; }
.diagram-block svg { max-width: 100%; height: auto; border: 1px solid #e2e8f0; border-radius: 4px; background: #fff; }
.diagram-block figcaption { font-size: 12px; color: #718096; margin-top: 6px; font-style: italic; }
.three-canvas-wrap { margin: 28px 0; }
.three-canvas-wrap canvas { width: 100% !important; max-width: 800px; height: 420px !important; border: 1px solid #e2e8f0; border-radius: 4px; display: block; margin: 0 auto; }
/* A4 Architectural Drawing */
.a4-drawing-page { width: 210mm; min-height: 297mm; margin: 20px auto; background: white; border: 1px solid #ccc; box-shadow: 0 4px 24px rgba(0,0,0,0.12); position: relative; padding: 0; }
.a4-drawing-page svg { width: 210mm; height: 297mm; display: block; }
@media print {
body { background: white !important; }
.page { box-shadow: none !important; margin: 0 !important; padding: 10mm !important; max-width: 100% !important; }
.a4-drawing-page { box-shadow: none; margin: 0; border: none; }
@page { size: A4 portrait; margin: 8mm; }
}`;
/**
* Pre-print hook script: converts Three.js canvases to static images before printing.
*/
const PRINT_HOOK_SCRIPT = `
<script>
window.addEventListener('beforeprint', () => {
document.querySelectorAll('canvas[data-threejs]').forEach(canvas => {
const img = document.createElement('img');
img.src = canvas.toDataURL('image/png');
img.style.cssText = canvas.style.cssText;
img.style.maxWidth = '100%';
canvas.parentNode.insertBefore(img, canvas);
canvas.style.display = 'none';
canvas._printImg = img;
});
});
window.addEventListener('afterprint', () => {
document.querySelectorAll('canvas[data-threejs]').forEach(canvas => {
if (canvas._printImg) { canvas._printImg.remove(); canvas.style.display = ''; }
});
});
</script>`;
// Helper to convert R2 Stream to Buffer (for Gemini)
const streamToBuffer = async (stream) => {
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
};
/**
* Label an uploaded file using AI β called immediately after upload.
* Returns { label, description, documentCategory, detectedCompanyName }
* documentCategory: 'call' (RFP/TOR/EOI/bid docs) | 'company' (applicant docs) | 'other'
*/
export const labelUploadedFile = async (fileBuffer, mimeType, originalName) => {
try {
let currentBuffer = fileBuffer;
let currentMimeType = mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
originalName.endsWith('.docx') || originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${originalName} to PDF for Gemini labeling...`);
currentBuffer = await convertToPdf(currentBuffer, currentMimeType, originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${originalName}, passing original. Error:`, err);
}
}
const prompt = `
TASK: Analyze this document and classify it for a tender/proposal management system.
Original filename: "${originalName}"
Determine ALL of the following:
1. A short TYPE label (e.g. "Call Document - RFP", "Terms of Reference", "EOI Announcement", "Bid Form / Template",
"Company Profile", "CV - [Person Name]", "Past Project Report", "Financial Statement", "Registration Certificate",
"Tax Certificate", "Audited Accounts", "Authorization Letter", "Technical Specification", "Company Brochure", etc.)
2. A 1-3 sentence description of the content.
3. Whether this is a CALL document or a COMPANY document:
- "call" = Documents FROM the procuring entity: RFP, RFQ, EOI, TOR, Tender Notice, Invitation to Bid, Bid Forms,
Mandatory Templates, Blank Forms, Evaluation Criteria documents, Addenda, Clarifications
- "company" = Documents BELONGING TO the applicant/bidder: Company Profile, CVs, Past Project Reports,
Financial Statements, Bank Statements, Audited Accounts, Registration Certificates, Tax Clearance,
Business Licenses, Authorization Letters, References, Company Brochures, Capability Statements,
Staff Qualifications, Insurance Certificates, Past applications and proposals
- "other" = anything that doesn't clearly fit either category
4. If it is a "company" document, try to detect the company/organization name from its content (or null if not found).
Return ONLY a valid JSON object, no markdown:
{
"label": "Short type label",
"description": "1-2 sentence summary",
"documentCategory": "call" | "company" | "other",
"detectedCompanyName": "Company Name Ltd" | null
}
`;
const result = await quickModel.generateContent([
prompt,
{ inlineData: { data: currentBuffer.toString('base64'), mimeType: currentMimeType } }
]);
let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
const parsed = JSON.parse(text);
return {
label: parsed.label || 'Uploaded Document',
description: parsed.description || '',
documentCategory: ['call', 'company', 'other'].includes(parsed.documentCategory) ? parsed.documentCategory : 'other',
detectedCompanyName: parsed.detectedCompanyName || null
};
} catch (error) {
console.warn('File labeling failed for', originalName, ':', error.message);
return { label: 'Uploaded Document', description: '', documentCategory: 'other', detectedCompanyName: null };
}
};
/**
* STEP 1: Deep analysis of the announcement documents.
* Determines type, extracts requirements, detects MISSING documents (templates/forms),
* and generates strategy questions.
*/
export const analyzeDocuments = async (files, userPrompt = '', promptOnly = false) => {
try {
// ββ PROMPT-ONLY MODE: No documents uploaded β use user description alone ββ
if (promptOnly || files.length === 0) {
const promptOnlyInstruction = `
I need your help to draft a document as described below:
USER DESCRIPTION:
${userPrompt || 'No description provided.'}
ATTACHED DOCUMENTS:
Please also review any attached documents to understand the context. The user may have attached documents they want you to work on or reference.
Based on this description and the attached documents:
TASK 1 - DETERMINE DOCUMENT TYPE:
Identify the type of document/proposal the user wants to create (e.g. "Company Profile", "Technical Proposal for IT Consultancy", "Grant Proposal for Youth Program", "Cover Letter", "Business Plan", etc.).
TASK 2 - GENERATE STRATEGY QUESTIONS:
Generate 4-6 targeted clarifying questions to gather the information needed to draft a high-quality, detailed version of this document. Focus on specific content, data, and evidence needed. DO NOT ask for information that is already clearly provided in the attached documents or the user description.
Return STRICTLY valid JSON (no markdown, no wrapping, just raw JSON):
{
"announcement_type": "Type of document to be drafted (e.g. 'Company Profile', 'Technical Proposal')",
"summary": "3-4 sentence summary describing exactly what document will be created and its purpose, incorporating insights from the attached documents if any.",
"is_complete": true,
"missing_documents": [],
"authority_documents": [],
"strategy_questions": [
"Specific question 1 to gather key content not found in the documents",
"Specific question 2",
"Specific question 3",
"Specific question 4"
]
}
`;
const aiInputs = [promptOnlyInstruction];
if (files && files.length > 0) {
for (const file of files) {
console.log(`Fetching ${file.originalName} from R2 (Prompt-Only Mode)...`);
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${file.originalName} to PDF for Gemini analysis (Prompt-Only)...`);
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({
inlineData: {
data: buffer.toString('base64'),
mimeType: currentMimeType
}
});
}
}
const result = await quickModel.generateContent(aiInputs);
let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
return JSON.parse(text);
}
// ββ STANDARD MODE: Analyze uploaded documents ββ
const prompt = `
I need your help to analyze the uploaded documents and help me draft response documents to the call/EOI/Grant/Tender, etc. in question.
Please thoroughly read and analyze the attached announcement documents (which may be an RFP, EOI, Call for Proposals, Grant Application, Tender Notice, Expression of Interest, TOR, or similar).
CUSTOM CONTEXT / INSTRUCTIONS (pay close attention):
${userPrompt ? userPrompt : "None provided."}
TASK 1 - IDENTIFY THE ANNOUNCEMENT TYPE:
First, please determine exactly what type of competitive announcement this is. Be specific (e.g., "Restricted Tender for Supply of Medical Equipment", "Open Call for EOI for IT Consultancy Services", "Grant Application for Youth Empowerment Program").
TASK 2 - DEEP DOCUMENT REVIEW:
Read all documents meticulously. Understand the evaluation criteria, scope of work, qualification requirements, format requirements, mandatory forms, and special instructions from any TOR or similar documents.
CRITICAL: If any uploaded call document contains an APPLICATION FORM, TEMPLATE, or SPECIFIC FORMAT requirements β note them exactly. All drafted documents MUST follow those templates/forms if provided, exactly.
TASK 3 - IDENTIFY MISSING DOCUMENTS:
Check if the applicant has provided ALL necessary documents from the announcement itself. Specifically look for:
- Required templates (e.g., "Please use the attached Budget Template", "Fill in Form A")
- Mandatory forms referenced in the RFP but not attached
- Technical specifications or addenda that should accompany the main document
- Reference letters format, CV templates, company profile templates specified by the issuer
Only list documents that are explicitly REQUIRED by the announcement and appear to be missing from the uploaded set.
TASK 4 - AUTHORITY DOCUMENTS:
List documents the applicant must obtain from external sources (Tax Clearance, Business Registration, Audited Financials, etc.).
TASK 5 - STRATEGY QUESTIONS:
Generate 4-6 high-impact strategy questions to build a winning proposal. Focus on the applicant's unique strengths, measurable past performance, team qualifications, and how they align with the evaluator's priorities. Do NOT ask for generic info like company name.
Return STRICTLY valid JSON (no markdown, no wrapping, just raw JSON):
{
"announcement_type": "Specific type of announcement (e.g. Open Tender - Supply of Laboratory Equipment)",
"summary": "Detailed 3-4 sentence summary covering: what is needed, who is the issuer, key deadlines/requirements, and evaluation focus.",
"is_complete": boolean,
"missing_documents": ["Only documents REQUIRED by the announcement that are not in the uploaded set, e.g. 'Budget Template Form B (referenced on page 4 of TOR)'"],
"authority_documents": ["Documents applicant must obtain externally, e.g. 'Valid Tax Clearance Certificate'"],
"strategy_questions": [
"Question 1 focused on demonstrating relevant past experience with measurable outcomes",
"Question 2 focused on technical approach or methodology",
"Question 3 focused on team qualifications and capacity",
"Question 4 focused on unique value proposition vs competitors",
"Question 5 focused on local presence or partnerships if applicable"
]
}
`;
// 1. Fetch files from R2 and format for Gemini
const aiInputs = [prompt];
for (const file of files) {
console.log(`Fetching ${file.originalName} from R2...`);
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${file.originalName} to PDF for Gemini analysis...`);
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({
inlineData: {
data: buffer.toString('base64'),
mimeType: currentMimeType
}
});
}
console.log("Sending to Gemini for deep analysis...");
const result = await powerfulModel.generateContent(aiInputs);
const response = result.response;
let text = response.text();
// Cleanup JSON
text = text.replace(/```json/g, '').replace(/```/g, '').trim();
return JSON.parse(text);
} catch (error) {
console.error("AI Analysis Error:", error);
throw new Error("Failed to analyze documents");
}
};
/**
* STEP 2: Generate a detailed drafting plan with section-level outlines.
* References the announcement instructions (TOR, evaluation criteria) to determine
* exactly what documents and structure are needed.
*/
export const generateDraftingPlan = async (tenderSummary, announcementType, requirements, questions, answers, files) => {
try {
let qaContext = "";
questions.forEach((q, i) => {
qaContext += `Q: ${q.question}\nA: ${answers[i]}\n\n`;
});
const prompt = `
I need your help to analyze the uploaded documents and help me draft a response documents writing plan to the call/EOI/Grant/Tender, etc. in question.
ANNOUNCEMENT TYPE: ${announcementType}
ANNOUNCEMENT SUMMARY: ${tenderSummary}
REQUIREMENTS & AUTHORITY DOCS: ${JSON.stringify(requirements)}
APPLICANT STRATEGY (their answers):
${qaContext}
TASK:
Based on the announcement type, requirements, and the applicant's strategy, please create a COMPREHENSIVE, DETAILED drafting plan for ALL documents that need to be created to submit a winning, compliant proposal.
CRITICAL RULES:
1. TEMPLATE/FORM ADHERENCE IS THE HIGHEST PRIORITY. If any call document contains an application form, a template, or explicit format instructions, ALL drafted documents MUST mirror that exact structure β use the same headings, same section order, same table formats, same field names. Do not invent your own section ordering if the announcement specifies one.
2. Follow the announcement's format instructions STRICTLY. If the TOR says "Technical Proposal must have: Executive Summary, Methodology, Team CVs, Work Plan" β use exactly those sections in exactly that order.
3. If a blank application form is uploaded, treat each form field as a required section in the drafting plan.
4. For each document, provide a DETAILED outline with specific sections, estimated paragraph count, and key points to cover.
5. Break large documents (anything over 3 pages should be a separate document section) into parts using this EXACT syntax: "Technical Proposal - Executive Summary - Part 1", "Technical Proposal - Methodology - Part 2" etc. so they can be merged.
6. Do NOT include documents the applicant must obtain themselves (like Tax Clearance). ONLY documents that require writing/drafting.
7. Each document section should be detailed enough for a writer to produce a complete, detailed, and professional draft.
8. Return a valid JSON array.
Output Format (strict JSON array):
[
{
"docName": "Document name using Part syntax if multi-part (e.g. Technical Proposal - Executive Summary & Methodology - Part 1)",
"purpose": "What this document/part covers and its role in the proposal",
"outline": {
"sections": [
"1. Executive Summary (2 paragraphs: project understanding + our value proposition)",
"2. Background & Context (1 paragraph: issuer context, 1 paragraph: problem statement)",
"3. Proposed Methodology (3-4 paragraphs covering each work stream)",
"4. Innovation & Differentiation (1 paragraph)"
],
"estimatedPages": 4,
"estimatedParagraphs": 9,
"keyPoints": [
"Highlight ${answers[0] ? answers[0].substring(0, 60) + '...' : 'applicant strengths'}",
"Use evaluation criteria language from the announcement",
"Reference specific requirements from the TOR"
]
}
}
]
`;
const aiInputs = [prompt];
if (files && files.length > 0) {
for (const file of files) {
try {
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({
inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType }
});
} catch (fileErr) {
console.warn(`Could not attach ${file.originalName}:`, fileErr.message);
}
}
}
const result = await powerfulModel.generateContent(aiInputs);
const response = result.response;
let text = response.text();
text = text.replace(/```json/g, '').replace(/```/g, '').trim();
return JSON.parse(text);
} catch (error) {
console.error("Plan Generation Error:", error);
throw new Error("Failed to generate drafting plan");
}
};
export const checkExistingDocuments = async (generatedPlan, uploadedFileNames) => {
try {
const prompt = `
You are a STRICT document matching assistant. Your job is to identify which AI-drafted document plans are ALREADY SATISFIED by an uploaded file.
CRITICAL RULES β err strongly on the side of NOT matching:
- Only mark a Required Document as satisfied if an uploaded file is CLEARLY and OBVIOUSLY the EXACT completed final version of that specific document.
- Call documents such as RFPs, TORs, EOIs, templates, blank forms, guidelines, requests, and announcements DO NOT satisfy any Required Document β they are input reference material.
- Reference documents, company profiles, CVs, and past work samples DO NOT satisfy a Required Document unless the Required Document is literally asking for that exact thing (e.g. Required Document = "Company Profile" and uploaded file = "Company_Profile.pdf").
- A required document that needs to be WRITTEN (e.g. Technical Proposal, Cover Letter, Methodology, Budget, Staffing Plan, Work Plan, Financial Proposal, Capability Statement) is NEVER satisfied by an uploaded reference file.
- When in doubt, DO NOT match. It is better to re-draft something than to silently skip it.
- ONLY match when the file name is an unmistakably direct match to the exact required document name AND the file is clearly the final completed version.
Required Documents (to be drafted by AI):
${JSON.stringify(generatedPlan.map(d => d.docName))}
Uploaded Files (reference material provided by user):
${JSON.stringify(uploadedFileNames)}
Please return a strictly valid JSON array of strings containing ONLY the Required Documents that are genuinely, obviously already completed in one of the uploaded files.
If nothing is clearly satisfied, please return an empty array [].
Do NOT include markdown formatting, just the raw JSON array.
`;
const result = await quickModel.generateContent(prompt);
let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
return JSON.parse(text);
} catch (error) {
console.error("Check Existing Docs Error:", error);
return []; // Safe default β draft everything
}
};
/**
* STEP 3: Generate document content using the detailed outline from the plan.
* Separates call docs (bid requirements) from company docs (applicant data).
* Only attaches company docs that match the tender's companyName, so a user
* working for multiple companies never mixes up their documents.
*/
export const generateDocumentContent = async (tender, planItem) => {
try {
// ββ Detect what kind of visual content this document needs ββ
const diagramFlags = detectDiagramNeeds(planItem, tender);
const { needsSvg, needs3d, isArchitecturalDrawing } = diagramFlags;
// Route architectural drawings to the specialist function
if (isArchitecturalDrawing) {
console.log(`π Architectural drawing detected: "${planItem.docName}" β using specialist generator`);
return await generateArchitecturalDrawing(tender, planItem);
}
let strategyContext = "";
tender.analysis.strategyQuestions.forEach(q => {
strategyContext += `Q: ${q.question}\nA: ${q.answer}\n\n`;
});
const outlineInstructions = planItem.outline ? `
DOCUMENT OUTLINE (follow this PRECISELY - do not deviate):
Sections to cover:
${planItem.outline.sections ? planItem.outline.sections.join('\n') : 'As appropriate for this document type'}
Target: ~${planItem.outline.estimatedPages || 2} pages, ~${planItem.outline.estimatedParagraphs || 6} paragraphs
Key Points to emphasize:
${planItem.outline.keyPoints ? planItem.outline.keyPoints.join('\n') : 'Based on applicant strategy'}
` : '';
// ββ Build diagram instructions to inject into the prompt ββ
let diagramInstructions = '';
if (needsSvg || needs3d) {
diagramInstructions = `
βββ DIAGRAM & VISUALISATION REQUIREMENTS βββ
This document requires visual diagrams. You MUST include them as described below.
The HTML wrapper already loads Three.js via importmap, so all script tags will work.
${needsSvg ? `SVG DIAGRAMS (REQUIRED):
- Where relevant (org charts, Gantt charts, process flows, timelines, work plans, site layouts, data flows),
embed DETAILED inline SVG diagrams directly in the HTML body.
- Wrap each in: <figure class="diagram-block"><svg viewBox="0 0 800 500" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:800px">...</svg><figcaption>Figure N: Description β Scale/Units if applicable</figcaption></figure>
- SVG must be FULLY DRAWN β no placeholder boxes. Include labels, axis ticks, arrows, legend if needed.
- Gantt charts: horizontal bars per task on a time axis with month labels.
- Org charts: rectangles connected by lines, with role titles and names.
- Flowcharts: rounded rects for steps, diamonds for decisions, arrows for flow.
- Use colours: header/title bars #2b6cb0, accents #38a169, gridlines #e2e8f0, text #1a202c.` : ''}
${needs3d ? `THREE.JS 3D VISUALISATION (include if it adds value β e.g. system architecture, building structure, infrastructure layout):
- Add a <div class="three-canvas-wrap"><canvas id="three-canvas" data-threejs></canvas></div> where appropriate.
- Follow it with a <script type="module"> that imports from 'three' (already in importmap).
- Build a simple but meaningful scene: e.g. OrbitControls-enabled isometric view of a building block or network node graph.
- Camera: orthographic or perspective. Lighting: AmbientLight + DirectionalLight. Background: 0xf0f4f8.
- Keep the script self-contained. Use THREE.BoxGeometry, MeshStandardMaterial, etc.
- CRITICAL FOR PDF EXPORT: When creating the WebGLRenderer, you MUST set preserveDrawingBuffer: true so the canvas can be captured as a PNG for PDF export:
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('three-canvas'), antialias: true, preserveDrawingBuffer: true });
- Example import: import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js';` : ''}
`;
}
// ββ File filtering: separate by category, filter company docs by company name ββ
const projectCompany = (tender.companyName || '').toLowerCase().trim();
const callDocs = [];
const companyDocs = [];
const otherDocs = [];
for (const file of (tender.inputFiles || [])) {
const cat = file.documentCategory || 'other';
if (cat === 'call') {
callDocs.push(file);
} else if (cat === 'company') {
// If project has a company name set, only include matching company docs
if (projectCompany) {
const fileCompany = (file.companyName || '').toLowerCase().trim();
const matches = !fileCompany ||
fileCompany.includes(projectCompany) ||
projectCompany.includes(fileCompany);
if (matches) companyDocs.push(file);
else console.log(`Skipping ${file.originalName} β belongs to "${file.companyName}", project is "${tender.companyName}"`);
} else {
companyDocs.push(file); // No filter if company not set
}
} else {
otherDocs.push(file);
}
}
const filesToUse = [...callDocs, ...companyDocs, ...otherDocs];
// Build file manifest for prompt
const callManifest = callDocs.map((f, i) => ` π’ ${i + 1}. [${f.aiLabel}] "${f.originalName}" β ${f.aiDescription || '(no description)'}`).join('\n');
const companyManifest = companyDocs.map((f, i) => ` π’ ${i + 1}. [${f.aiLabel}] "${f.originalName}" β ${f.aiDescription || '(no description)'}`).join('\n');
const otherManifest = otherDocs.map((f, i) => ` π ${i + 1}. [${f.aiLabel}] "${f.originalName}" β ${f.aiDescription || '(no description)'}`).join('\n');
const prompt = `
ROLE: Expert Proposal Writer with 20+ years of experience in ${tender.analysis.announcementType || 'competitive procurement'}.
TASK: Please write the COMPLETE, DETAILED content for: "${planItem.docName}"
PURPOSE: ${planItem.purpose || 'As specified by the announcement'}
βββ ANNOUNCEMENT CONTEXT βββ
Type: ${tender.analysis.announcementType || 'Tender/RFP'}
Title: ${tender.title}
Bidding Company: ${tender.companyName || '(see company documents)'}
Summary: ${tender.analysis.summary}
βββ APPLICANT STRATEGY (Q&A) βββ
${strategyContext}
βββ ATTACHED FILES βββ
The following documents are attached inline to this request:
π’ CALL / BID DOCUMENTS (from the procuring entity):
${callManifest || ' (none)'}
β Use these to understand: requirements, evaluation criteria, scoring rubrics, submission format, TOR instructions.
π’ COMPANY DOCUMENTS β ${tender.companyName || 'Applicant'} (belonging to the bidding company):
${companyManifest || ' (none)'}
β Extract REAL specific data from these: company name, registration number, directors, key staff names &
qualifications, specific past projects (names, locations, dates, contract values, outcomes), financial turnover,
certifications, licenses, client references.
${otherManifest ? `π OTHER DOCUMENTS:\n ${otherManifest}` : ''}
CRITICAL: Do NOT use generic placeholders if the real data exists in the attached documents.
Only use [COMPANY NAME], [AMOUNT], [DATE] etc. for data genuinely absent from all files.
${outlineInstructions}
WRITING RULES:
1. Write COMPLETE, professional, detailed content β not a generic template.
2. CRITICAL β TEMPLATE/FORM ADHERENCE: If a call document contains an application form or template, reproduce its structure EXACTLY. Use the same field/section names, same table columns, same ordering. Fill in every field or section from the company data and strategy Q&A.
3. Use the bidding company's actual data from the attached company documents (real names, real projects, real figures, real registration numbers).
4. Mirror the call document's terminology and evaluation criteria language throughout.
5. Use clear headings (h2, h3), well-developed paragraphs, semi-professional tone.
6. For budgets/schedules/BOQs use proper HTML tables with realistic but well-reasoned figures.
7. Use semantic HTML (NO <html>/<head>/<body> tags). You MAY use Tailwind CSS classes and Google Material Icons (<span class="material-icons">icon_name</span>) to create a beautiful, modern design, especially if the user requests a specific style.
8. Every section must be substantive with specific evidence, examples, and measurable outcomes β never leave placeholder text if real data is available.
9. CUSTOM FONTS: If the user requests a specific font, or if you choose to use a custom Google Font, you MUST include its \`<style>@import url('https://fonts.googleapis.com/css2?family=Font+Name&display=swap');</style>\` tag at the very top of your HTML output and apply it using inline styles or Tailwind classes.
${diagramInstructions}
`;
// Attach files inline to the AI request
const aiInputs = [prompt];
if (filesToUse.length > 0) {
console.log(`Attaching ${filesToUse.length} file(s) β ${callDocs.length} call, ${companyDocs.length} company, ${otherDocs.length} other`);
for (const file of filesToUse) {
try {
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${file.originalName} to PDF for Gemini generation...`);
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({
inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType }
});
} catch (fileErr) {
console.warn(`Could not attach ${file.originalName}:`, fileErr.message);
}
}
} else {
console.log('No input files to attach β generating from strategy context only.');
}
const result = await powerfulModel.generateContent(aiInputs);
let rawHtml = result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();
// WRAPPER: Full document with Three.js importmap + diagram CSS
const fullHtml = buildDocumentWrapper(planItem.docName, tender.title, tender.companyName, rawHtml, diagramFlags);
return fullHtml;
} catch (error) {
console.error(`Error generating ${planItem.docName}:`, error);
throw new Error("AI Generation Failed");
}
};
/**
* Builds the full self-contained HTML wrapper for a generated document.
* Always includes the Three.js importmap and diagram CSS so SVG/canvas
* content rendered by the AI works out-of-the-box in the iframe and prints correctly.
*/
const buildDocumentWrapper = (docName, tenderTitle, companyName, bodyContent, diagramFlags = {}) => {
const archClass = diagramFlags.isArchitecturalDrawing ? ' arch-drawing-doc' : '';
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${docName}</title>${THREE_IMPORTMAP}
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Merriweather:wght@400;700&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', sans-serif; background: #f4f5f7; color: #1a202c; line-height: 1.7; }
.page { max-width: 850px; margin: 30px auto; padding: 60px 70px; background: white; box-shadow: 0 4px 24px rgba(0,0,0,0.08); border-radius: 4px; }
h1 { font-family: 'Merriweather', serif; font-size: 24px; color: #1a365d; margin-bottom: 8px; padding-bottom: 16px; border-bottom: 3px solid #2b6cb0; }
h2 { font-family: 'Merriweather', serif; font-size: 18px; color: #2b6cb0; margin-top: 32px; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 1px solid #bee3f8; }
h3 { font-size: 15px; font-weight: 700; color: #2d3748; margin-top: 20px; margin-bottom: 8px; }
h4 { font-size: 14px; font-weight: 600; color: #4a5568; margin-top: 16px; margin-bottom: 6px; }
p { margin-bottom: 14px; font-size: 14px; text-align: justify; }
ul, ol { margin: 10px 0 14px 24px; font-size: 14px; }
li { margin-bottom: 6px; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }
thead { background: #2b6cb0; color: white; }
th { padding: 10px 12px; text-align: left; font-weight: 600; }
td { padding: 9px 12px; border-bottom: 1px solid #e2e8f0; }
tr:nth-child(even) { background: #f7fafc; }
strong { color: #2d3748; }
.doc-meta { font-size: 12px; color: #718096; margin-bottom: 30px; padding-bottom: 16px; border-bottom: 1px solid #e2e8f0; }
${DIAGRAM_CSS}
</style>
</head>
<body class="${archClass}">
<div class="page">
<h1>${docName}</h1>
<div class="doc-meta">Document for: ${tenderTitle} | Generated by ${companyName}</div>
${bodyContent}
</div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;
};
/**
* SPECIALIST: Generate a detailed A4-sized architectural / technical drawing.
* Called automatically when detectDiagramNeeds() flags isArchitecturalDrawing.
*/
export const generateArchitecturalDrawing = async (tender, planItem) => {
try {
let strategyContext = "";
(tender.analysis?.strategyQuestions || []).forEach(q => {
strategyContext += `Q: ${q.question}\nA: ${q.answer}\n\n`;
});
const prompt = `
ROLE: Professional Architectural Drafter β 20+ years technical drawing experience.
TASK: Produce a COMPLETE, DETAILED architectural/technical drawing for: "${planItem.docName}"
PURPOSE: ${planItem.purpose || 'Technical drawing as specified'}
PROJECT CONTEXT:
Project Title: ${tender.title}
Client/Company: ${tender.companyName || '[Company]'}
Announcement Type: ${tender.analysis?.announcementType || 'Construction/Design Project'}
STRATEGY CONTEXT:
${strategyContext || '(Infer from project title and purpose)'}
OUTPUT: Raw HTML content ONLY (no <html>/<head>/<body> wrapper tags).
The surrounding document already has Three.js loaded via importmap.
MANDATORY CONTENT:
1. MAIN SVG DRAWING β A4 proportions (viewBox="0 0 794 1123"):
- Outer border: <rect x="10" y="10" width="774" height="1103" fill="none" stroke="#1a202c" stroke-width="2"/>
- Inner margin line: <rect x="25" y="25" width="744" height="1068" fill="none" stroke="#1a202c" stroke-width="0.5"/>
2. TITLE BLOCK (inside SVG, at bottom ~y=1010 to y=1103):
Render as bordered cells with <rect> + <text>:
- "PROJECT:" ${tender.title}
- "DRAWING TITLE:" ${planItem.docName}
- "DRAWN BY:" ${tender.companyName || 'AI Drafter'}
- "DATE:" ${new Date().toLocaleDateString('en-GB')}
- "SCALE:" 1:100 (or as appropriate)
- "REV:" A "DWG NO:" DWG-001
3. MAIN DRAWING (SVG drawing area, y=25 to y=1005):
Draw a realistic, detailed plan appropriate for: "${planItem.docName}"
For FLOOR PLANS / BUILDING PLANS use:
- Walls: <line> or <rect> with stroke-width="5" stroke="#1a202c" β show actual room layout
- Windows: double parallel lines + centre gap + opening arc (stroke="#4a90d9" stroke-width="1.5")
- Doors: single line + quarter-circle arc showing swing direction
- Room labels: <text> centred in each room (font-family="Arial" font-size="11" fill="#2d3748")
- Grid reference bubbles at grid intersections (circles with A/B/C and 1/2/3 labels)
- Dimension lines: <line stroke="#e53e3e" stroke-width="0.7"> with tick marks + <text> measurements
- Hatching in wall thickness: <pattern> with diagonal lines or cross-hatch
For SITE PLANS use roads, plot boundaries, building footprints, vegetation symbols, north arrow.
For STRUCTURAL DRAWINGS use beam/column grid, member sizes annotated.
For ELECTRICAL LAYOUTS use socket/light symbols, circuit lines, distribution board.
4. NORTH ARROW (top-right, around x=720 y=80):
SVG north arrow: circle + arrow pointing up + "N" text label.
5. SCALE BAR (bottom-left of drawing area, around x=35 y=990):
Graphic bar: alternating black/white segments, labelled 0-5-10-20m.
6. THREE.JS 3D INSET (placed BELOW the SVG, outside the drawing frame):
<div class="three-canvas-wrap" style="padding:20px;text-align:center;background:#f7fafc;border-top:2px solid #e2e8f0;margin-top:0">
<p style="font-size:12px;color:#4a5568;margin-bottom:8px;font-family:Arial">📐 3D Perspective View — Interactive (Drag to Rotate)</p>
<canvas id="arch-3d-canvas" data-threejs style="width:100%;max-width:700px;height:360px;border:1px solid #d0d8e8;border-radius:4px"></canvas>
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// IMPORTANT: preserveDrawingBuffer MUST be true so canvas.toDataURL() works for PDF export.
// Create renderer like this:
// const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('arch-3d-canvas'), antialias: true, preserveDrawingBuffer: true });
// Build an appropriate 3D scene: walls extruded from floor plan, roof slab, columns.
// Materials: floor=0xd4c5a9, walls=0xe8e0d0, roof=0x8b7355, glass=0xa8d8f0.
// Add GridHelper, AmbientLight(0xffffff,0.6), DirectionalLight(0xffffff,0.8).
// OrbitControls for interactivity. Auto-resize on window resize.
// Isometric-style camera start: camera.position.set(15, 12, 15); camera.lookAt(0,0,0).
</script>
DRAWING QUALITY RULES:
- Every element must be drawn β no empty placeholders.
- All text must be legible (min 9px in SVG).
- Use colour coding: structure=#1a202c, annotations=#e53e3e, services=#4a90d9, vegetation=#38a169.
- Include a LEGEND box if using symbols.
- The Three.js script must be FULLY written and functional β not just pseudocode.
Output ONLY the HTML elements (SVG + Three.js div+script). No wrapper tags.
`;
const aiInputs = [prompt];
for (const file of (tender.inputFiles || [])) {
if (['call', 'other'].includes(file.documentCategory)) {
try {
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${file.originalName} to PDF for Gemini drawing...`);
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({ inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType } });
} catch (_) { /* skip unreadable */ }
}
}
const result = await powerfulModel.generateContent(aiInputs);
let rawHtml = result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${planItem.docName} β Technical Drawing</title>${THREE_IMPORTMAP}
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial, sans-serif; background: #dde1ea; }
.arch-header { text-align:center; padding: 14px 20px; font-size: 12px; color: #4a5568; background: #f7fafc; border-bottom: 1px solid #d0d8e8; display:flex; justify-content:space-between; align-items:center; }
.arch-header strong { color: #1a365d; font-size: 14px; }
.arch-header .note { font-size: 11px; color: #a0aec0; }
.drawing-container { width: 210mm; margin: 18px auto; background: white; box-shadow: 0 6px 32px rgba(0,0,0,0.22); border: 1px solid #b0b8c8; }
.drawing-container svg { display: block; width: 100%; height: auto; }
.three-canvas-wrap canvas { width: 100% !important; max-width: 700px; height: 360px !important; display: block; margin: 0 auto; }
@media print {
body { background: white !important; }
.arch-header { display: none; }
.drawing-container { box-shadow: none; margin: 0; border: none; width: 100%; }
.three-canvas-wrap { display: none; }
@page { size: A4 portrait; margin: 5mm; }
}
</style>
</head>
<body>
<div class="arch-header">
<strong>📐 ${planItem.docName}</strong>
<span>${tender.title} • ${tender.companyName || 'Technical Drawing'}</span>
<span class="note">3D view: drag to rotate • prints as line drawing only</span>
</div>
<div class="drawing-container">
${rawHtml}
</div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;
} catch (error) {
console.error(`Architectural drawing error for ${planItem.docName}:`, error);
throw new Error('Architectural drawing generation failed');
}
};
export const mergeHtmlParts = (htmlParts, title, companyName) => {
let combinedBodyContent = "";
htmlParts.forEach((html, index) => {
const $ = cheerio.load(html);
$('h1, h2, h3').each((i, el) => {
const text = $(el).text();
$(el).text(text.replace(/\s*-\s*Part\s*\d+/i, ''));
});
if (index > 0) {
$('.doc-meta').remove();
}
let content = $('.page').html();
if (!content) content = $('body').html();
combinedBodyContent += `\n<div class="merged-section mb-8">${content || ""}</div>\n`;
});
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>${THREE_IMPORTMAP}
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Merriweather:wght@400;700&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', sans-serif; background: #f4f5f7; color: #1a202c; line-height: 1.7; }
.page { max-width: 850px; margin: 30px auto; padding: 60px 70px; background: white; box-shadow: 0 4px 24px rgba(0,0,0,0.08); border-radius: 4px; }
h1 { font-family: 'Merriweather', serif; font-size: 24px; color: #1a365d; margin-bottom: 8px; padding-bottom: 16px; border-bottom: 3px solid #2b6cb0; }
h2 { font-family: 'Merriweather', serif; font-size: 18px; color: #2b6cb0; margin-top: 32px; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 1px solid #bee3f8; }
h3 { font-size: 15px; font-weight: 700; color: #2d3748; margin-top: 20px; margin-bottom: 8px; }
h4 { font-size: 14px; font-weight: 600; color: #4a5568; margin-top: 16px; margin-bottom: 6px; }
p { margin-bottom: 14px; font-size: 14px; text-align: justify; }
ul, ol { margin: 10px 0 14px 24px; font-size: 14px; }
li { margin-bottom: 6px; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }
thead { background: #2b6cb0; color: white; }
th { padding: 10px 12px; text-align: left; font-weight: 600; }
td { padding: 9px 12px; border-bottom: 1px solid #e2e8f0; }
tr:nth-child(even) { background: #f7fafc; }
strong { color: #2d3748; }
.doc-meta { font-size: 12px; color: #718096; margin-bottom: 30px; padding-bottom: 16px; border-bottom: 1px solid #e2e8f0; }
.merged-section + .merged-section { border-top: 2px dashed #e2e8f0; padding-top: 30px; margin-top: 20px; }
${DIAGRAM_CSS}
</style>
</head>
<body>
<div class="page">
<h1>${title} (Complete Document)</h1>
<div class="doc-meta">Combined document | Generated by ${companyName}</div>
${combinedBodyContent}
</div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;
};
export const refineDocumentContent = async (tender, currentContent, instruction) => {
try {
const prompt = `
ROLE: Expert Proposal Editor and Technical Document Specialist.
TASK: Please rewrite/update and improve the following HTML document based on the user's specific instruction.
USER INSTRUCTION: "${instruction}"
CURRENT CONTENT (HTML):
${currentContent}
ATTACHED FILES GUIDE:
Evaluate the attached files to incorporate real, specific data requested by the user instructions.
RULES:
1. Maintain the full HTML structure (h1, h2, h3, p, ul, table, etc.).
2. ONLY output the complete, valid HTML content. No markdown, no code fences.
3. Implement the requested changes thoroughly and specifically, using real facts and data from attached documents when requested.
4. Keep what is working well; only change what the instruction says.
5. Ensure the output is still complete β do not truncate.
6. CRITICAL β PRESERVE ALL SVG DIAGRAMS: If the document contains inline <svg> diagram blocks, preserve them exactly unless the instruction specifically asks to modify or add diagrams. You may update data values or labels within SVGs if the instruction asks for it.
7. CRITICAL β PRESERVE THREE.JS SCRIPTS: If the document contains <script type="module"> Three.js scenes, preserve them unless the instruction asks to change the 3D view.
8. If the instruction asks to ADD a diagram (Gantt, org chart, floor plan, 3D view), generate a complete, detailed SVG or Three.js block as appropriate. Follow the same diagram conventions: SVG wrapped in <figure class="diagram-block">, Three.js canvas with data-threejs attribute.
9. CUSTOM FONTS: If the user requests a specific font, include its \`<link href='https://fonts.googleapis.com/css2?family=Font+Name&display=swap' rel='stylesheet'>\` tag in the <head> of the document, and apply it using CSS/Tailwind.
10. The output must remain a complete self-contained HTML document with all original <head> content (importmap, styles) intact.
`;
const aiInputs = [prompt];
if (tender && tender.inputFiles && tender.inputFiles.length > 0) {
console.log(`Attaching ${tender.inputFiles.length} file(s) to document refinement...`);
for (const file of tender.inputFiles) {
try {
const { Body } = await getFileObject(file.storageKey);
let buffer = await streamToBuffer(Body);
let currentMimeType = file.mimeType;
if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
try {
console.log(`Converting ${file.originalName} to PDF for Gemini refinement...`);
buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
currentMimeType = 'application/pdf';
} catch (err) {
console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
}
}
aiInputs.push({
inlineData: {
data: buffer.toString('base64'),
mimeType: currentMimeType
}
});
} catch (fileErr) {
console.warn(`Could not attach file ${file.originalName} for refinement:`, fileErr.message);
}
}
}
const result = await powerfulModel.generateContent(aiInputs);
let html = result.response.text();
return html.replace(/```html/g, '').replace(/```/g, '').trim();
} catch (error) {
console.error("Refinement Error:", error);
throw new Error("Failed to refine document");
}
};
export const generateSubmissionInstructions = async (tender, documentsWithLinks) => {
const prompt = `
TASK: Please create a detailed Step-by-Step Submission Guide for this ${tender.analysis.announcementType || 'tender'}.
CONTEXT:
Title: ${tender.title}
Announcement Type: ${tender.analysis.announcementType}
Requirements: ${JSON.stringify(tender.analysis.requirements)}
Missing Docs to Gather: ${JSON.stringify(tender.analysis.missingDocuments)}
AI-Generated Documents with Download Links: ${JSON.stringify(documentsWithLinks)}
OUTPUT:
Return clean HTML with numbered steps (<ol>/<li>) covering exactly what the user needs to do to submit:
1. Documents to print and how many copies
2. Documents to sign and where
3. Physical or digital submission steps
4. Deadline reminders
5. Any other critical steps from the announcement
IMPORTANT: For any AI-generated documents mentioned, provide actual HTML clickable links using the provided URLs.
Use <a href="..." target="_blank" style="color:#2b6cb0; text-decoration:underline;">...</a> for links.
Provide both PDF and Word options where applicable.
`;
const result = await powerfulModel.generateContent(prompt);
return result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();
};
import { GoogleGenerativeAI } from '@google/generative-ai';
import { getFileObject } from '../utils/storageUtils.js';
import * as cheerio from 'cheerio';
import { convertToPdf } from '../utils/docConverter.js';
// Initialize Gemini
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
export const quickModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });
export const powerfulModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });
// βββ DIAGRAM / DRAWING INTELLIGENCE ββββββββββββββββββββββββββββββββββββββββ
/**
* Keywords that trigger full A4 architectural/technical drawing mode.
*/
const ARCH_DRAWING_KEYWORDS = [
'architectural drawing', 'floor plan', 'site plan', 'structural drawing',
'elevation drawing', 'section drawing', 'building plan', 'layout plan',
'construction drawing', 'civil drawing', 'electrical layout', 'plumbing layout',
'landscape plan', 'master plan', 'plot plan', 'foundation plan'
];
/**
* Analyses a plan item and tender context to determine diagram needs.
* Returns { needsSvg, needs3d, isArchitecturalDrawing }
*/
const detectDiagramNeeds = (planItem, tender) => {
const text = [
planItem.docName || '',
planItem.purpose || '',
(planItem.outline?.sections || []).join(' '),
(planItem.outline?.keyPoints || []).join(' '),
tender?.analysis?.announcementType || '',
tender?.userPrompt || ''
].join(' ').toLowerCase();
const isArchitecturalDrawing = ARCH_DRAWING_KEYWORDS.some(kw => text.includes(kw));
const needsSvg = isArchitecturalDrawing || [
'org chart', 'organisational chart', 'organizational chart', 'organogram',
'gantt', 'timeline', 'work plan', 'schedule', 'flowchart', 'process flow',
'workflow', 'methodology diagram', 'logical framework', 'logframe',
'results framework', 'theory of change', 'network diagram',
'site layout', 'infrastructure', 'system architecture', 'data flow'
].some(kw => text.includes(kw));
const needs3d = isArchitecturalDrawing || [
'3d model', 'three-dimensional', 'perspective view', 'isometric',
'building model', 'structural model', '3d render'
].some(kw => text.includes(kw));
return { needsSvg, needs3d, isArchitecturalDrawing };
};
/**
* The Three.js importmap injected into every generated document <head>.
* Allows AI-generated <script type="module"> blocks to import from 'three'.
*/
const THREE_IMPORTMAP = `
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.165.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.165.0/examples/jsm/"
}
}
</script>`;
/**
* Extra CSS injected into every generated document for diagrams/drawings.
*/
const DIAGRAM_CSS = `
/* ββ Diagram / Drawing Styles ββ */
.diagram-block { margin: 28px 0; text-align: center; }
.diagram-block svg { max-width: 100%; height: auto; border: 1px solid #e2e8f0; border-radius: 4px; background: #fff; }
.diagram-block figcaption { font-size: 12px; color: #718096; margin-top: 6px; font-style: italic; }
.three-canvas-wrap { margin: 28px 0; }
.three-canvas-wrap canvas { width: 100% !important; max-width: 800px; height: 420px !important; border: 1px solid #e2e8f0; border-radius: 4px; display: block; margin: 0 auto; }
/* A4 Architectural Drawing */
.a4-drawing-page { width: 210mm; min-height: 297mm; margin: 20px auto; background: white; border: 1px solid #ccc; box-shadow: 0 4px 24px rgba(0,0,0,0.12); position: relative; padding: 0; }
.a4-drawing-page svg { width: 210mm; height: 297mm; display: block; }
@media print {
body { background: white !important; }
.page { box-shadow: none !important; margin: 0 !important; padding: 10mm !important; max-width: 100% !important; }
.a4-drawing-page { box-shadow: none; margin: 0; border: none; }
@page { size: A4 portrait; margin: 8mm; }
}`;
/**
* Pre-print hook script: converts Three.js canvases to static images before printing.
*/
const PRINT_HOOK_SCRIPT = `
<script>
window.addEventListener('beforeprint', () => {
document.querySelectorAll('canvas[data-threejs]').forEach(canvas => {
const img = document.createElement('img');
img.src = canvas.toDataURL('image/png');
img.style.cssText = canvas.style.cssText;
img.style.maxWidth = '100%';
canvas.parentNode.insertBefore(img, canvas);