File size: 2,650 Bytes
16855a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import Tender from '../models/Tender.js';
import { getFileObject } from '../utils/storageUtils.js';
import { convertToDocx, convertToPdf, convertToXlsx } from '../services/conversionService.js';

// Helper to read R2 stream to string
const streamToString = (stream) => {
    const chunks = [];
    return new Promise((resolve, reject) => {
        stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
        stream.on('error', (err) => reject(err));
        stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
    });
};

export const downloadDocument = async (req, res) => {
    const { id, format, docIndex } = req.params;

    try {
        const tender = await Tender.findOne({ _id: id, user: req.user._id });
        if (!tender || !tender.draftingPlan[docIndex]) {
            return res.status(404).json({ message: 'Document not found' });
        }

        const doc = tender.draftingPlan[docIndex];
        
        // 1. Get HTML from R2
        const { Body } = await getFileObject(doc.storageKey);
        const htmlContent = await streamToString(Body);

        let fileBuffer;
        let contentType;
        let extension;

        // 2. Convert based on format
        switch (format) {
            case 'docx':
                fileBuffer = await convertToDocx(htmlContent, doc.docName);
                contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                extension = 'docx';
                break;
            case 'pdf':
                fileBuffer = await convertToPdf(htmlContent);
                contentType = 'application/pdf';
                extension = 'pdf';
                break;
            case 'xlsx':
                try {
                    fileBuffer = await convertToXlsx(htmlContent, doc.docName);
                    contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    extension = 'xlsx';
                } catch (e) {
                    return res.status(400).send("Error: This document contains no tables to convert to Excel.");
                }
                break;
            default:
                return res.status(400).send("Invalid format");
        }

        // 3. Send File
        res.setHeader('Content-Type', contentType);
        res.setHeader('Content-Disposition', `attachment; filename="${doc.docName}.${extension}"`);
        res.send(fileBuffer);

    } catch (error) {
        console.error("Download Error:", error);
        res.status(500).send("Conversion Failed");
    }
};