-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleView.java
More file actions
448 lines (409 loc) · 18.3 KB
/
Copy pathConsoleView.java
File metadata and controls
448 lines (409 loc) · 18.3 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
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
package com.strms.view;
import com.strms.controller.TaskManager;
import com.strms.enums.NotificationType;
import com.strms.enums.PriorityLevel;
import com.strms.enums.TaskCategory;
import com.strms.enums.TaskStatus;
import com.strms.exceptions.CircularDependencyException;
import com.strms.exceptions.DependencyNotCompletedException;
import com.strms.exceptions.DuplicateTaskException;
import com.strms.exceptions.FilePersistenceException;
import com.strms.exceptions.InvalidRoleException;
import com.strms.exceptions.InvalidTaskStateException;
import com.strms.exceptions.TaskNotFoundException;
import com.strms.model.Task;
import com.strms.model.TaskHistoryEntry;
import com.strms.model.User;
import com.strms.utils.ReportGenerator;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Scanner;
/**
* Console-based view for the STRMS application.
* Handles menu display and user input, delegating all business logic to TaskManager.
*/
public class ConsoleView {
private static final String SEPARATOR = "────────────────────────────────────────";
private final TaskManager taskManager;
private final Scanner scanner;
private User activeUser;
/**
* @param taskManager the controller to delegate operations to
*/
public ConsoleView(TaskManager taskManager) {
if (taskManager == null) throw new IllegalArgumentException("TaskManager must not be null");
this.taskManager = taskManager;
this.scanner = new Scanner(System.in);
}
/**
* Sets the currently active user for the session.
*
* @param user the active user
*/
public void setActiveUser(User user) {
this.activeUser = user;
System.out.println("Active user set to: " + user.getName() + " [" + user.getRole() + "]");
}
/** Launches the interactive main menu loop. */
public void start() {
System.out.println("╔══════════════════════════════════════════╗");
System.out.println("║ Smart Task & Resource Management System ║");
System.out.println("║ STRMS v1.0 ║");
System.out.println("╚══════════════════════════════════════════╝");
if (activeUser == null) {
System.out.println("No active user set. Please call setActiveUser() before start().");
return;
}
boolean running = true;
while (running) {
printMainMenu();
String choice = prompt("Select option");
switch (choice) {
case "1" -> handleAddTask();
case "2" -> handleDeleteTask();
case "3" -> handleAssignTask();
case "4" -> handleStartTask();
case "5" -> handleCompleteTask();
case "6" -> handleAddDependency();
case "7" -> handleRemoveDependency();
case "8" -> handleViewAllTasks();
case "9" -> handleViewTaskDetails();
case "10" -> handleViewInProgress();
case "11" -> handleSwitchUser();
case "12" -> handleSaveToFile();
case "13" -> handleLoadFromFile();
case "14" -> handleShowReport();
case "15" -> { running = false; System.out.println("Goodbye!"); }
case "16" -> handleUpdateTask();
default -> System.out.println("[!] Invalid option. Please try again.");
}
}
}
/** Prints the main navigation menu. */
public void printMainMenu() {
System.out.println("\n" + SEPARATOR);
System.out.println(" Logged in as: " + activeUser.getName()
+ " [" + activeUser.getRole() + "]");
System.out.println(SEPARATOR);
System.out.println(" 1. Add Task");
System.out.println(" 2. Delete Task");
System.out.println(" 3. Assign Task to Engineer");
System.out.println(" 4. Start Task");
System.out.println(" 5. Complete Task");
System.out.println(" 6. Add Dependency");
System.out.println(" 7. Remove Dependency");
System.out.println(" 8. View All Tasks");
System.out.println(" 9. View Task Details");
System.out.println(" 10. View In-Progress Tasks");
System.out.println(" 11. Switch Active User");
System.out.println(" 12. Save Tasks to File");
System.out.println(" 13. Load Tasks from File");
System.out.println(" 14. Generate Report");
System.out.println(" 15. Exit");
System.out.println(" 16. Update Task");
System.out.println(SEPARATOR);
}
/** Collects task fields from stdin and delegates to TaskManager.addTask. */
private void handleAddTask() {
System.out.println("\n-- Add New Task --");
String id = prompt("Task ID");
String title = prompt("Title");
String description = prompt("Description");
PriorityLevel pl = promptEnum(PriorityLevel.class, "Priority");
TaskCategory cat = promptEnum(TaskCategory.class, "Category");
String deadlineStr = prompt("Deadline (YYYY-MM-DD, or NONE)");
LocalDate deadline = "NONE".equalsIgnoreCase(deadlineStr)
? null : LocalDate.parse(deadlineStr);
Task task = new Task(id, title, description, pl, cat, deadline);
try {
taskManager.addTask(task, activeUser);
System.out.println("[✓] Task '" + id + "' added successfully.");
} catch (InvalidRoleException | DuplicateTaskException e) {
printError(e.getMessage());
}
}
/** Prompts for a task ID and deletes it. */
private void handleDeleteTask() {
System.out.println("\n-- Delete Task --");
String taskId = prompt("Task ID to delete");
try {
taskManager.deleteTask(taskId, activeUser);
System.out.println("[✓] Task '" + taskId + "' deleted.");
} catch (InvalidRoleException | TaskNotFoundException e) {
printError(e.getMessage());
}
}
/** Prompts for task and engineer IDs and assigns the task. */
private void handleAssignTask() {
System.out.println("\n-- Assign Task --");
String taskId = prompt("Task ID");
String engineerId = prompt("Engineer User ID");
try {
taskManager.assignTask(taskId, engineerId, activeUser);
System.out.println("[✓] Task '" + taskId + "' assigned to engineer '" + engineerId + "'.");
} catch (InvalidRoleException | TaskNotFoundException e) {
printError(e.getMessage());
}
}
/** Prompts for a task ID and starts it. */
private void handleStartTask() {
System.out.println("\n-- Start Task --");
String taskId = prompt("Task ID to start");
try {
taskManager.startTask(taskId, activeUser);
System.out.println("[✓] Task '" + taskId + "' is now IN_PROGRESS.");
} catch (TaskNotFoundException | InvalidTaskStateException
| DependencyNotCompletedException e) {
printError(e.getMessage());
}
}
/** Prompts for a task ID and marks it complete. */
private void handleCompleteTask() {
System.out.println("\n-- Complete Task --");
String taskId = prompt("Task ID to complete");
try {
taskManager.completeTask(taskId, activeUser);
System.out.println("[✓] Task '" + taskId + "' marked as DONE.");
} catch (TaskNotFoundException | InvalidTaskStateException e) {
printError(e.getMessage());
}
}
/** Prompts for task and dependency IDs and adds the dependency. */
private void handleAddDependency() {
System.out.println("\n-- Add Dependency --");
String taskId = prompt("Task ID (the dependent task)");
String depId = prompt("Dependency Task ID (must be DONE first)");
try {
taskManager.addDependency(taskId, depId);
System.out.println("[✓] Dependency added: '" + taskId + "' depends on '" + depId + "'.");
} catch (TaskNotFoundException | CircularDependencyException
| InvalidTaskStateException e) {
printError(e.getMessage());
}
}
/** Prompts for task and dependency IDs and removes the dependency. */
private void handleRemoveDependency() {
System.out.println("\n-- Remove Dependency --");
String taskId = prompt("Task ID");
String depId = prompt("Dependency Task ID to remove");
try {
taskManager.removeDependency(taskId, depId);
System.out.println("[✓] Dependency removed: '" + taskId + "' no longer depends on '" + depId + "'.");
} catch (TaskNotFoundException e) {
printError(e.getMessage());
}
}
/** Prints a summary line for every registered task. */
private void handleViewAllTasks() {
System.out.println("\n-- All Tasks --");
Collection<Task> allTasks = taskManager.getAllTasks();
if (allTasks.isEmpty()) {
System.out.println(" (no tasks registered)");
return;
}
allTasks.stream()
.sorted()
.forEach(this::printTaskSummary);
}
/** Prompts for a task ID and prints full details including history. */
private void handleViewTaskDetails() {
System.out.println("\n-- Task Details --");
String taskId = prompt("Task ID");
try {
Task task = taskManager.findTask(taskId);
printTaskDetails(task);
} catch (TaskNotFoundException e) {
printError(e.getMessage());
}
}
/** Shows all in-progress tasks. */
private void handleViewInProgress() {
taskManager.printInProgressTasks();
}
/** Allows switching the active user by entering a registered user ID. */
private void handleSwitchUser() {
System.out.println("\n-- Switch Active User --");
System.out.println(" Registered users:");
taskManager.getAllUsers().forEach(u ->
System.out.println(" " + u.getId() + " → " + u.getName() + " [" + u.getRole() + "]"));
String userId = prompt("Enter User ID");
User found = taskManager.findUser(userId);
if (found == null) {
printError("No user found with ID: " + userId);
} else {
setActiveUser(found);
}
}
/** Prompts for a file path and saves tasks to CSV. */
private void handleSaveToFile() {
System.out.println("\n-- Save Tasks to File --");
String filepath = prompt("File path (e.g. tasks.csv)");
try {
taskManager.saveTasksToFile(filepath);
System.out.println("[✓] Tasks saved to '" + filepath + "'.");
} catch (FilePersistenceException e) {
printError(e.getMessage());
}
}
/** Prompts for a file path and loads tasks from CSV. */
private void handleLoadFromFile() {
System.out.println("\n-- Load Tasks from File --");
String filepath = prompt("File path (e.g. tasks.csv)");
try {
taskManager.loadTasksFromFile(filepath);
System.out.println("[✓] Tasks loaded from '" + filepath + "'.");
} catch (FilePersistenceException e) {
printError(e.getMessage());
}
}
/** Prompts for a task ID and optional new values, then calls updateTask(). */
private void handleUpdateTask() {
System.out.println("\n-- Update Task --");
String taskId = prompt("Task ID to update");
System.out.println(" Leave any field blank to keep its current value.");
String newTitle = prompt("New title (or ENTER to skip)");
if (newTitle.isEmpty()) newTitle = null;
String newDescription = prompt("New description (or ENTER to skip)");
if (newDescription.isEmpty()) newDescription = null;
System.out.println(" Priority options (or ENTER to skip):");
PriorityLevel[] pLevels = PriorityLevel.values();
for (int i = 0; i < pLevels.length; i++) {
System.out.println(" " + (i + 1) + ". " + pLevels[i].name());
}
String priorityInput = prompt("New priority (name, number, or ENTER to skip)");
PriorityLevel newPriority = null;
if (!priorityInput.isEmpty()) {
try {
int idx = Integer.parseInt(priorityInput) - 1;
if (idx >= 0 && idx < pLevels.length) newPriority = pLevels[idx];
} catch (NumberFormatException ignored) {
try { newPriority = PriorityLevel.valueOf(priorityInput.toUpperCase()); }
catch (IllegalArgumentException e) { System.out.println(" [!] Invalid priority — skipped."); }
}
}
System.out.println(" Category options (or ENTER to skip):");
TaskCategory[] cats = TaskCategory.values();
for (int i = 0; i < cats.length; i++) {
System.out.println(" " + (i + 1) + ". " + cats[i].name());
}
String categoryInput = prompt("New category (name, number, or ENTER to skip)");
TaskCategory newCategory = null;
if (!categoryInput.isEmpty()) {
try {
int idx = Integer.parseInt(categoryInput) - 1;
if (idx >= 0 && idx < cats.length) newCategory = cats[idx];
} catch (NumberFormatException ignored) {
try { newCategory = TaskCategory.valueOf(categoryInput.toUpperCase()); }
catch (IllegalArgumentException e) { System.out.println(" [!] Invalid category — skipped."); }
}
}
String deadlineInput = prompt("New deadline (YYYY-MM-DD, or ENTER to skip)");
LocalDate newDeadline = null;
if (!deadlineInput.isEmpty()) {
try { newDeadline = LocalDate.parse(deadlineInput); }
catch (Exception e) { System.out.println(" [!] Invalid date format — skipped."); }
}
try {
taskManager.updateTask(taskId, newTitle, newDescription, newPriority, newCategory, newDeadline, activeUser);
System.out.println("[✓] Task '" + taskId + "' updated successfully.");
} catch (InvalidRoleException | TaskNotFoundException e) {
printError(e.getMessage());
}
}
/** Generates and prints the full system report. */
private void handleShowReport() {
ReportGenerator gen = new ReportGenerator(
taskManager.getAllTasks(), taskManager.getAllUsers());
System.out.println(gen.generateReport());
}
/**
* Prints a one-line task summary.
*
* @param task the task to display
*/
public void printTaskSummary(Task task) {
String assignee = task.getAssignedTo() != null ? task.getAssignedTo().getName() : "—";
System.out.printf(" [%s] %-30s | %-12s | %-8s | Assignee: %s%n",
task.getId(), task.getTitle(), task.getStatus(), task.getPriorityLevel(), assignee);
}
/**
* Prints full task details including dependencies and history.
*
* @param task the task to display
*/
public void printTaskDetails(Task task) {
System.out.println("\n" + SEPARATOR);
System.out.println(" Task ID : " + task.getId());
System.out.println(" Title : " + task.getTitle());
System.out.println(" Description: " + task.getDescription());
System.out.println(" Status : " + task.getStatus());
System.out.println(" Priority : " + task.getPriorityLevel());
System.out.println(" Category : " + task.getCategory());
System.out.println(" Deadline : " + (task.getDeadline() != null ? task.getDeadline() : "none"));
System.out.println(" Assigned To: "
+ (task.getAssignedTo() != null ? task.getAssignedTo().getName() : "unassigned"));
System.out.println(" Dependencies:");
if (task.getDependencies().isEmpty()) {
System.out.println(" (none)");
} else {
task.getDependencies().forEach(d ->
System.out.println(" → " + d.getId() + " [" + d.getStatus() + "] " + d.getTitle()));
}
System.out.println(" History (" + task.getHistory().size() + " entries):");
for (TaskHistoryEntry entry : task.getHistory()) {
System.out.println(" " + entry);
}
System.out.println(SEPARATOR);
}
/**
* Prints user identity information.
*
* @param user the user to display
*/
public void printUserInfo(User user) {
System.out.println(" User: " + user.getName()
+ " | Role: " + user.getRole()
+ " | Email: " + user.getEmail()
+ " | ID: " + user.getId());
}
/**
* Prints a prompt and reads a trimmed line from stdin.
*
* @param label the prompt text
* @return the trimmed input
*/
private String prompt(String label) {
System.out.print(" " + label + ": ");
return scanner.nextLine().trim();
}
/**
* Prompts the user to pick an enum value by name or number.
*
* @param type the enum class
* @param label the prompt label
* @return the chosen enum constant
*/
private <E extends Enum<E>> E promptEnum(Class<E> type, String label) {
E[] values = type.getEnumConstants();
System.out.println(" " + label + " options:");
for (int i = 0; i < values.length; i++) {
System.out.println(" " + (i + 1) + ". " + values[i].name());
}
while (true) {
String input = prompt(label + " (name or number)").toUpperCase();
try {
int idx = Integer.parseInt(input) - 1;
if (idx >= 0 && idx < values.length) return values[idx];
} catch (NumberFormatException ignored) {
try {
return Enum.valueOf(type, input);
} catch (IllegalArgumentException ignored2) { }
}
System.out.println(" [!] Invalid choice. Try again.");
}
}
/** Prints a formatted error message. */
private void printError(String message) {
System.out.println(" [✗] ERROR: " + message);
}
}