diff --git a/AGENTS.md b/AGENTS.md index b591e20..6899c8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,13 +73,14 @@ Syncs the whole H2 file. OAuth client credentials live in `bootstrap/PendingDownloadApplier` swaps it in at the next launch, before Spring opens H2. There is no live reload, and nothing is downloaded automatically at startup. -- Startup maintenance (marking delayed tasks, sweeping overdue goal attempts) +- Startup maintenance (marking delayed tasks, sweeping overdue goal attempts, + normalizing achieved goal checklists) is derived data every machine recomputes, so it must not set the dirty flag: otherwise merely opening the app looks like unsaved edits and raises a false sync conflict. `StudySyncUI.runStartupMaintenance` wraps it in `GoogleDriveService.runStartupMaintenanceWithoutDirtyTracking`, and the goal - sweep saves through `StudyService.saveLocallyWithoutDirtyFlag` (its javadoc - says why the wrapper alone is not enough). It runs only once the startup + sweep and checklist repair save through `StudyService.saveLocallyWithoutDirtyFlag` + (its javadoc says why the wrapper alone is not enough). It runs only once the startup Drive check reports up to date, local newer, unknown or disabled; never with a newer Drive copy, a conflict, or a staged download pending. Reading goals also sweeps overdue attempts, so `StudySyncUI` holds that sweep @@ -186,10 +187,22 @@ Syncs the whole H2 file. OAuth client credentials live in (not the attempt) so a retry continues from earlier ticks. Only `StudyGoal.parseCriteria` / `serializeCriteria` know its `[x] ` / `[ ] ` line format. -- Ticking the last criterion achieves the current attempt through the same path - as the checkbox (`StudyService.setGoalCriterionDone`); unticking one reopens - an achieved goal. The checkbox also works alone, so a goal can be achieved - with criteria open or with no checklist. There is no partial credit. +- The checkbox and the checklist mirror each other, so a goal with a checklist + is achieved exactly when every line is ticked. Ticking the last criterion + achieves the current attempt and unticking one reopens it, keeping the other + ticks (`StudyService.setGoalCriterionDone`). Ticking the checkbox ticks every + line and unticking it clears them (`updateStudyGoalAchievement`); a goal it + cannot change keeps its ticks. A checklist edit re-applies the rule. An + earlier day's achieved goal stays achieved with its lines ticked + (`StudyGoal.isAchievedBefore`): reopening it would leave a past pending + attempt that is swept to missed, so unticking it changes nothing, the planner + shows it read-only, and a checklist edit ticks its new lines instead. A + missed or dropped attempt can be neither achieved nor ticked; a retry + continues from its ticks. When those ticks are already complete, a retry or + reopen must say what to do (`StudyService.CompletedChecklist`): start the + checklist over, or mark the goal done with an attempt dated today. The + planner asks in the retry row; date dialogs use `GoalActions.ChecklistChoice`. + A goal without a checklist uses the checkbox alone. There is no partial credit. - Goal forms reuse `GoalEditFields` and `TaskStyleUtils.criteriaArea` / `CRITERIA_LABEL` / `criteriaChecklist` / `criteriaProgress`. A task's `done_criteria` is plain text, not a checklist. diff --git a/src/main/java/com/studysync/domain/entity/StudyGoal.java b/src/main/java/com/studysync/domain/entity/StudyGoal.java index 22a3709..02056ce 100644 --- a/src/main/java/com/studysync/domain/entity/StudyGoal.java +++ b/src/main/java/com/studysync/domain/entity/StudyGoal.java @@ -235,6 +235,14 @@ public void setAchieved(boolean achieved) { } } + /** + * Achieved on a day before {@code today}. That achievement is history: reopening it would leave a + * pending attempt in the past that the next refresh sweeps to missed, so nothing reopens it. + */ + public boolean isAchievedBefore(LocalDate today) { + return achieved && date != null && date.isBefore(today); + } + public String getReasonIfNotAchieved() { return reasonIfNotAchieved; } public void setReasonIfNotAchieved(String reasonIfNotAchieved) { this.reasonIfNotAchieved = reasonIfNotAchieved; @@ -284,6 +292,12 @@ public void setFailed(boolean failed) { /** The checklist behind {@link #getDoneCriteria()}; empty when none was written. */ public List getCriteria() { return parseCriteria(doneCriteria); } + /** True when the goal has a checklist and every line of it is ticked. */ + public boolean isChecklistComplete() { + List criteria = getCriteria(); + return !criteria.isEmpty() && criteria.stream().allMatch(Criterion::done); + } + // ponytail: checklist stored as "[x] line" text on the parent goal, not a // table - move to a study_goal_criteria table only if criteria ever need // ids or history. @@ -321,6 +335,11 @@ public static String serializeCriteria(List criteria) { // ponytail: ticks re-matched by exact trimmed text; a reworded done // criterion comes back unticked. public static String criteriaFromLines(String plainLines, String previousStored) { + return criteriaFromLines(plainLines, previousStored, true); + } + + /** When typed ticks are disallowed, only matching previously stored ticks survive an edit. */ + public static String criteriaFromLines(String plainLines, String previousStored, boolean allowTypedTicks) { if (plainLines == null) { return null; } @@ -334,7 +353,7 @@ public static String criteriaFromLines(String plainLines, String previousStored) // Always consume the matching previous tick, even when the typed line // is already "[x]", or it would leak to the next duplicate line. boolean previouslyDone = ticks != null && !ticks.isEmpty() && ticks.poll(); - out.add(new Criterion(typed.text(), typed.done() || previouslyDone)); + out.add(new Criterion(typed.text(), (allowTypedTicks && typed.done()) || previouslyDone)); } return serializeCriteria(out); } @@ -837,13 +856,57 @@ public static Optional> setCriterionDone(String goalId, int inde return Optional.of(criteria); } + /** Ticks or clears every checklist line; returns whether the stored checklist changed. */ + public static boolean setAllCriteriaDone(String goalId, boolean done) { + if (jdbcTemplate == null || goalId == null || goalId.isBlank()) { + return false; + } + String stored = jdbcTemplate.query(""" + SELECT done_criteria FROM study_goals WHERE id = ? + """, rs -> rs.next() ? rs.getString("done_criteria") : null, goalId); + return markAllCriteria(goalId, parseCriteria(stored), done); + } + + /** + * Repairs pre-mirroring achieved goals without changing their outcome or completion history. + * Runs at every startup, so it reads all achieved checklists at once and writes only the rows + * that still have an open line. + */ + public static int normalizeAchievedChecklists() { + requireJdbcTemplate(); + List> checklists = jdbcTemplate.query(""" + SELECT id, done_criteria FROM study_goals WHERE status = 'ACHIEVED' AND done_criteria IS NOT NULL + """, (rs, row) -> Map.entry(rs.getString("id"), rs.getString("done_criteria"))); + int changed = 0; + for (Map.Entry checklist : checklists) { + if (markAllCriteria(checklist.getKey(), parseCriteria(checklist.getValue()), true)) { + changed++; + } + } + return changed; + } + + private static boolean markAllCriteria(String goalId, List criteria, boolean done) { + if (criteria.isEmpty() || criteria.stream().allMatch(criterion -> criterion.done() == done)) { + return false; + } + return jdbcTemplate.update(""" + UPDATE study_goals + SET done_criteria = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, serializeCriteria(criteria.stream().map(criterion -> new Criterion(criterion.text(), done)) + .toList()), goalId) > 0; + } + public static boolean markCurrentAttemptAchieved(String goalId, String reasonIfNot) { Optional goalOpt = findById(goalId); if (goalOpt.isEmpty()) { return false; } StudyGoal goal = goalOpt.get(); - if (goal.attemptId == null || goal.isDropped() || goal.isDroppedAttempt()) { + // A missed attempt is history; achieving the goal means planning a retry first. + if (goal.attemptId == null || goal.isDropped() || goal.isDroppedAttempt() + || goal.attemptOutcome == AttemptOutcome.MISSED) { return false; } jdbcTemplate.update(""" diff --git a/src/main/java/com/studysync/domain/service/StudyService.java b/src/main/java/com/studysync/domain/service/StudyService.java index 33889af..e679ed2 100644 --- a/src/main/java/com/studysync/domain/service/StudyService.java +++ b/src/main/java/com/studysync/domain/service/StudyService.java @@ -189,6 +189,7 @@ public void addStudyGoal(String description, LocalDate date, String taskId, Stri StudyGoal goal = new StudyGoal(null, date, description, false, null, 0, false, 0, taskId); goal.setDoneCriteria(StudyGoal.criteriaFromLines(doneCriteriaLines, null)); goal.save(); + reconcileAchievementWithChecklist(goal, goal.getCriteria()); // When a goal is created for an OPEN task, automatically transition it // to IN_PROGRESS to reflect that active work has been planned. @@ -247,7 +248,23 @@ public List getUnlinkedDelayedGoalsForReplanning() { * @param goalId ID of the goal to retry * @return {@code true} when a new pending retry attempt was created */ + /** + * What a new attempt does with a checklist that has no open line left. Starting it pending + * with every line ticked would break the checklist rule, so retries and reopens of such a + * goal must choose; for a goal with open lines the choice is ignored. + */ + public enum CompletedChecklist { + /** Clear every tick, so the new attempt has the whole checklist to do again. */ + START_OVER, + /** The work is already done: plan the new attempt for today and achieve it. */ + MARK_DONE + } + public boolean replanGoalForToday(String goalId) { + return replanGoalForToday(goalId, null); + } + + public boolean replanGoalForToday(String goalId, CompletedChecklist choice) { Optional goalOpt = StudyGoal.findById(goalId); if (goalOpt.isEmpty()) { logger.warn("Requested retry for study goal '{}' but it did not exist", goalId); @@ -257,8 +274,10 @@ public boolean replanGoalForToday(String goalId) { if (goal.getStatus() == StudyGoal.GoalStatus.ABANDONED || goal.isAchieved()) { return false; } + requireChecklistChoice(goal, choice); boolean created = StudyGoal.createReplanAttempt(goalId, dateTimeService.getCurrentDate()); if (created) { + applyChecklistChoice(goal, choice); markDirtyAndSaveLocally("study goal replan"); logger.info("Created new attempt for goal '{}' on {}", goal.getDescription(), dateTimeService.getCurrentDate()); } @@ -266,6 +285,11 @@ public boolean replanGoalForToday(String goalId) { } public boolean planGoalAttempt(String goalId, LocalDate plannedForDate) { + return planGoalAttempt(goalId, plannedForDate, null); + } + + /** {@link CompletedChecklist#MARK_DONE} plans the attempt for today, whatever date was picked. */ + public boolean planGoalAttempt(String goalId, LocalDate plannedForDate, CompletedChecklist choice) { if (goalId == null || goalId.isBlank()) { throw ValidationException.requiredFieldMissing("goalId"); } @@ -285,10 +309,13 @@ public boolean planGoalAttempt(String goalId, LocalDate plannedForDate) { if (goal.getStatus() == StudyGoal.GoalStatus.ABANDONED || goal.isAchieved()) { return false; } - boolean created = StudyGoal.createReplanAttempt(goalId, plannedForDate); + requireChecklistChoice(goal, choice); + LocalDate attemptDate = attemptDate(goal, choice, plannedForDate); + boolean created = StudyGoal.createReplanAttempt(goalId, attemptDate); if (created) { + applyChecklistChoice(goal, choice); markDirtyAndSaveLocally("study goal retry planning"); - logger.info("Created new attempt for goal '{}' on {}", goal.getDescription(), plannedForDate); + logger.info("Created new attempt for goal '{}' on {}", goal.getDescription(), attemptDate); } return created; } @@ -321,25 +348,70 @@ public boolean updateStudyGoalDetails(String goalId, String description, LocalDa } String doneCriteria = doneCriteriaLines == null ? goal.getDoneCriteria() - : StudyGoal.criteriaFromLines(doneCriteriaLines, goal.getDoneCriteria()); + : StudyGoal.criteriaFromLines(doneCriteriaLines, goal.getDoneCriteria(), !checklistTicksLocked(goal)); boolean updated = StudyGoal.updateDetails(goalId, description, pendingPlannedForDate, doneCriteria); if (updated) { + if (doneCriteriaLines != null) { + reconcileAchievementWithChecklist(goal, StudyGoal.parseCriteria(doneCriteria)); + } markDirtyAndSaveLocally("study goal details update"); } return updated; } + /** + * Keeps "achieved exactly when the checklist is complete" on creation and checklist edits. A pending goal + * whose remaining open lines were removed is achieved; an achieved goal that gained an open line + * reopens. An achieved attempt from an earlier day is history: reopening it would leave a pending + * attempt in the past that the next refresh sweeps to missed, so its lines are ticked instead. + * Missed and dropped goals are left alone. + */ + private void reconcileAchievementWithChecklist(StudyGoal goal, List criteria) { + if (criteria.isEmpty() || checklistTicksLocked(goal)) { + return; + } + boolean complete = criteria.stream().allMatch(StudyGoal.Criterion::done); + if (complete && !goal.isAchieved()) { + applyAchievement(goal.getId(), true, null); + } else if (!complete && goal.isAchieved()) { + if (goal.isAchievedBefore(dateTimeService.getCurrentDate())) { + StudyGoal.setAllCriteriaDone(goal.getId(), true); + } else { + applyAchievement(goal.getId(), false, null); + } + } + } + + private static boolean checklistTicksLocked(StudyGoal goal) { + return goal.isDropped() || goal.isDroppedAttempt() + || goal.getAttemptOutcome() == StudyGoal.AttemptOutcome.MISSED; + } + + /** + * Idempotent upgrade maintenance, called only after the startup Drive check permits mutations. + * Like the overdue sweep, this derived repair must checkpoint without setting the dirty flag, + * including when its transaction commits after the UI's maintenance wrapper has returned. + */ + public int normalizeAchievedGoalChecklists() { + int changed = StudyGoal.normalizeAchievedChecklists(); + if (changed > 0) { + saveLocallyWithoutDirtyFlag("achieved goal checklist normalization"); + } + return changed; + } + /** * Ticks or unticks one line of a goal's checklist. Ticking the last open * line achieves the current attempt; unticking any line on an achieved - * goal reopens it, with exactly the semantics of the achieved checkbox. - * Ticking a line never reopens anything: a goal achieved by hand with - * open criteria stays achieved while the remaining lines are filled in. - * An unknown goal or index changes nothing, achievement included. + * goal reopens it and keeps the other ticks. Ticking a line never reopens + * anything. A missed or dropped goal, or an unknown goal or index, changes + * nothing; a retry continues from the ticks the missed attempt left. + * Unticking a line of an earlier day's achieved goal changes nothing either. */ public void setGoalCriterionDone(String goalId, int index, boolean done) { Optional goal = StudyGoal.findById(goalId); - if (goal.isEmpty() || goal.get().isDropped() || goal.get().isDroppedAttempt()) { + if (goal.isEmpty() || checklistTicksLocked(goal.get()) + || (!done && goal.get().isAchievedBefore(dateTimeService.getCurrentDate()))) { return; } Optional> changed = StudyGoal.setCriterionDone(goalId, index, done); @@ -355,17 +427,30 @@ public void setGoalCriterionDone(String goalId, int index, boolean done) { markDirtyAndSaveLocally("study goal criterion update"); } + /** + * The goal checkbox. Its checklist mirrors it: achieving ticks every line + * and reopening clears them, so a goal is achieved exactly when its + * checklist is complete. A goal that cannot change (dropped, missed, + * not achieved, achieved on an earlier day) keeps its ticks. + */ public void updateStudyGoalAchievement(String goalId, boolean achieved, String reasonIfNot) { if (applyAchievement(goalId, achieved, reasonIfNot)) { + StudyGoal.setAllCriteriaDone(goalId, achieved); markDirtyAndSaveLocally("study goal achievement update"); } } - /** The one place that flips a goal's current attempt between achieved and pending. */ + /** + * The one place that flips a goal's current attempt between achieved and pending. It never + * reopens an earlier day's achievement ({@link StudyGoal#isAchievedBefore}). + */ private boolean applyAchievement(String goalId, boolean achieved, String reasonIfNot) { - return achieved - ? StudyGoal.markCurrentAttemptAchieved(goalId, reasonIfNot) - : StudyGoal.reopenAchievedGoal(goalId); + if (achieved) { + return StudyGoal.markCurrentAttemptAchieved(goalId, reasonIfNot); + } + LocalDate today = dateTimeService.getCurrentDate(); + return StudyGoal.findById(goalId).filter(goal -> !goal.isAchievedBefore(today)).isPresent() + && StudyGoal.reopenAchievedGoal(goalId); } /** A missed attempt stays retryable; it does not drop the goal. */ @@ -393,6 +478,11 @@ public boolean dropGoal(String goalId, String reason) { } public boolean reopenDroppedGoal(String goalId, LocalDate plannedForDate) { + return reopenDroppedGoal(goalId, plannedForDate, null); + } + + /** {@link CompletedChecklist#MARK_DONE} reopens the goal for today, whatever date was picked. */ + public boolean reopenDroppedGoal(String goalId, LocalDate plannedForDate, CompletedChecklist choice) { if (goalId == null || goalId.isBlank()) { throw ValidationException.requiredFieldMissing("goalId"); } @@ -402,13 +492,43 @@ public boolean reopenDroppedGoal(String goalId, LocalDate plannedForDate) { if (plannedForDate.isBefore(dateTimeService.getCurrentDate())) { throw ValidationException.invalidDateRange(plannedForDate.toString(), "today or a future date"); } - boolean changed = StudyGoal.reopenDroppedGoal(goalId, plannedForDate); + Optional goal = StudyGoal.findById(goalId); + if (goal.isEmpty()) { + return false; + } + requireChecklistChoice(goal.get(), choice); + boolean changed = StudyGoal.reopenDroppedGoal(goalId, attemptDate(goal.get(), choice, plannedForDate)); if (changed) { + applyChecklistChoice(goal.get(), choice); markDirtyAndSaveLocally("study goal reopened"); } return changed; } + private static void requireChecklistChoice(StudyGoal goal, CompletedChecklist choice) { + if (choice == null && goal.isChecklistComplete()) { + throw new ValidationException("Every checklist item is already ticked. Choose whether to start the " + + "checklist over or mark the goal done.", ValidationException.INVALID_INPUT); + } + } + + private LocalDate attemptDate(StudyGoal goal, CompletedChecklist choice, LocalDate plannedForDate) { + return choice == CompletedChecklist.MARK_DONE && goal.isChecklistComplete() + ? dateTimeService.getCurrentDate() : plannedForDate; + } + + /** Runs in the caller's transaction, right after the new attempt was created. */ + private void applyChecklistChoice(StudyGoal goal, CompletedChecklist choice) { + if (choice == null || !goal.isChecklistComplete()) { + return; + } + if (choice == CompletedChecklist.START_OVER) { + StudyGoal.setAllCriteriaDone(goal.getId(), false); + } else { + applyAchievement(goal.getId(), true, null); + } + } + /** * Permanently deletes a study goal from the database. */ diff --git a/src/main/java/com/studysync/presentation/ui/StudySyncUI.java b/src/main/java/com/studysync/presentation/ui/StudySyncUI.java index 3dc07ef..e0d4225 100644 --- a/src/main/java/com/studysync/presentation/ui/StudySyncUI.java +++ b/src/main/java/com/studysync/presentation/ui/StudySyncUI.java @@ -367,6 +367,12 @@ private void markDelayedTasksOnStartup() { } private void processDelayedGoalsOnStartup() { + // Separate from the sweep: maintenance runs once, so a failed repair must not skip it. + try { + studyService.normalizeAchievedGoalChecklists(); + } catch (Exception e) { + logger.error("Failed to normalize achieved goal checklists on startup", e); + } try { StudyService.GoalDelayProcessingResult result = studyService.processAllDelayedGoals(); if (result.missedAttempts() > 0) { diff --git a/src/main/java/com/studysync/presentation/ui/components/GoalActions.java b/src/main/java/com/studysync/presentation/ui/components/GoalActions.java index 80af470..1ea36e5 100644 --- a/src/main/java/com/studysync/presentation/ui/components/GoalActions.java +++ b/src/main/java/com/studysync/presentation/ui/components/GoalActions.java @@ -12,7 +12,10 @@ import javafx.scene.control.Label; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; +import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; +import javafx.scene.control.ToggleGroup; +import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import java.time.LocalDate; @@ -87,6 +90,9 @@ static Dialog dialog(final Node owner, final Action action, final St TaskStyleUtils.fontSemiBold(description, 13); Label explanation = new Label(action.explanation); explanation.setWrapText(true); + // A wrapped label may otherwise shrink to one ellipsized line when the dialog has more content. + description.setMinHeight(Region.USE_PREF_SIZE); + explanation.setMinHeight(Region.USE_PREF_SIZE); VBox content = new VBox(12, description, explanation); content.setPrefWidth(400); @@ -106,9 +112,18 @@ public void updateItem(final LocalDate value, final boolean empty) { setDisable(empty || value == null || value.isBefore(today)); } }); - if (action == Action.REOPEN || action == Action.RETRY) { + boolean plansAttempt = action == Action.REOPEN || action == Action.RETRY; + ChecklistChoice checklist = plansAttempt ? ChecklistChoice.forGoal(goal, date, today) : null; + if (plansAttempt) { content.getChildren().addAll(new Label("Planned date"), date); } + if (checklist != null) { + // The choice below decides what happens to the ticks, so do not promise to keep them. + explanation.setText(action == Action.RETRY + ? "Choose a date for another attempt. Earlier attempts will be kept." + : "Plan a new attempt. Earlier attempts will be kept."); + content.getChildren().add(checklist.view); + } Label error = new Label(); error.setWrapText(true); error.setVisible(false); @@ -129,8 +144,8 @@ public void updateItem(final LocalDate value, final boolean empty) { boolean changed = switch (action) { case MISS -> service.markGoalAttemptMissed(goal.getId(), goal.getAttemptId()); case DROP -> service.dropGoal(goal.getId(), reason.getText()); - case REOPEN -> service.reopenDroppedGoal(goal.getId(), date.getValue()); - case RETRY -> service.planGoalAttempt(goal.getId(), date.getValue()); + case REOPEN -> service.reopenDroppedGoal(goal.getId(), date.getValue(), checklistValue(checklist)); + case RETRY -> service.planGoalAttempt(goal.getId(), date.getValue(), checklistValue(checklist)); }; if (!changed) { throw new IllegalStateException( @@ -151,4 +166,47 @@ public void updateItem(final LocalDate value, final boolean empty) { }); return dialog; } + + private static StudyService.CompletedChecklist checklistValue(final ChecklistChoice checklist) { + return checklist == null ? null : checklist.value(); + } + + /** + * What a retry or reopen does when every checklist line is already ticked, asked wherever an + * attempt is planned with a date. Marking the goal done plans the attempt for today, so the + * date is fixed to today while that option is selected. + */ + static final class ChecklistChoice { + final VBox view; + private final RadioButton markDone = new RadioButton("Mark the goal done today"); + + private ChecklistChoice(final DatePicker date, final LocalDate today) { + RadioButton startOver = new RadioButton("Start the checklist over"); + ToggleGroup group = new ToggleGroup(); + startOver.setToggleGroup(group); + markDone.setToggleGroup(group); + startOver.setSelected(true); + Label prompt = new Label("Every checklist item is already ticked."); + prompt.setWrapText(true); + prompt.setMinHeight(Region.USE_PREF_SIZE); + TaskStyleUtils.fontSemiBold(prompt, 12); + markDone.selectedProperty().addListener((observable, wasSelected, selected) -> { + if (selected) { + date.setValue(today); + } + date.setDisable(selected); + }); + view = new VBox(6, prompt, startOver, markDone); + } + + /** The choice for a goal whose checklist is complete, or null when it has open lines. */ + static ChecklistChoice forGoal(final StudyGoal goal, final DatePicker date, final LocalDate today) { + return goal.isChecklistComplete() ? new ChecklistChoice(date, today) : null; + } + + StudyService.CompletedChecklist value() { + return markDone.isSelected() ? StudyService.CompletedChecklist.MARK_DONE + : StudyService.CompletedChecklist.START_OVER; + } + } } diff --git a/src/main/java/com/studysync/presentation/ui/components/GoalListAgenda.java b/src/main/java/com/studysync/presentation/ui/components/GoalListAgenda.java new file mode 100644 index 0000000..58f16ce --- /dev/null +++ b/src/main/java/com/studysync/presentation/ui/components/GoalListAgenda.java @@ -0,0 +1,144 @@ +package com.studysync.presentation.ui.components; + +import com.studysync.domain.entity.StudyGoal; +import com.studysync.domain.entity.Task; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * How the planner's goal list is sorted and grouped. Dropped goals are not + * passed in; the planner keeps them in their own collapsed section. + * + *

Goals are sorted first and then grouped, so groups appear in the order + * of their first goal: grouped by task under the Status sort, groups with + * pending work come first. Goals without a task form a "No task" group that + * is ordered the same way. Status groups keep a fixed Pending, Done, Missed + * order. Priority and deadline belong to a goal's task; goals without one + * sort after those with one.

+ */ +final class GoalListAgenda { + + enum Group { + TASK("Task"), STATUS("Status"), NONE("None"); + + private final String label; + + Group(final String label) { + this.label = label; + } + + @Override + public String toString() { + return label; + } + } + + enum Sort { + STATUS("Status"), PRIORITY("Priority"), DEADLINE("Deadline"), TITLE("Title"); + + private final String label; + + Sort(final String label) { + this.label = label; + } + + @Override + public String toString() { + return label; + } + } + + /** Goal states, declared in display order. */ + enum Status { + PENDING("Pending"), DONE("Done"), MISSED("Missed"); + + final String label; + + Status(final String label) { + this.label = label; + } + + static Status of(final StudyGoal goal) { + if (goal.isAchieved()) { + return DONE; + } + return goal.isFailed() || goal.getAttemptOutcome() == StudyGoal.AttemptOutcome.MISSED ? MISSED : PENDING; + } + } + + /** One heading and its goals; {@code title} is null for the ungrouped list. */ + record Section(String title, List goals) { + } + + static final String NO_TASK = "No task"; + + private GoalListAgenda() { + } + + static List
build(final List goals, final Map tasksById, + final Group group, final Sort sort) { + List sorted = goals.stream().sorted(comparator(sort, tasksById)).toList(); + return switch (group) { + case NONE -> sorted.isEmpty() ? List.of() : List.of(new Section(null, sorted)); + case STATUS -> byStatus(sorted); + case TASK -> byTask(sorted, tasksById); + }; + } + + private static List
byStatus(final List sorted) { + Map> groups = new LinkedHashMap<>(); + for (Status status : Status.values()) { + groups.put(status, new ArrayList<>()); + } + sorted.forEach(goal -> groups.get(Status.of(goal)).add(goal)); + List
sections = new ArrayList<>(); + groups.forEach((status, members) -> { + if (!members.isEmpty()) { + sections.add(new Section(status.label, members)); + } + }); + return sections; + } + + private static List
byTask(final List sorted, final Map tasksById) { + // A null key collects the goals without a task; LinkedHashMap keeps first-appearance order. + Map> groups = new LinkedHashMap<>(); + sorted.forEach(goal -> groups.computeIfAbsent(task(goal, tasksById), key -> new ArrayList<>()).add(goal)); + List
sections = new ArrayList<>(); + groups.forEach((task, members) -> sections.add(new Section( + task == null ? NO_TASK : CalendarAgenda.taskTitle(task, tasksById), members))); + return sections; + } + + private static Comparator comparator(final Sort sort, final Map tasksById) { + Comparator status = Comparator.comparing(Status::of); + // A task without a deadline ties with no task at all; keep goals without a task after it. + Comparator withTaskFirst = Comparator.comparing(goal -> task(goal, tasksById) == null); + Comparator title = Comparator.comparing(StudyGoal::getDescription, String.CASE_INSENSITIVE_ORDER); + Comparator taskTitle = Comparator.comparing(goal -> { + Task task = task(goal, tasksById); + return task == null ? null : CalendarAgenda.taskTitle(task, tasksById); + }, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)); + return switch (sort) { + case STATUS -> status.thenComparing(taskTitle).thenComparing(title); + case PRIORITY -> Comparator.comparingInt((StudyGoal goal) -> { + Task task = task(goal, tasksById); + return task == null || task.getPriority() == null ? 0 : task.getPriority().stars(); + }).reversed().thenComparing(status).thenComparing(taskTitle).thenComparing(title); + case DEADLINE -> Comparator.comparing((StudyGoal goal) -> { + Task task = task(goal, tasksById); + return task == null || task.getDeadline() == null ? LocalDate.MAX : task.getDeadline(); + }).thenComparing(withTaskFirst).thenComparing(status).thenComparing(taskTitle).thenComparing(title); + case TITLE -> title.thenComparing(status); + }; + } + + private static Task task(final StudyGoal goal, final Map tasksById) { + return goal.getTaskId() == null ? null : tasksById.get(goal.getTaskId()); + } +} diff --git a/src/main/java/com/studysync/presentation/ui/components/PlanningRow.java b/src/main/java/com/studysync/presentation/ui/components/PlanningRow.java index 6ee1d8e..7df4583 100644 --- a/src/main/java/com/studysync/presentation/ui/components/PlanningRow.java +++ b/src/main/java/com/studysync/presentation/ui/components/PlanningRow.java @@ -17,6 +17,9 @@ /** Shared task-to-goal interaction for the calendar and daily planner. */ final class PlanningRow { + /** Node property holding the item's planning key, so a closed dialog can return focus to it. */ + static final String KEY = "studysync.planning-key"; + private PlanningRow() { } @@ -68,6 +71,7 @@ private static Label reasonLabel(String reason, String color) { private static void install(Region item, String title, String reason, String hint, DataFormat format, String id, Runnable plan) { item.getStyleClass().add("cal-plan-item"); + item.getProperties().put(KEY, id); item.setFocusTraversable(true); item.setAccessibleText(title + ". " + reason + ". " + hint); Tooltip.install(item, new Tooltip(title + "\n" + reason + "\n\n" + hint)); diff --git a/src/main/java/com/studysync/presentation/ui/components/StudyPlannerPanel.java b/src/main/java/com/studysync/presentation/ui/components/StudyPlannerPanel.java index aa6d033..ba89d48 100644 --- a/src/main/java/com/studysync/presentation/ui/components/StudyPlannerPanel.java +++ b/src/main/java/com/studysync/presentation/ui/components/StudyPlannerPanel.java @@ -35,6 +35,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import javafx.animation.Timeline; import javafx.animation.KeyFrame; @@ -67,6 +68,10 @@ private enum PlannerTaskView { // Sort / group state for the tasks section private String currentSort = "Status"; private String currentGroup = "None"; + private GoalListAgenda.Group goalGroup = GoalListAgenda.Group.TASK; + private GoalListAgenda.Sort goalSort = GoalListAgenda.Sort.STATUS; + // Task IDs survive refreshes and renames; null is the "No task" group. + private final Set collapsedGoalTaskIds = new HashSet<>(); private PlannerTaskView currentTaskView = PlannerTaskView.TODAY; // UI containers that get rebuilt on navigation @@ -162,9 +167,9 @@ private void initializeComponents(VBox mainContent) { HBox.setHgrow(goalsHeaderSpacer, Priority.ALWAYS); HBox goalsHeader = new HBox(10, goalsTitle, goalsHeaderSpacer, addGoal); goalsHeader.setAlignment(Pos.CENTER_LEFT); - goalsContainer = new VBox(8); + goalsContainer = new VBox(16); unlinkedRetriesContainer = new VBox(8); - goals.getChildren().addAll(goalsHeader, goalsContainer, unlinkedRetriesContainer); + goals.getChildren().addAll(goalsHeader, createGoalListToolbar(), goalsContainer, unlinkedRetriesContainer); installPlanningDropTarget(goals); VBox sidebar = new VBox(20); @@ -316,6 +321,36 @@ private void createTasksSection(VBox mainContent) { mainContent.getChildren().add(browse); } + /** Group and sort controls for the goal list; the rules are in {@link GoalListAgenda}. */ + private FlowPane createGoalListToolbar() { + Label groupLabel = new Label("Group:"); + TaskStyleUtils.fontBold(groupLabel, 12); + ComboBox groupCombo = new ComboBox<>(); + groupCombo.getItems().addAll(GoalListAgenda.Group.values()); + groupCombo.setValue(goalGroup); + groupCombo.setAccessibleText("Group goals by"); + groupCombo.valueProperty().addListener((obs, old, value) -> { + goalGroup = value; + updateTasksDisplay(); + }); + + Label sortLabel = new Label("Sort:"); + TaskStyleUtils.fontBold(sortLabel, 12); + ComboBox sortCombo = new ComboBox<>(); + sortCombo.getItems().addAll(GoalListAgenda.Sort.values()); + sortCombo.setValue(goalSort); + sortCombo.setAccessibleText("Sort goals by"); + sortCombo.valueProperty().addListener((obs, old, value) -> { + goalSort = value; + updateTasksDisplay(); + }); + + FlowPane toolbar = new FlowPane(8, 6, groupLabel, groupCombo, sortLabel, sortCombo); + toolbar.setAlignment(Pos.CENTER_LEFT); + FlowPane.setMargin(sortLabel, new Insets(0, 0, 0, 8)); + return toolbar; + } + private void createSessionBar() { // An HBox, not a FlowPane: a FlowPane is at least as wide as its widest child's // preferred width, so a long goal name would set the whole planner's minimum width. @@ -432,15 +467,24 @@ private void updateTasksDisplay() { goalsTitle.setText(displayDate.equals(dateTimeService.getCurrentDate()) ? "Today's Goals" : "Goals"); goalsContainer.getChildren().clear(); goalSessionButtons.clear(); - displayDateAttempts.stream().filter(goal -> !goal.isDropped() && !goal.isDroppedAttempt()) - .sorted(Comparator.comparingInt(goal -> - goal.isFailed() ? 2 : goal.isAchieved() ? 1 : 0)).forEach(goal -> - goalsContainer.getChildren().add(buildGoalRow(goal, tasksById.get(goal.getTaskId())))); + List active = displayDateAttempts.stream() + .filter(goal -> !goal.isDropped() && !goal.isDroppedAttempt()).toList(); + boolean byTask = goalGroup == GoalListAgenda.Group.TASK; + GoalListAgenda.build(active, tasksById, goalGroup, goalSort).forEach(section -> { + VBox group = new VBox(8); + if (!byTask && section.title() != null) { + group.getChildren().add(goalGroupHeader(section)); + } + section.goals().forEach(goal -> + group.getChildren().add(buildGoalRow(goal, tasksById.get(goal.getTaskId()), !byTask))); + goalsContainer.getChildren().add(byTask ? taskGoalGroup(section, group) : group); + }); List dropped = displayDateAttempts.stream() .filter(goal -> goal.isDropped() || goal.isDroppedAttempt()).toList(); if (!dropped.isEmpty()) { VBox history = new VBox(8); - dropped.forEach(goal -> history.getChildren().add(buildGoalRow(goal, tasksById.get(goal.getTaskId())))); + dropped.forEach(goal -> + history.getChildren().add(buildGoalRow(goal, tasksById.get(goal.getTaskId()), true))); TitledPane section = new TitledPane("Dropped (" + dropped.size() + ")", history); section.setExpanded(false); goalsContainer.getChildren().add(section); @@ -517,6 +561,23 @@ private void planEntry(PlannerAgenda.Entry entry) { if (entry.retries().isEmpty()) { showAddGoalDialog(entry.task()); } else { + new RetryDialog(entry).refresh(null, false); + } + } + + /** + * The "Plan retry" modal. Every action in it refreshes the planner and brings the dialog back + * with a notice, so several goals can be handled in one visit; only Done closes it. The frame is + * built once so a refresh keeps the scroll position; only the notice and rows are rebuilt. + */ + private final class RetryDialog { + private final PlannerAgenda.Entry entry; + private final Label notice = new Label(); + private final VBox rows = new VBox(12); + private final ScrollPane wrapper; + + RetryDialog(PlannerAgenda.Entry entry) { + this.entry = entry; VBox content = new VBox(12); content.setPadding(new Insets(20)); content.getStyleClass().add("modal-content"); @@ -525,24 +586,107 @@ private void planEntry(PlannerAgenda.Entry entry) { Label title = new Label("Plan retry: " + entry.title()); title.setWrapText(true); TaskStyleUtils.fontBold(title, 16); - content.getChildren().add(title); - entry.retries().forEach(goal -> content.getChildren().add(buildTaskRetryRow(goal))); + notice.setWrapText(true); + TaskStyleUtils.fontNormal(notice, 12); + Button newGoal = new Button("+ New goal"); newGoal.getStyleClass().add("btn-purple"); - newGoal.setOnAction(event -> showAddGoalDialog(entry.task())); - Button cancel = new Button("Cancel"); - cancel.getStyleClass().add("btn-cancel"); - cancel.setOnAction(event -> closeModal.run()); - content.getChildren().add(new HBox(10, newGoal, cancel)); - ScrollPane wrapper = new ScrollPane(content); + newGoal.setOnAction(event -> showAddGoalDialog(entry.task(), + refreshError -> showAfterRefresh("Added a new goal.", false, refreshError), this::reopen)); + Button done = new Button("Done"); + done.getStyleClass().add("btn-primary"); + done.setOnAction(event -> { + closeModal.run(); + focusPlanningTile(entry.key()); + }); + Region spacer = new Region(); + HBox.setHgrow(spacer, Priority.ALWAYS); + + content.getChildren().addAll(title, mutedLabel(entry.task() != null + ? "Try a missed goal again today, or add a new goal for this task." + : "Try this missed goal again today, or add a new goal."), + notice, rows, new HBox(10, newGoal, spacer, done)); + wrapper = new ScrollPane(content); wrapper.setFitToWidth(true); wrapper.getStyleClass().add("transparent-bg"); wrapper.setMaxWidth(580); wrapper.setMaxHeight(600); + } + + /** Reload the planner after a change made here, then show the dialog's current retries. */ + void refresh(String message, boolean error) { + showAfterRefresh(message, error, refreshAfterChange()); + } + + /** A failed reload must not offer actions on stale retry rows or claim the list is empty. */ + void showAfterRefresh(String message, boolean error, String refreshError) { + if (refreshError == null) { + show(message, error, true); + return; + } + String failure = refreshError; + if (message != null) { + failure = (error ? message + "\n" : "Changes saved. ") + refreshError; + } + show(failure, true, false); + } + + void reopen() { + refresh(null, false); + } + + /** Offer retry actions only when the planner's list was successfully refreshed. */ + private void show(String message, boolean error, boolean listAvailable) { + // The planner rebuilds its entries on refresh; handled goals have left this one. + PlannerAgenda.Entry current = planningEntries.get(entry.key()); + List retries = current == null ? List.of() : current.retries(); + notice.setText(message); + notice.setVisible(message != null); + notice.setManaged(message != null); + notice.setGraphic(TaskStyleUtils.iconLabel(error ? "\u26A0" : "\u2713", 12)); + TaskStyleUtils.textColor(notice, error ? TaskStyleUtils.COLOR_DANGER : TaskStyleUtils.COLOR_SUCCESS); + rows.getChildren().clear(); + if (!listAvailable) { + rows.getChildren().add(mutedLabel("Retry list unavailable. Close and reopen this dialog to refresh.")); + } else if (retries.isEmpty()) { + rows.getChildren().add(mutedLabel("No missed goals left to retry.")); + } else { + rows.getChildren().setAll(retries.stream().map(goal -> (Node) buildTaskRetryRow(goal, this)).toList()); + } showModal.accept(wrapper); } } + /** + * Reload the planner after a change that already succeeded. A failure here is reported rather + * than thrown, so the dialog that made the change still closes or moves on instead of staying + * open and inviting the same save twice. + */ + private String refreshAfterChange() { + try { + updateTasksDisplay(); + updateProgress(); + plannerError.setVisible(false); + plannerError.setManaged(false); + return null; + } catch (Exception ex) { + String message = "The planner could not refresh: " + ex.getMessage(); + showPlannerError(message); + return message; + } + } + + /** + * Opening the retry dialog rebuilds the planning tiles, so the one it was opened from has lost + * keyboard focus; give it to that entry's new tile, if it is still listed. + */ + private void focusPlanningTile(String key) { + Stream.of(needsPlanContainer, unlinkedRetriesContainer) + .flatMap(container -> container.lookupAll(".plan-tile").stream()) + .filter(tile -> key.equals(tile.getProperties().get(PlanningRow.KEY))) + .findFirst().ifPresent(Node::requestFocus); + } + private void installPlanningDropTarget(VBox goals) { goals.setOnDragOver(event -> { if (planningEntries.containsKey(event.getDragboard().getContent(PLAN_DRAG))) { @@ -789,7 +933,7 @@ private Node buildTaskRow(Task task) { row.getChildren().add(badges); } retryableGoals.stream().filter(goal -> task.getId().equals(goal.getTaskId())).forEach(goal -> - row.getChildren().add(buildTaskRetryRow(goal))); + row.getChildren().add(buildTaskRetryRow(goal, null))); return row; } @@ -826,58 +970,152 @@ private List