File size: 8,790 Bytes
a129b81
 
 
e08ecbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a129b81
 
e08ecbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a129b81
 
 
 
 
 
 
78785b5
a129b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78785b5
 
a129b81
 
 
 
 
 
 
 
 
 
 
 
e08ecbf
a129b81
e08ecbf
 
 
a129b81
e08ecbf
 
 
a129b81
e08ecbf
a129b81
 
 
 
 
 
e08ecbf
 
a129b81
 
e08ecbf
 
 
 
 
 
a129b81
e08ecbf
a129b81
e08ecbf
a129b81
 
 
 
e08ecbf
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
const { checkAndRefreshAccessToken } = require('../utils/refreshToken');
const { insertDemoRequest, checkExistingDemoRequest } = require('../utils/demoRequestDB');
const { sendEmail } = require('../utils/sendEmail');
const { DateTime } = require('luxon');
const fetch = require('node-fetch');

// The assistant URL for Vapi & other related config
const assistant_url = 'https://api.vapi.ai/call';

const demoRequest = async (req, res) => {
    const { name, email, company, product, demoDate, selectedSlot, phone, additionalComments, timezone } = req.body;
    console.log('Received demo request:', req.body);

    // Basic validation on the server side
    if (!name || !email || !company || !demoDate || !phone || !product || !selectedSlot) {
        console.log("Missing required fields");
        return res.status(400).send({ error: 'Please fill in all required fields.' });
    }

    const convertedDemoDate = DateTime.fromISO(demoDate, { zone: 'utc' })  // Parse demoDate as UTC
        .setZone('Asia/Kolkata') // Convert it to Asia/Kolkata time zone
        .toFormat('yyyy-MM-dd'); // Format it to 'yyyy-MM-dd'

    console.log('Converted demoDate to Asia/Kolkata timezone:', convertedDemoDate);

    // Step 2: Convert the Asia/Kolkata date to the user's time zone (const, as we're not reassigning it)
    const userDemoDate = DateTime.fromISO(convertedDemoDate, { zone: 'Asia/Kolkata' })  // Parse demoDate as Asia/Kolkata
        .setZone(timezone) // Convert it to user's time zone (e.g., 'America/New_York')
        .toFormat('yyyy-MM-dd'); // Format it to 'yyyy-MM-dd'

    console.log('Converted demoDate to user\'s timezone:', userDemoDate);

    // 1. Check if a demo request already exists within the last 15 days
    const existingRequest = await checkExistingDemoRequest(name, email, product, convertedDemoDate, phone);

    if (existingRequest) {
        console.log("Demo request already made within 15 days");
        return res.status(400).send({
            error: 'You have already requested a demo for this product within 15 days. Our team will get back to you shortly.'
        });
    }

    const [startTime, endTime] = selectedSlot.split(' (')[0].split(' - ');
    console.log('Selected time slot:', startTime, endTime);
    console.log('User\'s timezone:', timezone);
    // Convert start time and end time to the user's time zone first
    const startUserTime = DateTime.fromFormat(startTime, 'HH:mm', { zone: timezone });
    const endUserTime = DateTime.fromFormat(endTime, 'HH:mm', { zone: timezone });

    // Ensure that the conversion to Asia/Kolkata time zone is successful
    const startAsiaKolkata = startUserTime.setZone('Asia/Kolkata').toFormat('HH:mm');
    const endAsiaKolkata = endUserTime.setZone('Asia/Kolkata').toFormat('HH:mm');

    // Create the formatted time range string
    const formattedRange = `${startAsiaKolkata} - ${endAsiaKolkata}`;

    console.log('Converted time range to Asia/Kolkata:', formattedRange);

    // 2. Insert the new demo request into the database
    await insertDemoRequest(name, email, company, product, convertedDemoDate, formattedRange, phone, additionalComments);
    console.log('Demo request added successfully');

    // Refresh access token if needed
    await checkAndRefreshAccessToken();

    try {
        // 🔹 Email to User
        const userEmailSubject = "Demo Request Confirmation";
        const userEmailContent = `
            <div style="font-family: Arial, sans-serif; color: #333;">
                <center><img src="https://drive.google.com/thumbnail?id=17oMmzl_mTNvohvLhSWHbb_XNPfCC8KaO" alt="Genomatics Logo" height="150px"></center>
                <h2 style="color: #0056b3;">Hello ${name},</h2>
                <p>Thank you for requesting a demo of our <strong>Genomatics</strong> product: <strong>${product}</strong>. We're excited to showcase how our solutions can benefit your team at <strong>${company}</strong>.</p>
                <p><strong>Requested demo date:</strong> ${userDemoDate} - <strong>Time zone:</strong> ${timezone}</p>
                <p><strong>Preferred time slot:</strong> ${selectedSlot}</p>
                <p>We'll be in touch soon to confirm the details. In the meantime, please feel free to reach out with any specific questions or topics you’d like us to cover during the demo.</p>
                <h3 style="color: #0056b3;">Additional Message from You:</h3>
                <p>${additionalComments || "<em>No additional message provided.</em>"}</p>
                <p style="margin-top: 20px;">Best regards,</p>
                <p><strong>The Genomatics Team</strong></p>
                <hr style="border: 0; height: 1px; background: #ddd; margin: 20px 0;">
                <p style="font-size: 12px; color: #666;">
                    This email was sent in response to your request for a demo on the Genomatics platform.
                </p>
            </div>`;

        // Send the confirmation email to the user
        await sendEmail(email, userEmailSubject, userEmailContent);
        console.log("Confirmation email sent to user");

        // 🔹 Email to Team
        const teamEmail = process.env.TEAM_MAIL_IDS;
        const teamEmailSubject = `New Demo Request: ${product}`;
        const teamEmailContent = `
            <div style="font-family: Arial, sans-serif; color: #333; line-height: 1.6;">
                <center><img src="https://drive.google.com/thumbnail?id=17oMmzl_mTNvohvLhSWHbb_XNPfCC8KaO" alt="Genomatics Logo" height="150px"></center>
                <h2 style="color: #0056b3;">📩 New Demo Request Received</h2>
                <p>Dear Team,</p>
                <p>A new demo request has been submitted. Details are as follows:</p>
                <table style="width: 100%; border-collapse: collapse;">
                    <tr><td style="padding: 8px; font-weight: bold;">Name:</td><td style="padding: 8px;">${name}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Email:</td><td style="padding: 8px;">${email}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Company:</td><td style="padding: 8px;">${company}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Product:</td><td style="padding: 8px;">${product}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Phone:</td><td style="padding: 8px;">${phone}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Demo Date:</td><td style="padding: 8px;">${convertedDemoDate}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Preferred Slot:</td><td style="padding: 8px;">${formattedRange}</td></tr>
                    <tr><td style="padding: 8px; font-weight: bold;">Additional Comments:</td><td style="padding: 8px;">${additionalComments || "<em>No additional comments provided.</em>"}</td></tr>
                </table>
                <p>Please follow up with the requester accordingly.</p>
                <p style="margin-top: 20px;">Best regards,</p>
                <p><strong>Genomatics System</strong></p>
            </div>`;

        // Send the notification email to the team
        await sendEmail(teamEmail, teamEmailSubject, teamEmailContent);
        console.log("Notification email sent to team");

        res.status(200).send({ message: 'Demo request submitted successfully! Our team will get in touch with you soon.' });
    } catch (error) {
        console.error('Failed to send demo request confirmation email, however request registered successfully!', error);
        res.status(200).send({ error: 'Failed to send demo request confirmation email, however the demo request has been registered successfully!' });
    }

    // 🔹 Vapi AI Call
    const curr_time = DateTime.now().toFormat('yyyy-MM-dd');
    const postData = {
        "name": `${phone}_${curr_time}_DRC`,
        "assistantId": process.env.DEMO_ASSISTANT_ID,
        "assistantOverrides": {
            "variableValues": {
                "name": name,
                "product_name": product,
                "demo_date": demoDate,
                "slot": selectedSlot,
                "comments": additionalComments
            }
        },
        "customer": { "number": phone },
        "phoneNumberId": process.env.PHONE_NUMBER_ID
    };

    fetch(assistant_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${process.env.VAPI_KEY}`
        },
        body: JSON.stringify(postData)
    })
    .then(response => response.json())
    .then(data => console.log('Vapi AI Call Success:', data))
    .catch(error => console.error('Vapi AI Call Error:', error));
};

module.exports = { demoRequest };