-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbamazonCustomer.js
More file actions
70 lines (55 loc) · 2.2 KB
/
bamazonCustomer.js
File metadata and controls
70 lines (55 loc) · 2.2 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
var mysql = require("mysql");
var cTable = require("console.table");
var inquirer = require("inquirer");
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "root",
database : "bamazon"
});
connection.connect();
console.log(`\n\t\t\tBAMazon - Customer`);
console.log(`\t\t\t==================\n`);
console.log(`The following items are for sale:\n`);
/* Get all products and display to user */
connection.query("SELECT item_id, product_name, price FROM products", function (error, results, fields) {
if (error) throw error;
console.table(results);
console.log("\n");
});
function getUserInput() {
inquirer.prompt([
{
type: "input",
name: "item_id",
message: "Enter the Item ID of the product you would like to buy:"
},
{
type: "input",
name: "units",
message: "How many units of the item?"
}
]).then(answers => {
var availStockQuery = `SELECT item_id, price, stock_quantity FROM products
WHERE item_id = ?;`;
connection.query(availStockQuery, [answers.item_id], function (error, results, fields) {
var unitPrice = results[0].price;
if (error) throw error;
if (answers.units <= results[0].stock_quantity) {
var newQuantity = results[0].stock_quantity - answers.units;
var purchaseQuery = `UPDATE products
SET stock_quantity = ?
WHERE item_id = ?;`
connection.query(purchaseQuery, [newQuantity, answers.item_id], function (error, results, fields) {
if (error) throw error;
var totalCost = unitPrice * answers.units;
console.log(`\nTransaction SUCCESSFUL: You owe \$${totalCost.toFixed(2)}\n`); // set precision to 2 decimal points
});
}
else {
console.log("\nTransaction FAILED: Insufficient stock available.\n");
}
});
});
}
setTimeout(getUserInput, 500);