Brotherton-Aspire-App/index.js

182 lines
6.7 KiB
JavaScript

// index.js
const express = require('express');
const path = require('path');
const axios = require('axios');
const sgMail = require('@sendgrid/mail');
const WorkTicketVisitModel = require('./models/workticketvisit');
const WorkTicketModel = require("./models/workticket");
const ContactModel = require("./models/contact");
const OpportunityModel = require('./models/opportunity');
const PropertyModel = require('./models/property');
const PropertyContactModel = require('./models/propertyContact');
require('dotenv').config();
//connect database
//development
const mongoose = require('mongoose');
const { error } = require('console');
const opportunity = require('./models/opportunity');
mongoose.connect('mongodb://127.0.0.1:27017/test')
.then(() => {
console.log("Connection Open")
})
.catch(err => {
console.log("ERROR")
console.log(err)
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", () => {
console.log("Database connected");
});
// const { fetchAspireData } = require('./aspireApi')
const app = express();
const port = 3000;
// Configure SendGrid with your API key
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'));
//index route
app.get('/', (req, res) => {
res.render('home')
})
//POST Authorize route to gain access
app.post('/authorize', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_API_SECRET_KEY } = process.env;
const tokenUrl = 'https://cloud-api.youraspire.com/Authorization';
const response = await axios.post(tokenUrl, {
grant_type: 'client_credentials',
ClientId: ASPIRE_API_CLIENT_ID,
Secret: ASPIRE_API_SECRET_KEY,
});
return response.data.access_token;
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**** MESSAGING FEATURE ROUTES ****/
app.get('/data-for-messages', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_API_SECRET_KEY, ASPIRE_TOKEN } = process.env;
//Specific api routes with details needed
const apiPropertyUrl = `https://cloud-api.youraspire.com/Properties?%24select=PropertyID%2CSequenceNumber%2CPropertyName%2CPropertyAddressLine1%2CPropertyAddressLine2%2CPropertyAddressCity%2CPropertyAddressStateProvinceCode%2CPropertyAddressZipCode%2CBranchName`;
const apiPropertyContactUrl = `https://cloud-api.youraspire.com/PropertyContacts?%24select=ContactID%2CPropertyID`;
const apiContactUrl = `https://cloud-api.youraspire.com/Contacts?%24select=ContactID%2CEmail%2CMobilePhone%2CNotes%2CFirstName%2CLastName`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN}`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
//VARIABLES to capture needed data
const responseProperty = await axios.get(apiPropertyUrl, { headers });
const responsePropertyContact = await axios.get(apiPropertyContactUrl, { headers });
const responseContact = await axios.get(apiContactUrl, { headers });
const propertyData = responseProperty.data;
const propertyContactData = responsePropertyContact.data;
const contactData = responseContact.data;
// Function to connect propertyData to propertyContactData based on PropertyID and connect propertyContactData to contactData based on ContactID
const connectPropertyToContact = property => {
const propertyID = property.PropertyID;
const propertyContacts = propertyContactData.filter(contact => contact.PropertyID === propertyID);
return propertyContacts.map(contact => {
const contactID = contact.ContactID;
const contactDetails = contactData.find(c => c.ContactID === contactID);
return {
...contact,
contactDetails
};
});
};
// Mapping propertyData to connect to contactData
const connectedData = propertyData.map(property => ({
...property,
contacts: connectPropertyToContact(property)
}));
res.render('./messages/index', { connectedData });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
//DONT USE THIS
//SendGrid TEST - Navigation will need emails to employee contacts in apsire.
// app.get('/test', async (req, res) => {
// try {
// const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN, SENDGRID_API_KEY } = process.env;
// // Implement logic to fetch appointment data using Axios and API keys
// const apiUrl = `https://cloud-api.youraspire.com/Contacts?$filter=ContactTypeName eq 'Employee' and LastName ne 'Employee'&$select=FirstName,LastName,Email,CompanyName,Salutation`; // Replace with the actual API endpoint
// const headers = {
// 'Authorization': `Bearer ${ASPIRE_TOKEN}`,
// 'Client-ID': ASPIRE_API_CLIENT_ID,
// 'Content-Type': 'application/json',
// };
// const response = await axios.get(apiUrl, { headers });
// const contacts = response.data;
// // Assuming the response directly provides contacts
// // Send personalized emails using SendGrid for each contact retrieved
// const sgMail = require('@sendgrid/mail');
// sgMail.setApiKey(SENDGRID_API_KEY);
// contacts.forEach(async (contact) => {
// const msg = {
// to: contact.Email,
// from: 'info@sprinklersnorthwest.com',
// subject: 'Bulk Email To Employee Contacts', // Set a subject for the email
// text: `Hi ${contact.FirstName} ${contact.LastName} of ${contact.CompanyName}, This is an bulk email test to confirm I have pulled contact data from the Aspire API and sent it through sendGrid if this is received please respond to my email landry@shilocode.com when possible thank you Landry-Developer-Shiloh Code`,
// html: `Hi ${contact.FirstName} ${contact.LastName} of ${contact.CompanyName}, This is an bulk email test to confirm I have pulled contact data from the Aspire API and sent it through sendGrid if this is received please respond to my email landry@shilocode.com when possible thank you Landry-Developer-Shiloh Code`,
// };
// await sgMail.send(msg);
// });
// res.json({ message: 'Emails sent successfully!' });
// } catch (error) {
// res.status(500).json({ error: error.message });
// }
// });
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});