Brotherton-Aspire-App/index.js

182 lines
6.7 KiB
JavaScript
Raw Normal View History

2024-02-03 00:44:34 +00:00
// 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');
2024-02-03 00:44:34 +00:00
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)
});
2024-02-03 00:44:34 +00:00
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", () => {
2024-02-03 00:44:34 +00:00
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'));
2024-02-03 00:44:34 +00:00
//index route
app.get('/', (req, res) => {
res.render('home')
2024-02-03 00:44:34 +00:00
})
//POST Authorize route to gain access
app.post('/authorize', async (req, res) => {
2024-02-03 00:44:34 +00:00
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) => {
2024-02-03 00:44:34 +00:00
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`;
2024-02-03 00:44:34 +00:00
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
};
});
2024-02-03 00:44:34 +00:00
};
// Mapping propertyData to connect to contactData
const connectedData = propertyData.map(property => ({
...property,
contacts: connectPropertyToContact(property)
}));
2024-02-03 00:44:34 +00:00
2024-02-03 00:44:34 +00:00
res.render('./messages/index', { connectedData });
2024-02-03 00:44:34 +00:00
} 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;
2024-02-03 00:44:34 +00:00
// // 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',
// };
2024-02-03 00:44:34 +00:00
// const response = await axios.get(apiUrl, { headers });
2024-02-03 00:44:34 +00:00
// const contacts = response.data;
// // Assuming the response directly provides contacts
2024-02-03 00:44:34 +00:00
// // Send personalized emails using SendGrid for each contact retrieved
// const sgMail = require('@sendgrid/mail');
// sgMail.setApiKey(SENDGRID_API_KEY);
2024-02-03 00:44:34 +00:00
// 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`,
// };
2024-02-03 00:44:34 +00:00
// await sgMail.send(msg);
// });
2024-02-03 00:44:34 +00:00
// res.json({ message: 'Emails sent successfully!' });
// } catch (error) {
// res.status(500).json({ error: error.message });
// }
// });
2024-02-03 00:44:34 +00:00
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});