File size: 2,024 Bytes
2dddd1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import nodemailer from 'nodemailer';
import * as xlsx from 'xlsx';
import { getDb } from '../db';
import dotenv from 'dotenv';

dotenv.config();

const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
    },
});

export async function exportToBuffer(): Promise<Buffer> {
    const db = await getDb();
    const transactions = await db.all('SELECT * FROM transactions');
    const wallets = await db.all('SELECT * FROM wallets');
    const exchanges = await db.all('SELECT * FROM exchanges');
    const loans = await db.all('SELECT * FROM loans');

    const wb = xlsx.utils.book_new();

    xlsx.utils.book_append_sheet(wb, xlsx.utils.json_to_sheet(transactions), 'Transactions');
    xlsx.utils.book_append_sheet(wb, xlsx.utils.json_to_sheet(wallets), 'Wallets');
    xlsx.utils.book_append_sheet(wb, xlsx.utils.json_to_sheet(exchanges), 'Exchanges');
    xlsx.utils.book_append_sheet(wb, xlsx.utils.json_to_sheet(loans), 'Loans');

    return xlsx.write(wb, { type: 'buffer', bookType: 'xlsx' });
}

export async function performWeeklyBackup() {
    console.log('[Backup] Starting weekly export...');
    try {
        const buffer = await exportToBuffer();
        const date = new Date().toISOString().split('T')[0];
        const filename = `backup-${date}.xlsx`;

        const mailOptions = {
            from: process.env.EMAIL_USER,
            to: process.env.EMAIL_TO,
            subject: `Weekly Wallet Backup - ${date}`,
            text: 'Please find the attached weekly backup of your wallet data.',
            attachments: [
                {
                    filename: filename,
                    content: buffer,
                },
            ],
        };

        const info = await transporter.sendMail(mailOptions);
        console.log('[Backup] Email sent successfully:', info.messageId);
    } catch (error) {
        console.error('[Backup] Error during weekly backup:', error);
    }
}