-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskManager.java
More file actions
509 lines (473 loc) · 20.5 KB
/
Copy pathTaskManager.java
File metadata and controls
509 lines (473 loc) · 20.5 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
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
package com.strms.controller;
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.interfaces.Assignable;
import com.strms.model.Admin;
import com.strms.model.Engineer;
import com.strms.model.Task;
import com.strms.model.User;
import com.strms.utils.FileManager;
import com.strms.utils.NotificationManager;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Central controller for the STRMS application.
* All business operations on tasks and users go through this class.
* Role-based permission checks are enforced on every mutating operation.
*/
public class TaskManager implements Assignable {
private static final User SYSTEM = new Admin("SYSTEM", "System", "system@strms.local");
private final HashMap<String, Task> tasks;
private final HashMap<String, User> users;
private final PriorityQueue<Task> readyQueue;
private final HashSet<Task> inProgress;
private final NotificationManager notificationManager;
private final FileManager fileManager;
/** Constructs an empty TaskManager. */
public TaskManager() {
this.tasks = new HashMap<>();
this.users = new HashMap<>();
this.readyQueue = new PriorityQueue<>();
this.inProgress = new HashSet<>();
this.notificationManager = new NotificationManager();
this.fileManager = new FileManager();
}
/**
* Registers a user in the system.
*
* @param user the user to register
*/
public void addUser(User user) {
if (user == null) throw new IllegalArgumentException("User must not be null");
users.put(user.getId(), user);
}
/**
* @param userId the user ID to look up
* @return the matching User, or null if not found
*/
public User findUser(String userId) {
return users.get(userId);
}
/**
* Registers a new task. If it has no dependencies it is immediately enqueued in the ready queue.
*
* @param task the task to add
* @param requester the user requesting the operation
* @throws InvalidRoleException if the requester cannot create tasks
* @throws DuplicateTaskException if a task with the same ID already exists
*/
public void addTask(Task task, User requester) throws InvalidRoleException, DuplicateTaskException {
if (!requester.canCreateTask()) {
throw new InvalidRoleException(requester.getId(), "create task");
}
if (tasks.containsKey(task.getId())) {
throw new DuplicateTaskException(task.getId());
}
tasks.put(task.getId(), task);
if (task.getStatus() == TaskStatus.TODO && task.getDependencies().isEmpty()) {
readyQueue.offer(task);
}
task.addHistoryEntry(requester, "Task created with status " + task.getStatus());
}
/**
* Permanently removes a task and purges it from all data structures, including
* the dependency lists of other tasks that reference it.
*
* @param taskId the ID of the task to remove
* @param requester the user requesting the operation
* @throws InvalidRoleException if the requester cannot delete tasks
* @throws TaskNotFoundException if no task with that ID exists
*/
public void deleteTask(String taskId, User requester)
throws InvalidRoleException, TaskNotFoundException {
if (!requester.canDeleteTask()) {
throw new InvalidRoleException(requester.getId(), "delete task");
}
Task task = findTask(taskId);
tasks.remove(taskId);
readyQueue.remove(task);
inProgress.remove(task);
for (Task other : tasks.values()) {
other.removeDependency(task);
}
}
/**
* Updates one or more fields of an existing task. Pass null to leave a field unchanged.
*
* @throws InvalidRoleException if the requester cannot edit tasks
* @throws TaskNotFoundException if no task with that ID exists
*/
public void updateTask(String taskId, String newTitle, String newDescription,
PriorityLevel newPriority, TaskCategory newCategory,
LocalDate newDeadline, User requester)
throws InvalidRoleException, TaskNotFoundException {
if (!requester.canCreateTask()) {
throw new InvalidRoleException(requester.getId(), "update task");
}
Task task = findTask(taskId);
StringBuilder changes = new StringBuilder("Task updated:");
if (newTitle != null && !newTitle.isBlank()) {
task.setTitle(newTitle);
changes.append(" title,");
}
if (newDescription != null && !newDescription.isBlank()) {
task.setDescription(newDescription);
changes.append(" description,");
}
if (newPriority != null) {
boolean wasInReady = readyQueue.remove(task);
task.setPriorityLevel(newPriority);
if (wasInReady) readyQueue.offer(task);
changes.append(" priority=" + newPriority + ",");
}
if (newCategory != null) {
task.setCategory(newCategory);
changes.append(" category=" + newCategory + ",");
}
if (newDeadline != null) {
task.setDeadline(newDeadline);
changes.append(" deadline=" + newDeadline + ",");
}
task.addHistoryEntry(requester, changes.toString().replaceAll(",$", ""));
}
/**
* @param taskId the task ID to look up
* @return the matching Task
* @throws TaskNotFoundException if no task with that ID exists
*/
public Task findTask(String taskId) throws TaskNotFoundException {
Task task = tasks.get(taskId);
if (task == null) throw new TaskNotFoundException(taskId);
return task;
}
/**
* Assigns a task to an engineer and sends a notification.
*
* @param task the task to assign
* @param engineer the engineer who will own the task
* @param requester the user requesting the assignment
* @throws InvalidRoleException if the requester cannot assign tasks
* @throws TaskNotFoundException if the task is not registered
*/
@Override
public void assignTask(Task task, Engineer engineer, User requester)
throws InvalidRoleException, TaskNotFoundException {
if (!requester.canAssignTask()) {
throw new InvalidRoleException(requester.getId(), "assign task");
}
if (!tasks.containsKey(task.getId())) {
throw new TaskNotFoundException(task.getId());
}
task.setAssignedTo(engineer);
task.addHistoryEntry(requester, "Assigned to engineer: " + engineer.getName());
notificationManager.sendNotification(
engineer,
"You have been assigned task [" + task.getId() + "]: " + task.getTitle(),
NotificationType.CONSOLE);
}
/**
* Resolves task and engineer by ID, then delegates to assignTask(Task, Engineer, User).
*
* @throws InvalidRoleException if the requester cannot assign tasks or the user is not an Engineer
* @throws TaskNotFoundException if the task or engineer ID is not found
*/
public void assignTask(String taskId, String engineerId, User requester)
throws InvalidRoleException, TaskNotFoundException {
Task task = findTask(taskId);
User user = users.get(engineerId);
if (user == null) {
throw new TaskNotFoundException("User not found with ID: " + engineerId);
}
if (!(user instanceof Engineer)) {
throw new InvalidRoleException(engineerId,
"receive task assignment (role is " + user.getRole() + ", not Engineer)");
}
assignTask(task, (Engineer) user, requester);
}
/**
* Transitions a task from TODO or BLOCKED to IN_PROGRESS.
* Throws DependencyNotCompletedException if any dependency is not yet DONE.
*
* @throws TaskNotFoundException if no task with that ID exists
* @throws InvalidTaskStateException if the task is already DONE or IN_PROGRESS
* @throws DependencyNotCompletedException if one or more dependencies are unmet
*/
public void startTask(String taskId, User requester)
throws TaskNotFoundException, InvalidTaskStateException, DependencyNotCompletedException {
Task task = findTask(taskId);
if (task.getStatus() == TaskStatus.DONE) {
throw new InvalidTaskStateException(taskId, TaskStatus.DONE.name(), TaskStatus.IN_PROGRESS.name());
}
if (task.getStatus() == TaskStatus.IN_PROGRESS) {
throw new InvalidTaskStateException(taskId, TaskStatus.IN_PROGRESS.name(), TaskStatus.IN_PROGRESS.name());
}
if (task.hasUnmetDependencies()) {
Task blocker = task.getDependencies().stream()
.filter(t -> t.getStatus() != TaskStatus.DONE)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Inconsistent state: unmet dep not found"));
task.setStatus(TaskStatus.BLOCKED);
readyQueue.remove(task);
task.addHistoryEntry(requester,
"Start attempted; blocked by dependency: " + blocker.getId());
throw new DependencyNotCompletedException(taskId, blocker.getId());
}
readyQueue.remove(task);
task.setStatus(TaskStatus.IN_PROGRESS);
inProgress.add(task);
task.addHistoryEntry(requester, "Task started (status → IN_PROGRESS)");
}
/**
* Transitions a task from IN_PROGRESS to DONE.
* Automatically promotes any BLOCKED tasks whose dependencies are now fully met.
*
* @throws TaskNotFoundException if no task with that ID exists
* @throws InvalidTaskStateException if the task is not IN_PROGRESS
*/
public void completeTask(String taskId, User requester)
throws TaskNotFoundException, InvalidTaskStateException {
Task task = findTask(taskId);
if (task.getStatus() != TaskStatus.IN_PROGRESS) {
throw new InvalidTaskStateException(
taskId, task.getStatus().name(), TaskStatus.DONE.name());
}
task.setStatus(TaskStatus.DONE);
inProgress.remove(task);
task.addHistoryEntry(requester, "Task completed (status → DONE)");
if (task.getAssignedTo() != null) {
notificationManager.sendNotification(
task.getAssignedTo(),
"Task [" + task.getId() + "] \"" + task.getTitle() + "\" has been marked DONE.",
NotificationType.CONSOLE);
}
refreshBlockedTasks(requester);
}
/**
* Adds a dependency edge: taskId depends on dependencyId.
* The edge is added speculatively; if a cycle is detected it is rolled back.
*
* @throws TaskNotFoundException if either ID does not exist
* @throws CircularDependencyException if adding the edge would create a cycle
* @throws InvalidTaskStateException if the dependent task is already DONE
*/
public void addDependency(String taskId, String dependencyId)
throws TaskNotFoundException, CircularDependencyException, InvalidTaskStateException {
if (taskId.equals(dependencyId)) {
throw new CircularDependencyException(taskId, dependencyId);
}
Task task = findTask(taskId);
Task dependency = findTask(dependencyId);
if (task.getStatus() == TaskStatus.DONE) {
throw new InvalidTaskStateException(taskId, TaskStatus.DONE.name(), "add dependency");
}
task.addDependency(dependency);
if (detectCircularDependency(taskId)) {
task.removeDependency(dependency);
throw new CircularDependencyException(taskId, dependencyId);
}
if (task.getStatus() == TaskStatus.TODO && dependency.getStatus() != TaskStatus.DONE) {
task.setStatus(TaskStatus.BLOCKED);
readyQueue.remove(task);
}
task.addHistoryEntry(SYSTEM, "Dependency added: must wait for task " + dependencyId);
}
/**
* Removes a dependency edge. If the task was BLOCKED and now has all deps met,
* it is promoted back to TODO and re-enqueued.
*
* @throws TaskNotFoundException if either ID does not exist
*/
public void removeDependency(String taskId, String dependencyId) throws TaskNotFoundException {
Task task = findTask(taskId);
Task dependency = findTask(dependencyId);
boolean removed = task.removeDependency(dependency);
if (removed) {
task.addHistoryEntry(SYSTEM, "Dependency removed: " + dependencyId);
if (task.getStatus() == TaskStatus.BLOCKED && task.allDependenciesMet()) {
task.setStatus(TaskStatus.TODO);
readyQueue.offer(task);
task.addHistoryEntry(SYSTEM, "All dependencies met after removal of "
+ dependencyId + "; status -> TODO");
}
}
}
/**
* Returns true if the dependency graph contains a cycle reachable from startTaskId.
* Uses recursive DFS; a back-edge (node on the current stack) indicates a cycle.
*/
public boolean detectCircularDependency(String startTaskId) {
Task start = tasks.get(startTaskId);
if (start == null) return false;
Set<String> visited = new HashSet<>();
Set<String> stack = new HashSet<>();
return dfs(start, visited, stack);
}
/** DFS helper: returns true if a cycle is found in the subgraph rooted at task. */
private boolean dfs(Task task, Set<String> visited, Set<String> stack) {
visited.add(task.getId());
stack.add(task.getId());
for (Task dep : task.getDependencies()) {
if (!visited.contains(dep.getId())) {
if (dfs(dep, visited, stack)) return true;
} else if (stack.contains(dep.getId())) {
return true;
}
}
stack.remove(task.getId());
return false;
}
/** Promotes any BLOCKED tasks whose dependencies are now fully satisfied back to TODO. */
private void refreshBlockedTasks(User actor) {
for (Task t : tasks.values()) {
if (t.getStatus() == TaskStatus.BLOCKED && t.allDependenciesMet()) {
t.setStatus(TaskStatus.TODO);
readyQueue.offer(t);
t.addHistoryEntry(actor, "All dependencies satisfied; status → TODO (ready to start)");
}
}
}
/** Prints all tasks currently IN_PROGRESS. */
public void printInProgressTasks() {
System.out.println("════════════════════════════════════════");
System.out.println(" Tasks Currently IN PROGRESS");
System.out.println("════════════════════════════════════════");
if (inProgress.isEmpty()) {
System.out.println(" (none)");
} else {
inProgress.stream()
.sorted()
.forEach(t -> System.out.println(" » " + t));
}
System.out.println("════════════════════════════════════════");
}
/**
* Persists the current task registry to a CSV file.
*
* @param filepath the target file path
* @throws FilePersistenceException if the write fails
*/
public void saveTasksToFile(String filepath) throws FilePersistenceException {
fileManager.save(filepath, new java.util.ArrayList<>(tasks.values()));
}
/**
* Loads tasks from a CSV file, replacing the current task registry.
* Dependency links referencing unknown IDs are skipped with a warning.
*
* @param filepath the source file path
* @throws FilePersistenceException if the read fails
*/
public void loadTasksFromFile(String filepath) throws FilePersistenceException {
java.util.List<Task> loaded = fileManager.load(filepath);
tasks.clear();
readyQueue.clear();
inProgress.clear();
for (Task t : loaded) {
tasks.put(t.getId(), t);
if (t.getStatus() == TaskStatus.TODO && t.getDependencies().isEmpty()) {
readyQueue.offer(t);
} else if (t.getStatus() == TaskStatus.IN_PROGRESS) {
inProgress.add(t);
}
}
}
/** @return an unmodifiable view of all registered tasks */
public Collection<Task> getAllTasks() {
return Collections.unmodifiableCollection(tasks.values());
}
/** @return an unmodifiable view of all registered users */
public Collection<User> getAllUsers() {
return Collections.unmodifiableCollection(users.values());
}
/** @return a snapshot copy of the ready queue */
public PriorityQueue<Task> getReadyQueue() {
return new PriorityQueue<>(readyQueue);
}
/** @return an unmodifiable view of in-progress tasks */
public Set<Task> getInProgressTasks() {
return Collections.unmodifiableSet(inProgress);
}
/** @return an unmodifiable view of the full task map (ID → Task) */
public Map<String, Task> getTaskMap() {
return Collections.unmodifiableMap(tasks);
}
/** @return an unmodifiable view of the full user map (ID → User) */
public Map<String, User> getUserMap() {
return Collections.unmodifiableMap(users);
}
// =========================================================================
// METHODES PERSONNE 4
// =========================================================================
/**
* Returns all tasks with the given status, sorted by descending priority.
*/
public List<Task> listTasksByStatus(TaskStatus status) {
return tasks.values().stream()
.filter(t -> t.getStatus() == status)
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
}
/**
* Returns all tasks assigned to the given engineer.
*/
public List<Task> listTasksByUser(Engineer engineer) {
return tasks.values().stream()
.filter(t -> engineer.equals(t.getAssignedTo()))
.collect(Collectors.toList());
}
/**
* Returns the highest-priority task from the ready queue that is not BLOCKED.
*/
public Task getNextTask() {
PriorityQueue<Task> snapshot = new PriorityQueue<>(readyQueue);
while (!snapshot.isEmpty()) {
Task candidate = snapshot.poll();
if (!candidate.isBlocked()) {
return candidate;
}
}
return null;
}
/**
* Unassigns the engineer from a task.
* Only Admin or Manager can unassign.
*/
public void unassignTask(Task task, User requester)
throws InvalidRoleException, TaskNotFoundException {
if (!requester.canAssignTask()) {
throw new InvalidRoleException(requester.getId(), "unassign task");
}
if (!tasks.containsKey(task.getId())) {
throw new TaskNotFoundException(task.getId());
}
Engineer previous = task.getAssignedTo();
task.setAssignedTo(null);
String note = (previous != null)
? "Unassigned from engineer: " + previous.getName()
: "Unassign called but task had no assigned engineer";
task.addHistoryEntry(requester, note);
if (previous != null) {
notificationManager.sendNotification(
previous,
"You have been unassigned from task [" + task.getId() + "]: " + task.getTitle(),
NotificationType.CONSOLE);
}
}
}