-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbamazonCustomer.js
More file actions
88 lines (82 loc) · 2.26 KB
/
bamazonCustomer.js
File metadata and controls
88 lines (82 loc) · 2.26 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
var mysql = require('mysql');
var inquirer = require('inquirer');
var connection = mysql.createConnection({
host: 'localhost',
port: 8889,
user: 'root',
password: 'root',
database: 'bamazon_db'
});
connection.connect(function(err) {
if (err) throw err;
console.log('Connected at id ' + connection.threadID);
// connection.end();
availableItems();
});
function availableItems(){
console.log("All products available...\n");
connection.query("SELECT * FROM products", function(err, res) {
if (err) throw err;
// Log all results of the SELECT statement
for( var i = 0; i < res.length; i++){
console.log("\nID number: " + res[i].item_id + " | Product Name: " + res[i].product_name + " | Item Price: $" + res[i].price)
}
userPurchase();
});
};
function userPurchase(){
connection.query("SELECT * FROM products", function(err, res) {
if (err) throw err;
inquirer.prompt([
{
type: "list",
message: "What item you would like to buy?\n",
name: "item",
choices: function() {
var choicesArr = [];
for (var i = 0; i < res.length; i++) {
choicesArr.push(res[i].item_id + " | " + res[i].product_name);
}
return choicesArr;
},
},
{
type: "input",
message: "How many would you like to buy?\n",
name: "amount",
validate: value => !isNaN(value)
}
])
.then(function(answer){
var itemID = answer.item.split(" |")[0];
//console.log('item', itemID)
connection.query("SELECT * FROM products WHERE item_id=" + itemID, function (err, res){
if (err) throw err;
//console.log('res', res)
var total = res[0].price * answer.amount;
if ( res[0].stock_quantity >= answer.amount ){
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: res[0].stock_quantity - answer.amount,
},
{
item_id: res[0].item_id
}
],
function(err, res) {
if (err) throw err;
console.log("Thanks for shopping! Your total is $" + total + ".\n");
connection.end();
}
);
}
else{
console.log("Insufficint Quantity! Try Again!")
connection.end();
}
});
})
})
};