-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbamazonCustomer.js
More file actions
101 lines (93 loc) · 2.98 KB
/
bamazonCustomer.js
File metadata and controls
101 lines (93 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* eslint-disable */
const mysql = require("mysql");
const inquirer = require("inquirer");
const Table = require('cli-table');
// create the connection information for the sql database
const connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
// Your username
user: "root",
// Your password
password: "",
database: "bamazon_db"
});
// connect to the mysql server and sql database
connection.connect(function(err) {
if (err) throw err;
// run the start function after the connection is made to prompt the user
// console.log("We are connected");
showAllProducts();
});
function showAllProducts() {
connection.query("SELECT * FROM products", function(err, res) {
if (err) throw err;
const table = new Table({
head: ['ID', 'Product', 'Department', 'Price', 'In Stock', 'Product Sales'],
colWidths: [10, 30, 15, 10, 10, 15]
});
for (var i = 0; i < res.length; i++) {
table.push([res[i].id, res[i].product_name, res[i].department_name, res[i].price, res[i].stock_quantity, res[i].product_sales]);
}
console.log(table.toString());
});
whatToBuy();
}
function whatToBuy() {
connection.query("SELECT * FROM products", function(err, results) {
if (err) throw err;
inquirer
.prompt([
{
name: "productID",
type: "number",
message: "Enter the ID for the product you would like to buy:"
},
{
name: "units",
type: "number",
message: "How many would you like to buy?"
}
])
.then(function(answer) {
// get the information of the chosen item
let chosenProduct;
let chosenProductPrice;
for (var i = 0; i < results.length; i++) {
if (results[i].id === answer.productID) {
chosenProduct = results[i];
chosenProductPrice = results[i].price;
}
// console.log(chosenProductPrice);
}
if (chosenProduct.stock_quantity < answer.units) {
console.log("Insufficient quantity!");
} else {
console.log("Congratulations, your order was placed!");
let updatedStockQuantity = chosenProduct.stock_quantity - answer.units;
let updatedProductSales = answer.units * chosenProductPrice;
// console.log(updatedProductSales.toFixed(2));
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: updatedStockQuantity,
product_sales: updatedProductSales.toFixed(2)
},
{
product_name: chosenProduct.product_name
}
],
function(err) {
if (err) throw err;
connection.end();
}
);
let cost = answer.units * chosenProduct.price;
let shortenedCost = cost.toFixed(2);
console.log("Your total cost is: " + "$" + shortenedCost);
}
})
})
}