const express = require('express');
const router = express.Router();
const sql = require('mssql');
const moment = require('moment');
const { getUser } = require('../util.js');
router.get('/', async (req, res, next) => {
let pool;
let stmt;
try {
pool = await sql.connect(dbConfig);
let orderResults;
if (getUser(req).isAdmin) {
orderResults = await pool.request().query(`
select o.orderId, o.orderDate, o.customerId, c.firstName, c.lastName, o.totalAmount
from ordersummary as o
left join customer as c on o.customerId = c.customerId
`);
} else {
stmt = new sql.PreparedStatement(pool);
stmt.input('customerId', sql.Int);
await stmt.prepare(`
select o.orderId, o.orderDate, o.customerId, c.firstName, c.lastName, o.totalAmount
from ordersummary as o
left join customer as c on o.customerId = c.customerId
where o.customerId = @customerId
`);
orderResults = await stmt.execute({customerId: getUser(req).id});
}
const productResults = await pool.request().query(`
select orderId, productId, quantity, price from orderproduct
`);
res.render('layouts/main', {
loggedIn: getUser(req) != null,
user: getUser(req),
spacer: true,
content: `
Nat & Samira's Grocery Order List
Order List
Customer ID |
Order Date |
Customer ID |
Customer Name |
Total Amount |
${orderResults.recordset.map(row => {
const products = productResults.recordset.filter(r => r.orderId == row.orderId);
return `
${row.orderId} |
${row.orderDate.toDateString()} |
${row.customerId} |
${row.firstName} ${row.lastName} |
$${row.totalAmount.toFixed(2)} |
Prouct Id |
Quantity |
Price |
${products.map(productRow => `
${productRow.productId} |
${productRow.quantity} |
$${productRow.price.toFixed(2)} |
`).join('\n')}
|
`;
}).join('\n')}
`
});
pool.close();
} catch (err) {
res.write(err.toString());
res.end();
} finally {
if (stmt) stmt.unprepare();
if (pool) pool.close();
}
});
module.exports = router;