File size: 3,878 Bytes
62c3fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { checkAndRefreshAccessToken } = require('./refreshToken');
const { google } = require('googleapis');
const { oAuth2Client } = require('../config/googleOAuth');
const { DateTime } = require('luxon');
const ics = require('ics');
const { v4: uuid } = require('uuid');
const fs = require('fs');
const path = require('path');

async function convertToUTC(date, time, timezone) {
    // Combine date and time into one string (e.g., '2025-01-31T14:30')
    const dateTimeString = `${DateTime.fromISO(date).toFormat('yyyy-MM-dd')}T${time}`;
    console.log(dateTimeString);

    // Parse the combined date-time string in the given timezone
    const dateTimeInTimezone = DateTime.fromISO(dateTimeString, { zone: timezone });
    console.log(dateTimeInTimezone);

    // Convert it to UTC
    const dateTimeInUTC = dateTimeInTimezone.toUTC();
    console.log(dateTimeInUTC);

    // Return the UTC time as a string (ISO format)
    return dateTimeInUTC.toISO(); // Returns the date-time in ISO 8601 format (e.g., '2025-01-31T08:00:00.000Z')
}

async function isoToArray(isoString) {
    const dt = DateTime.fromISO(isoString, { zone: 'utc' }); // Ensure it's parsed as UTC
    return [dt.year, dt.month, dt.day, dt.hour, dt.minute];
}


// Create Google Calendar Event
async function createGoogleCalendarEvent(name, email, demoDate, selectedSlot, product, timezone) {

    const [startTime, endTime] = selectedSlot.split(' (')[0].split(' - ');

    const startDatetime = await convertToUTC(demoDate, startTime, timezone);
    const endDatetime = await convertToUTC(demoDate, endTime, timezone);

    console.log(`Times: ${startDatetime}, ${endDatetime}`);

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

    const calendar = google.calendar({ version: 'v3', auth: oAuth2Client });

    const event = {
        summary: `Demo for ${product}`,
        description: `Demo for ${product}`,
        start: {
            dateTime: startDatetime, // Use the demo date here
            timeZone: 'UTC',
        },
        end: {
            dateTime: endDatetime, // Assuming the demo lasts 30 minutes
            timeZone: 'UTC',
        },
        colorId: 1,
        conferenceData: {
            createRequest: {
                requestId: uuid(),
            }
        },
        attendees: [
            {email: email},
          ]
    };

    try {
        const response = await calendar.events.insert({
            calendarId: 'primary',
            conferenceDataVersion: 1, 
            resource: event,
            sendUpdates: 'all'
        });
        console.log('Google Calendar Event Created:', response.data);

        const dateArray = await isoToArray(startDatetime);    
        const icsevent = {
            start: dateArray,
            startInputType: 'utc',
            duration: { minutes: 30 },
            title: `Demo for ${product}`,
            description: `Product demonstration for ${product}`,
            url: response.data.hangoutLink,
            categories: ['Product Demo'],
            status: 'CONFIRMED',
            busyStatus: 'BUSY',
            attendees: [
              { name: name, email: email, rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
            ]
          }
        
        const icsFilePath = path.join(__dirname, '../demo-event.ics');
        const icsContent = await new Promise((resolve, reject) => {
            ics.createEvent(icsevent, (error, value) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(value); // Return .ics content as string
                }
            });
        });
        return [response.data, icsContent];
    } catch (error) {
        console.error('Error creating Google Calendar event:', error);
        throw error;
    }
}

module.exports = {createGoogleCalendarEvent}