const express = require('express');
const router = express.Router();
const sql = require('mssql');
const { getUser, getCustomerRecord } = require('../util.js');
router.get('/', async function(req, res, next) {
res.setHeader('Content-Type', 'text/html');
let pool;
try {
pool = await sql.connect(dbConfig);
const profile = await getCustomerRecord(pool, getUser(req).id);
res.render('layouts/main', {
loggedIn: getUser(req) != null,
user: getUser(req),
spacer: true,
content: `
${profile.firstName} ${profile.lastName}'s Profile
ID |
${profile.customerId} |
Username |
${profile.userid} |
First Name |
${profile.firstName} |
Last Name |
${profile.lastName} |
email |
${profile.email} |
Phone Number |
${profile.phonenum} |
Address |
${profile.address} |
City |
${profile.city} |
State |
${profile.state} |
Postal Code |
${profile.postalCode} |
Country |
${profile.country} |
`,
});
} catch(err) {
console.dir(err);
res.write(err + "")
res.end();
} finally {
if (pool) pool.close();
}
});
router.get('/update', async (req, res) => {
let pool;
try {
pool = await sql.connect(dbConfig);
const profile = await getCustomerRecord(pool, getUser(req).id);
res.render('layouts/main', {
title: 'Update your Profile',
loggedIn: getUser(req) != null,
user: getUser(req),
spacer: true,
content: `
${profile.firstName} ${profile.lastName}'s Profile
`,
});
} finally {
if (pool) pool.close();
}
});
router.post('/update', async (req, res) => {
let pool;
let stmt;
try {
pool = await sql.connect(dbConfig);
stmt = new sql.PreparedStatement(pool);
stmt.input('userid', sql.VarChar);
stmt.input('firstName', sql.VarChar);
stmt.input('lastName', sql.VarChar);
stmt.input('email', sql.VarChar);
stmt.input('phonenum', sql.VarChar);
stmt.input('address', sql.VarChar);
stmt.input('city', sql.VarChar);
stmt.input('state', sql.VarChar);
stmt.input('postalCode', sql.VarChar);
stmt.input('country', sql.VarChar);
stmt.input('customerId', sql.Int);
await stmt.prepare(`
update customer set
userid = @userid,
firstName = @firstName,
lastName = @lastName,
email = @email,
phonenum = @address,
city = @city,
state = @state,
postalCode = @postalCode,
country = @country
where customerId = @customerId
`);
await stmt.execute({...req.body, customerId: getUser(req).id});
res.redirect('/customer');
} catch (err) {
console.error(err);
res.write("Failed to update user");
} finally {
if (stmt) stmt.unprepare();
if (pool) pool.close();
}
});
module.exports = router;