-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
595 lines (558 loc) · 17.7 KB
/
server.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
const inquirer = require("inquirer");
require("console.table");
const connection = require("./db/connection.js");
// function to open the process
function openProcess() {
inquirer.prompt(
{
type: "list",
message: "What would you like to do?",
name: "action",
choices: ["Add department", "Add employee", "Add role", "Delete department", "Delete employee", "Delete role", "Update employee manager", "Update employee role", "View departments", "View all employees", "View employees by department", "View employees by manager", "View employees by role", "View roles", "View department budgets", "Done"]
}
).then(function (response) {
console.log(response.action)
switch (response.action) {
case "Add department": addDepartment();
break;
case "Add employee": addEmployee();
break;
case "Add role": addRole();
break;
case "Delete department": deleteDepartment();
break;
case "Delete employee": deleteEmployee();
break;
case "Delete role": deleteRole();
break;
case "Update employee manager": updateJobData("SELECT id, CONCAT(first_name,' ',last_name) AS manager_name FROM employee WHERE manager_id IS NULL", "employee", "manager", getEmployeeQuestions);
break;
case "Update employee role": updateJobData("SELECT id, title FROM role", "role", "role", getRoleNameQuestion);
break;
case "View departments": viewAll("department", "*");
break;
case "View all employees": viewAll("employee", "*");
break;
case "View employees by department": viewBy("department", "name", "SELECT department.id, department.name, role.id, role.title, role.department_id, employee.first_name, employee.last_name, employee.role_id FROM department INNER JOIN role ON department.id = role.department_id INNER JOIN employee ON role.id = employee.role_id WHERE ?", getDepartmentQuestion);
break;
case "View employees by manager": viewByManager();
break;
case "View employees by role": viewBy("role", "id, title", "SELECT role.id, role.title, employee.first_name, employee.last_name, employee.role_id FROM role INNER JOIN employee ON role.id = employee.role_id WHERE ?", getRoleNameQuestion);
break;
case "View roles": viewAll("role", "id, title");
break;
case "View department budgets": viewDeptBudget();
break;
default: process.exit();
}
}).catch(function (err) {
if (err) throw err;
})
};
// Gary gave me the "new Promise"/"await" logic & syntax
// Creates list of department, employee, manager, or role names
function getNames(queryStr, nameType) {
let objArr;
return new Promise(function (resolve, reject) {
connection.query(queryStr, function (err, res) {
const names = res.map(obj => {
switch (nameType) {
case "department":
objArr = obj.name;
break;
case "manager":
objArr = obj.manager_name;
break;
case "role":
objArr = obj.title;
break;
default:
objArr = obj.employee_name;
}
return objArr;
});
resolve(names);
});
});
};
// Resolves ID for employee table when given name of department, role, or manager
function getId(questionObj, table) {
let resolver;
return new Promise(function (resolve, reject) {
inquirer.prompt(questionObj).then(response => {
const queryStr = `SELECT id FROM ${table} WHERE ?`;
switch (table) {
case "department":
resolver = { name: response.chosenDept };
break;
case "role":
resolver = { title: response.jobTitle };
break;
default:
switch (response.managerName) {
case "None":
resolver = null;
break;
default:
const mName = response.managerName.split(" ");
const fName = mName[0];
const lName = mName[1];
resolver = [{ first_name: fName }, { last_name: lName }];
};
};
switch (resolver) {
case null:
resolve(null);
break;
default:
connection.query(queryStr, resolver, function (err, data) {
resolve(data[0].id);
});
};
});
});
};
// Deletes employees, roles or departments given table, ID, and a string to log
function deleteThis(table, thisId, logStr) {
switch (table) {
case "employee":
const eName = thisId.split(" ");
const fName = eName[0];
const lName = eName[1];
connection.query(
`DELETE FROM ${table} WHERE ? AND ?`,
[
{
first_name: fName
},
{
last_name: lName
}
],
function (err, res) {
if (err) throw err;
console.log(logStr);
openProcess();
}).catch(function (err) {
if (err) throw err;
});
break;
default:
connection.query(`DELETE FROM ${table} WHERE ?`,
{
id: thisId
},
function (err, res) {
if (err) throw err;
console.log(logStr);
openProcess();
}).catch(function (err) {
if (err) throw err;
});
};
};
// ==========================================================
// Functions to populate choices array(s) and return relevant question object(s)
// Role questions
function getRoleDeptQuestion(deptNames) {
return [
{
type: "list",
message: "In which department is this role?",
name: "chosenDept",
choices: deptNames
}
];
};
function getRoleNameQuestion(roleNames) {
return {
type: "list",
message: "Which role?",
name: "jobTitle",
choices: roleNames
}
};
// Employee questions
function getEmployeeQuestions(managerNames, roleNames) {
const managerChoices = managerNames.concat("None");
return [
{
type: "list",
message: "What is the employee's job title?",
name: "jobTitle",
choices: roleNames
},
{
type: "list",
message: "Who is the employee's manager?",
name: "managerName",
choices: managerChoices
},
];
};
function getEmployeeNameQuestion(employeeNames) {
return {
type: "list",
message: "Which employee?",
name: "employeeChoice",
choices: employeeNames
}
};
// Department question
function getDepartmentQuestion(deptNames) {
return {
type: "list",
message: "Which department?",
name: "chosenDept",
choices: deptNames
}
};
// ==========================================================
// CRUD functionality
// Create functions
async function addDepartment() {
const deptQuestion = {
type: "input",
message: "Name of department?",
name: "deptName"
};
inquirer.prompt(deptQuestion).then(response => {
console.log("Creating a new department...\n");
connection.query(
"INSERT INTO department SET ?",
{
name: response.deptName
},
function (err, res) {
if (err) throw err;
console.log("Department added!\n");
openProcess();
});
}).catch(function (err) {
if (err) throw err;
});
};
async function addEmployee() {
const manQuery = "SELECT id, CONCAT(first_name,' ',last_name) AS manager_name FROM employee WHERE manager_id IS NULL";
const roleQuery = "SELECT id, title FROM role";
const managerNames = await getNames(manQuery, "manager");
const roleNames = await getNames(roleQuery, "role");
const employeeQuestions = await getEmployeeQuestions(managerNames, roleNames);
const roleId = await getId(employeeQuestions[0], "role");
const managerId = await getId(employeeQuestions[1], "employee");
inquirer.prompt(
[
{
type: "input",
message: "What is the employee's first name?",
name: "firstName"
},
{
type: "input",
message: "What is the employee's last name?",
name: "lastName"
},
]
).then(response => {
console.log("Adding employee...\n");
connection.query(
"INSERT INTO employee SET ?",
{
first_name: response.firstName,
last_name: response.lastName,
role_id: roleId,
manager_id: managerId
},
function (err, res) {
if (err) throw err;
console.log("Employee added!\n");
openProcess();
});
}).catch(function (err) {
if (err) throw err;
});
};
async function addRole() {
const deptQuery = "SELECT name FROM department";
const deptNames = await getNames(deptQuery, "department");
const roleQuestion = await getRoleDeptQuestion(deptNames);
const deptId = await getId(roleQuestion, "department");
inquirer.prompt(
[
{
type: "input",
message: "Name of role?",
name: "roleTitle"
},
{
type: "number",
message: "What is this role's salary?",
name: "roleSalary"
},
]
).then(response => {
console.log("Creating a new role...\n");
connection.query(
"INSERT INTO role SET ?",
{
title: response.roleTitle,
salary: response.roleSalary,
department_id: deptId
},
function (err, res) {
if (err) throw err;
console.log("Role added!\n");
openProcess();
});
}).catch(function (err) {
if (err) throw err;
});
};
// Read functions
// Views all given table and column names
function viewAll(table, col) {
console.log(`Selecting all ${table}s...\n`);
connection.query(
`SELECT ${col} FROM ${table}`, function (err, res) {
if (err) throw err;
console.table(res);
openProcess();
});
};
// Views employees by department or role given table and column names, connection query,
// and function to get the appropriate questions
async function viewBy(table, col, connQuery, qFunction) {
let resObj;
const dataQuery = `SELECT ${col} FROM ${table}`;
const dataNames = await getNames(dataQuery, table);
const dataListQ = await qFunction(dataNames);
inquirer.prompt(dataListQ).then(response => {
switch (table) {
case "department":
resObj = { name: response.chosenDept };
break;
case "role":
resObj = { title: response.jobTitle };
break;
default:
return null;
};
console.log(`Selecting all employees by ${table}...\n`);
connection.query(connQuery, resObj,
function (err, res) {
if (err) throw err;
console.table(res);
openProcess();
});
}).catch(function (err) {
if (err) throw err;
});
};
// View employees by manager
async function viewByManager() {
let cQuery;
const manQuery = "SELECT id, CONCAT(first_name,' ',last_name) AS manager_name FROM employee WHERE manager_id IS NULL";
const managerNames = await getNames(manQuery, "manager");
const employeeQuestions = await getEmployeeQuestions(managerNames);
const managerId = await getId(employeeQuestions[1], "employee");
console.log(`Selecting all employees by manager...\n`);
if (managerId === null) {
cQuery = "SELECT employee.first_name, employee.last_name FROM employee WHERE manager_id IS NULL";
} else {
cQuery = `SELECT employee.first_name, employee.last_name FROM employee WHERE manager_id = ${managerId}`
};
connection.query(cQuery,
function (err, res) {
if (err) throw err;
console.table(res);
openProcess();
}).catch(function (err) {
if (err) throw err;
});
};
// View department budgets
async function viewDeptBudget() {
const budgetQuery = "SELECT department.id, department.name, SUM(role.salary) AS total_budget FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id GROUP BY department.id, department.name";
connection.query(budgetQuery,
function (err, res) {
if (err) throw err;
console.table(res);
openProcess();
}).catch(function (err) {
if (err) throw err;
});
};
// Update function
// Update employee manager or role given table and condition (manager or role) names,
// query to get array of condition names, and function to get the appropriate questions
async function updateJobData(dataQuery, table, cond, qFunction) {
let dataId;
let resObj;
const empQuery = "SELECT CONCAT(first_name,' ',last_name) AS employee_name FROM employee";
const employeeNames = await getNames(empQuery, "employee");
const dataNames = await getNames(dataQuery, cond);
const dataQuestion = await qFunction(dataNames);
switch (table) {
case "employee":
dataId = await getId(dataQuestion[1], table);
break;
default:
dataId = await getId(dataQuestion, table);
};
switch (cond) {
case "role":
resObj = { role_id: dataId };
break;
default:
resObj = { manager_id: dataId };
};
inquirer.prompt(
[
{
type: "list",
message: "Which employee?",
name: "employeeChoice",
choices: employeeNames
},
]
).then(response => {
console.log(`Updating ${cond}...\n`);
const eName = response.employeeChoice.split(" ");
const fName = eName[0];
const lName = eName[1];
connection.query(
"UPDATE employee SET ? WHERE ? AND ?",
[
resObj,
{
first_name: fName
},
{
last_name: lName
}
],
function (err, res) {
if (err) throw err;
console.log(`${res.affectedRows} employee's ${cond} updated!\n`);
openProcess();
});
}).catch(function (err) {
if (err) throw err;
});
};
// Delete functions
// Delete employee by name
async function deleteEmployee() {
const empQuery = "SELECT CONCAT(first_name,' ',last_name) AS employee_name FROM employee";
const employeeNames = await getNames(empQuery, "employee");
const employeeQuestion = await getEmployeeNameQuestion(employeeNames);
inquirer.prompt(employeeQuestion).then(response => {
deleteThis("employee", response.employeeChoice, "Employee deleted!\n");
}).catch(function (err) {
if (err) throw err;
});
};
// Delete role by ID
async function deleteRole() {
const roleQuery = "SELECT id, title FROM role";
const roleNames = await getNames(roleQuery, "role");
const roleQuestion = getRoleNameQuestion(roleNames);
const roleId = await getId(roleQuestion, "role");
// Checks whether there are employees in that role
connection.query(`SELECT id FROM employee WHERE ?`,
{
role_id: roleId
},
function (err, res) {
if (err) throw err;
switch (res.length) {
// If no employees in role, deletes role
case 0:
deleteThis("role", roleId, "Role deleted!\n");
break;
default:
// If employees in role, confirms whether user wants to continue
inquirer.prompt(
{
type: "list",
message: `${res.length} employee(s) currently hold this role. If you delete this role, those employees will also be deleted. Continue?`,
name: "roleConfirm",
choices: ["Yes", "No"]
}
).then(function (res) {
switch (res.roleConfirm) {
case "No":
openProcess();
break;
// If confirmed, deletes role and associated employee(s) on cascade
default:
deleteThis("role", roleId, "Role and associated employees deleted!\n");
};
}).catch(function (err) {
if (err) throw err;
});
};
});
};
// Delete department
async function deleteDepartment() {
const deptQuery = "SELECT name, id FROM department";
const deptNames = await getNames(deptQuery, "department");
const deptQuestion = getDepartmentQuestion(deptNames);
const deptId = await getId(deptQuestion, "department");
console.log(deptId);
// Checks whether there are any employees in that department
cQuery = `SELECT employee.id, role.id FROM employee INNER JOIN role ON employee.role_id = role.id WHERE role.department_id = ${deptId}`;
connection.query(cQuery, function (err, res) {
if (err) throw err;
console.log(res.length);
switch (res.length) {
// If not, confirms that user wants to delete department and associated role(s)
case 0:
inquirer.prompt(
{
type: "list",
message: "This action will also delete all roles in this department. Continue?",
name: "deptRoleConfirm",
choices: ["Yes", "No"]
}
).then(function (res) {
switch (res.deptRoleConfirm) {
case "No":
openProcess();
break;
// If confirmed, deletes department and associated role(s) on cascade
default:
deleteThis("department", deptId, "Department and associated roles deleted!\n");
};
}).catch(function (err) {
if (err) throw err;
});
break;
// If there are employees in the department, confirms that user wants to delete department
// and associated role(s) and employee(s)
default:
inquirer.prompt(
{
type: "list",
message: `This action will also delete the ${res.length} employee(s) and any associated roles in this department. Continue?`,
name: "deptEmployeeConfirm",
choices: ["Yes", "No"]
}
).then(function (res) {
switch (res.deptEmployeeConfirm) {
case "No":
openProcess();
break;
// If confirmed, deletes department and associated role(s) and employee(s) on cascade
default:
deleteThis("department", deptId, "Department and associated role(s) & employee(s) deleted!\n");
};
}).catch(function (err) {
if (err) throw err;
});
};
});
};
// BEGIN
openProcess();