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 . * Allows AI-generated `; /** * 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 = ` `; // 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 N: Description — Scale/Units if applicable
- 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
where appropriate. - Follow it with a

${docName}

Document for: ${tenderTitle}  |  Generated by ${companyName}
${bodyContent}
${PRINT_HOOK_SCRIPT} `; }; /** * 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 // 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: - Inner margin line: 2. TITLE BLOCK (inside SVG, at bottom ~y=1010 to y=1103): Render as bordered cells with + : - "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: or 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: 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: with tick marks + measurements - Hatching in wall thickness: 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):

📐 3D Perspective View — Interactive (Drag to Rotate)

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 ` ${planItem.docName} — Technical Drawing${THREE_IMPORTMAP}
📐 ${planItem.docName} ${tender.title}  •  ${tender.companyName || 'Technical Drawing'} 3D view: drag to rotate • prints as line drawing only
${rawHtml}
${PRINT_HOOK_SCRIPT} `; } 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
${content || ""}
\n`; }); return ` ${title}${THREE_IMPORTMAP}

${title} (Complete Document)

Combined document  |  Generated by ${companyName}
${combinedBodyContent}
${PRINT_HOOK_SCRIPT} `; }; 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 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 of the document, and apply it using CSS/Tailwind. 10. The output must remain a complete self-contained HTML document with all original 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 (
    /
  1. ) 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 ... 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(); };