-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBamazonCustomer.js
88 lines (82 loc) · 2.73 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Created by morgansliman on 1/11/17.
*/
const mysql = require('mysql');
const pass = require('./pass');
const inquirer = require('inquirer');
require('console.table');
const conn = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: pass.sql,
database: 'Bamazon'
});
function updateDatabase(item, quantity) {
var total = (item.Price * quantity).toFixed(2);
var query = "UPDATE `Bamazon`.`Products` SET `StockQuantity`= ? WHERE `ItemID`= ?;";
item.StockQuantity -= parseInt(quantity);
conn.query(query, [item.StockQuantity, item.ItemID], function(err) {
if (err) throw err;
});
console.log('Total cost: $' + total);
inquirer.prompt({
type: 'confirm',
name: 'continue',
message: 'Would you like to continue shopping?',
default: true
}).then(function(answer) {
if (answer.continue) bamazonCustomer();
else {
console.log('Thanks for shopping with us!');
conn.end();
}
});
}
function bamazonCustomer() {
conn.query('SELECT * FROM Bamazon.Products;', function(err, res) {
if (err) throw err;
console.table('Bamazon Inventory', res);
inquirer.prompt({
name: 'item',
type: 'input',
message: 'Which item would you like to buy:',
validate: function(value) {
if (!isNaN(value) && (1 <= value) && (value <= res.length)) {
return true;
}
return 'Please enter the ItemID of the item you would like to buy';
}
}).then(function(answer) {
var item = res[parseInt(answer.item) - 1];
inquirer.prompt({
name: 'quantity',
type: 'input',
message: 'How many would you like to buy:',
validate: function(value) {
if (!isNaN(value) && (0 <= value)) {
if (value > item.StockQuantity) {
return 'Insufficient Quantity! Please enter a lower number, or 0 to cancel purchase';
}
return true;
}
else {
return 'Please enter a positive number, or 0 to cancel purchase';
}
}
}).then(function(answer) {
if (answer.quantity == 0) {
console.log('Purchase cancelled');
conn.end();
}
else {
updateDatabase(item, answer.quantity);
}
});
})
});
}
conn.connect(function(err) {
if (err) throw err;
bamazonCustomer();
});