-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbamazonCustomer.js
71 lines (66 loc) · 2.35 KB
/
bamazonCustomer.js
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
// Dependencies
var mysql = require('mysql');
var inquirer = require('inquirer');
// Connect to MySQL database
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'min95595',
database : 'bamazon_db'
});
//Fix connection error
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
// Show ids, names, and prices of products
connection.query('SELECT * FROM `products`', function (err, results, fields) {
if (err) {
console.log(err);
}
for (var i=0; i<results.length; i++) {
console.log(results[i].item_id + " " + results[i].product_name + " [" + results[i].price + "]");
}
// Prompt user to select a product and enter desired quantity
function buyPrompt() {
inquirer.prompt( [{
name: "itemId",
type: "input",
message: "Enter the id of the product you'd like to buy."
}, {
name: "quantity",
type: "input",
message: "How many units would you like to purchase?"
}]).then(function(answer) {
for (var i=0; i<results.length; i++) {
if (results[i].item_id === parseInt(answer.itemId)) {
// If order quantity is too much, let user know "insufficient stock!"
if (results[i].stock_quantity < parseInt(answer.quantity)) {
console.log("Insufficient stock!");
buyPrompt();
} else {
// Calculate total and remaining stock
let total = parseFloat(answer.quantity*results[i].price).toFixed(2);
let newStock = results[i].stock_quantity - answer.quantity;
// Construct for the query to update stock
const updateStock = 'UPDATE `products` SET `stock_quantity` = ' + newStock + ' WHERE `item_id` = ' + answer.itemId
connection.query(updateStock, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result.affectedRows + " product updated");
}
});
// Tells user of an successful purchase and calculated total
console.log("You have purchased " + answer.quantity + " " + results[i].product_name);
console.log("Your order total is " + total);
}
}
}
});
}
buyPrompt();
});