Brotherton-Aspire-App/index.js

305 lines
10 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');
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 });
}
});
//WORK TICKET VISIT ROUTES
// api GET WORK TICKET VISITS
app.get('/api/workticketvisits', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN, ASPIRE_REFRESH_TOKEN } = process.env;
const apiUrl = `https://cloud-api.youraspire.com/WorkTicketVisits?%24select=WorkTicketVisitID%2CWorkTicketID%2CScheduledDate&%24filter=ScheduledDate%20gt%202024-01-29`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN }`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
const response = await axios.get(apiUrl, { headers });
const workticketvisits = response.data;
//save to database before going to client
// therefore logic to have databse filter logic beofre going to client
res.render('./workticketvisits', { workticketvisits });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
//API - GET - WORK TICKETS
app.get('/api/worktickets', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN, ASPIRE_REFRESH_TOKEN } = process.env;
const apiUrl = `https://cloud-api.youraspire.com/WorkTickets`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN }`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
const response = await axios.get(apiUrl, { headers });
const workTickets = response.data;
// await tickets.save();
res.json({ workTickets });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET ALL OPPORTUNITIES
app.get('/api/opportunities', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN, ASPIRE_REFRESH_TOKEN } = process.env;
const apiUrl = `https://cloud-api.youraspire.com/opportunities`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN}`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
const response = await axios.get(apiUrl, { headers });
const opportunities = response.data;
// await tickets.save();
res.json({ opportunities });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
//INDEX - GET ALL customer contacts
app.get('api/contacts', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_API_SECRET_KEY, ASPIRE_TOKEN, ASPIRE_REFRESH_TOKEN } = process.env;
// Implement logic to fetch appointment data using Axios and API keys
const apiUrl = `https://cloud-api.youraspire.com/Contacts?$filter=ContactTypeName eq 'Customer' and LastName ne 'Employee'&$select=FirstName,LastName,Email,CompanyName`; // 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
res.render('contacts', { contacts });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
//INDEX - GET ALL PROPERTIES
app.get('/api/properties', async (req, res) => {
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_API_SECRET_KEY, ASPIRE_TOKEN } = process.env;
// Implement logic to fetch appointment data using Axios and API keys
const apiUrl = `https://cloud-api.youraspire.com/properties`; // 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 properties = response.data; // Assuming the response directly provides properties
res.render('properties', { properties });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// DB -GET - WORK TICKET VISIT INDEX
app.get('/db/workticketvisits', async (req, res) => {
const visits = await WorkTicketVisitModel.find({})
res.render('./workticketvisits/index', { visits })
});
//DB - SHOW WORKTICKETVISIT/:ID
app.get('/db/workticketvisit/:id', async (req, res) => {
const visit = await WorkTicketVisitModel.findById(req.params.id)
res.render('./workticketvisits/show', { visit })
});
// DB -GET - WORK TICKET INDEX
app.get('/db/worktickets', async (req, res) => {
const tickets = await WorkTicketModel.find({})
res.render('worktickets/index', { tickets })
});
//DB - SHOW WORKTICKET/:ID
app.get('/db/worktickets/:id', async (req, res) => {
const ticket = await WorkTicketModel.findById(req.params.id)
res.render('./worktickets/show', { ticket });
});
//DB - INDEX GET ALL contacts
app.get('/db/contacts', async (req, res) => {
const contacts = await ContactModel.find({})
res.render('./contacts/index', {contacts });
});
/**** MESSAGING FEATURE ROUTE ****/
app.get('/messages', async (req, res)=>{
try {
const contacts = await ContactModel.find({});
const propertyContacts = await PropertyContactModel.find({});
const properties = await PropertyModel.find({});
const opportunities = await OpportunityModel.find({});
const worktickets = await WorkTicketModel.find({});
const workVisits = await WorkTicketVisitModel.find({});
const filteredContacts = workVisits.filter(visit => {
return worktickets.some(ticket => ticket.WorkTicketID === visit.WorkTicketID );
}).filter(opportunity => {
return opportunities.some(wonOpportunity => wonOpportunity.OpportunityID === ticket.OpportunityID && opportunity.OpportunityStatusName === "won");
}).filter(propertyContact => {
return propertyContacts.some(propContact => propContact.PropertyID === wonOpportunity.PropertyID );
});
res.render('./messages/index', {
filteredContacts,
// Include other filtered data in the render object
});
} catch (error) {
res.status(500).json({ error: error.message });
}
})
//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}`);
});