feat: add energy-aware scheduling and daily insights
- Learn a per-device 7x24 energy profile from completed tasks\n- Constrain high-energy scheduling and expose energy peaks to AI\n- Add ghost-time overlays, daily review dialog, and proactive suggestions\n- Cover energy/insights logic and local OpenAI-compatible providers with tests\n- Update validation docs and screenshots
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
当前本地时间:{CURRENT_TIME}
|
||||
今天星期:{WEEKDAY}
|
||||
用户默认可用时间:{WORK_START}–{WORK_END}
|
||||
用户精力高峰(用于安排高精力任务):{ENERGY_PROFILE}
|
||||
用户现有日程(每行开头的 [bN] 是引用编号,只能用于 update/delete):
|
||||
{EXISTING_SCHEDULE}
|
||||
|
||||
@@ -29,6 +30,7 @@
|
||||
15. 现有日程摘要中带“(会议)”标记的条目属于会议类;用户要求删除“所有会议”时,逐个 delete 所有带该标记的条目。
|
||||
16. 示例:现有 [b2] 团队同步(会议)、[b4] 项目会议(会议)。用户说“删除明天所有会议”时,输出 {"operations":[{"type":"delete","target_ref":"b2"},{"type":"delete","target_ref":"b4"}]}。
|
||||
17. 示例:用户说“明天之前找时间做两小时长任务,可以拆开”,输出 create 并设置 "splittable":true;不要拆成两个独立任务。
|
||||
18. energy_req 取值:0=低精力杂务,1=一般沟通/会议,2=高专注深度工作、学习或创作;不确定时填 1。高精力任务应优先放在用户的精力高峰时段。
|
||||
|
||||
补充信息:
|
||||
{EXTRA_CONTEXT}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
add_library(schedule_core STATIC
|
||||
core/DateTimeUtils.cpp
|
||||
core/DateTimeUtils.h
|
||||
core/DailyInsights.cpp
|
||||
core/DailyInsights.h
|
||||
core/EnergyProfile.cpp
|
||||
core/EnergyProfile.h
|
||||
core/ProposedDiff.h
|
||||
core/SchedulerEngine.cpp
|
||||
core/SchedulerEngine.h
|
||||
@@ -77,6 +81,8 @@ add_library(schedule_ui STATIC
|
||||
ui/MainWindow.h
|
||||
ui/dialogs/BlockEditDialog.cpp
|
||||
ui/dialogs/BlockEditDialog.h
|
||||
ui/dialogs/DailyReviewDialog.cpp
|
||||
ui/dialogs/DailyReviewDialog.h
|
||||
ui/dialogs/SettingsDialog.cpp
|
||||
ui/dialogs/SettingsDialog.h
|
||||
ui/panels/ChatPanel.cpp
|
||||
|
||||
@@ -476,6 +476,8 @@ QString AIService::buildSystemPrompt()
|
||||
prompt.replace(QStringLiteral("{WEEKDAY}"), weekdayLabel(now.date()));
|
||||
prompt.replace(QStringLiteral("{WORK_START}"), QStringLiteral("08:00"));
|
||||
prompt.replace(QStringLiteral("{WORK_END}"), QStringLiteral("22:00"));
|
||||
prompt.replace(QStringLiteral("{ENERGY_PROFILE}"),
|
||||
m_scheduleService.dailyReview(now.date()).energySummary);
|
||||
prompt.replace(QStringLiteral("{EXISTING_SCHEDULE}"), scheduleSummary());
|
||||
prompt.replace(QStringLiteral("{EXTRA_CONTEXT}"),
|
||||
m_filePaths.isEmpty()
|
||||
@@ -922,6 +924,9 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
|
||||
}
|
||||
scheduler::Options options;
|
||||
options.granularityMinutes = 15;
|
||||
options.energyAt = [this](scheduler::SysTime value) {
|
||||
return m_scheduleService.energyLevelFor(fromSysTime(value));
|
||||
};
|
||||
|
||||
struct Busy
|
||||
{
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
#include "DailyInsights.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "core/DateTimeUtils.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
bool isActiveStatus(const QString& status)
|
||||
{
|
||||
return status == QStringLiteral("scheduled") || status == QStringLiteral("in_progress");
|
||||
}
|
||||
|
||||
bool occupiesTime(const QString& status)
|
||||
{
|
||||
return status != QStringLiteral("dropped") && status != QStringLiteral("missed");
|
||||
}
|
||||
|
||||
QDateTime dayBoundary(const QDate& date, int hour)
|
||||
{
|
||||
if (hour >= 24)
|
||||
{
|
||||
return QDateTime(date.addDays(1), QTime(0, 0), Qt::LocalTime);
|
||||
}
|
||||
return QDateTime(date, QTime(std::max(0, hour), 0), Qt::LocalTime);
|
||||
}
|
||||
|
||||
QString formatWindow(const FreeWindow& window)
|
||||
{
|
||||
return QStringLiteral("%1–%2").arg(window.start.toString(QStringLiteral("HH:mm")),
|
||||
window.end.toString(QStringLiteral("HH:mm")));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
const QDateTime& from,
|
||||
int workStartHour,
|
||||
int workEndHour,
|
||||
int minMinutes)
|
||||
{
|
||||
QVector<FreeWindow> result;
|
||||
if (!date.isValid())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
QDateTime rangeStart = dayBoundary(date, workStartHour);
|
||||
const QDateTime rangeEnd = dayBoundary(date, workEndHour);
|
||||
if (from.isValid() && from > rangeStart)
|
||||
{
|
||||
rangeStart = from;
|
||||
}
|
||||
if (rangeStart >= rangeEnd || minMinutes <= 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
QVector<QPair<QDateTime, QDateTime>> busy;
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (!occupiesTime(item.block.status))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const QDateTime start = std::max(item.block.startAt, rangeStart);
|
||||
const QDateTime end = std::min(item.block.endAt, rangeEnd);
|
||||
if (start < end)
|
||||
{
|
||||
busy.append({start, end});
|
||||
}
|
||||
}
|
||||
std::sort(busy.begin(), busy.end(), [](const auto& a, const auto& b) {
|
||||
return a.first < b.first;
|
||||
});
|
||||
|
||||
QDateTime cursor = rangeStart;
|
||||
for (const auto& interval : busy)
|
||||
{
|
||||
if (interval.second <= cursor)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (interval.first > cursor)
|
||||
{
|
||||
const int minutes = DateTimeUtils::minutesBetween(cursor, interval.first);
|
||||
if (minutes >= minMinutes)
|
||||
{
|
||||
result.append({cursor, interval.first, minutes});
|
||||
}
|
||||
}
|
||||
cursor = std::max(cursor, interval.second);
|
||||
}
|
||||
if (cursor < rangeEnd)
|
||||
{
|
||||
const int minutes = DateTimeUtils::minutesBetween(cursor, rangeEnd);
|
||||
if (minutes >= minMinutes)
|
||||
{
|
||||
result.append({cursor, rangeEnd, minutes});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
int workStartHour,
|
||||
int workEndHour,
|
||||
int minMinutes)
|
||||
{
|
||||
return findFreeWindows(items, date, dayBoundary(date, workStartHour), workStartHour, workEndHour, minMinutes);
|
||||
}
|
||||
|
||||
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
const QDateTime& now)
|
||||
{
|
||||
DailyReview review;
|
||||
review.date = date;
|
||||
review.total = items.size();
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
const QString& status = item.block.status;
|
||||
if (status == QStringLiteral("done"))
|
||||
{
|
||||
++review.done;
|
||||
review.focusedMinutes +=
|
||||
std::max(0, DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt));
|
||||
}
|
||||
else if (isActiveStatus(status))
|
||||
{
|
||||
++review.active;
|
||||
if (item.block.endAt < now)
|
||||
{
|
||||
++review.overdue;
|
||||
}
|
||||
}
|
||||
else if (status == QStringLiteral("missed"))
|
||||
{
|
||||
++review.missed;
|
||||
}
|
||||
else if (status == QStringLiteral("dropped"))
|
||||
{
|
||||
++review.dropped;
|
||||
}
|
||||
}
|
||||
review.completionPercent =
|
||||
review.total > 0 ? static_cast<int>(std::lround(review.done * 100.0 / review.total)) : 0;
|
||||
|
||||
const QDateTime reviewFrom = date < now.date() ? dayBoundary(date, 8) : now;
|
||||
review.ghostWindows = findFreeWindows(items, date, reviewFrom, 8, 22, 30);
|
||||
|
||||
if (review.total == 0)
|
||||
{
|
||||
review.summary = QStringLiteral("今天还没有安排;可以先留出一段专注时间。");
|
||||
}
|
||||
else
|
||||
{
|
||||
review.summary = QStringLiteral("完成 %1/%2 项(%3%),累计专注 %4。")
|
||||
.arg(review.done)
|
||||
.arg(review.total)
|
||||
.arg(review.completionPercent)
|
||||
.arg(DateTimeUtils::formatDuration(review.focusedMinutes));
|
||||
}
|
||||
if (review.overdue > 0)
|
||||
{
|
||||
review.highlights.append(QStringLiteral("%1 项日程已超时").arg(review.overdue));
|
||||
}
|
||||
if (review.active > 0)
|
||||
{
|
||||
review.highlights.append(QStringLiteral("还有 %1 项待办").arg(review.active));
|
||||
}
|
||||
if (review.missed > 0 || review.dropped > 0)
|
||||
{
|
||||
review.highlights.append(
|
||||
QStringLiteral("错过 %1 项,放弃 %2 项").arg(review.missed).arg(review.dropped));
|
||||
}
|
||||
if (review.done > 0)
|
||||
{
|
||||
review.highlights.append(QStringLiteral("今日专注 %1 分钟").arg(review.focusedMinutes));
|
||||
}
|
||||
if (review.ghostWindows.isEmpty())
|
||||
{
|
||||
review.highlights.append(QStringLiteral("今天没有 30 分钟以上的幽灵时间"));
|
||||
}
|
||||
else
|
||||
{
|
||||
review.highlights.append(
|
||||
QStringLiteral("幽灵时间最早一段:%1").arg(formatWindow(review.ghostWindows.first())));
|
||||
}
|
||||
return review;
|
||||
}
|
||||
|
||||
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
|
||||
const QDateTime& now,
|
||||
int maxCount)
|
||||
{
|
||||
QVector<Suggestion> result;
|
||||
if (maxCount <= 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
QVector<ScheduleItem> overdue;
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (isActiveStatus(item.block.status) && item.block.endAt < now)
|
||||
{
|
||||
overdue.append(item);
|
||||
}
|
||||
}
|
||||
if (!overdue.isEmpty())
|
||||
{
|
||||
Suggestion suggestion;
|
||||
suggestion.kind = Suggestion::Kind::Overdue;
|
||||
suggestion.title = QStringLiteral("处理超时日程");
|
||||
suggestion.detail = QStringLiteral("「%1」%2已超时,建议重新安排或标记完成。")
|
||||
.arg(overdue.first().task.title)
|
||||
.arg(overdue.size() > 1
|
||||
? QStringLiteral("等 %1 项").arg(overdue.size())
|
||||
: QString());
|
||||
result.append(suggestion);
|
||||
}
|
||||
if (result.size() >= maxCount)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
const QVector<FreeWindow> ghost =
|
||||
findFreeWindows(items, now.date(), now, 8, 22, 30);
|
||||
if (!ghost.isEmpty())
|
||||
{
|
||||
Suggestion suggestion;
|
||||
suggestion.kind = Suggestion::Kind::GhostTime;
|
||||
suggestion.title = QStringLiteral("发现幽灵时间");
|
||||
const FreeWindow& window = ghost.first();
|
||||
suggestion.detail = QStringLiteral("%1 空出 %2,可安排一件重要的事。")
|
||||
.arg(formatWindow(window), DateTimeUtils::formatDuration(window.minutes));
|
||||
suggestion.start = window.start;
|
||||
suggestion.end = window.end;
|
||||
result.append(suggestion);
|
||||
}
|
||||
if (result.size() >= maxCount)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
int doneCount = 0;
|
||||
int activeCount = 0;
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (item.block.status == QStringLiteral("done"))
|
||||
{
|
||||
++doneCount;
|
||||
}
|
||||
else if (isActiveStatus(item.block.status))
|
||||
{
|
||||
++activeCount;
|
||||
}
|
||||
}
|
||||
if (now.time().hour() >= 18 && (doneCount > 0 || activeCount > 0))
|
||||
{
|
||||
Suggestion suggestion;
|
||||
suggestion.kind = Suggestion::Kind::Review;
|
||||
suggestion.title = QStringLiteral("做一次今日复盘");
|
||||
suggestion.detail = QStringLiteral("今天完成 %1 项,还有 %2 项待办,花 2 分钟回顾一下。")
|
||||
.arg(doneCount)
|
||||
.arg(activeCount);
|
||||
result.append(suggestion);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include <QDate>
|
||||
#include <QDateTime>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
|
||||
#include "core/ScheduleItem.h"
|
||||
|
||||
struct FreeWindow
|
||||
{
|
||||
QDateTime start;
|
||||
QDateTime end;
|
||||
int minutes = 0;
|
||||
};
|
||||
|
||||
struct DailyReview
|
||||
{
|
||||
QDate date;
|
||||
int total = 0;
|
||||
int done = 0;
|
||||
int active = 0;
|
||||
int missed = 0;
|
||||
int dropped = 0;
|
||||
int overdue = 0;
|
||||
int focusedMinutes = 0;
|
||||
int completionPercent = 0;
|
||||
QVector<FreeWindow> ghostWindows;
|
||||
QStringList highlights;
|
||||
QString summary;
|
||||
QString energySummary;
|
||||
};
|
||||
|
||||
struct Suggestion
|
||||
{
|
||||
enum class Kind
|
||||
{
|
||||
Overdue,
|
||||
GhostTime,
|
||||
Review,
|
||||
Energy,
|
||||
};
|
||||
|
||||
Kind kind = Kind::Review;
|
||||
QString title;
|
||||
QString detail;
|
||||
QDateTime start;
|
||||
QDateTime end;
|
||||
};
|
||||
|
||||
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
const QDateTime& from,
|
||||
int workStartHour = 8,
|
||||
int workEndHour = 22,
|
||||
int minMinutes = 30);
|
||||
|
||||
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
int workStartHour = 8,
|
||||
int workEndHour = 22,
|
||||
int minMinutes = 30);
|
||||
|
||||
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
|
||||
const QDate& date,
|
||||
const QDateTime& now = QDateTime::currentDateTime());
|
||||
|
||||
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
|
||||
const QDateTime& now,
|
||||
int maxCount = 3);
|
||||
@@ -0,0 +1,147 @@
|
||||
#include "EnergyProfile.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace
|
||||
{
|
||||
int clampedLevel(int level)
|
||||
{
|
||||
return std::clamp(level, 0, 2);
|
||||
}
|
||||
|
||||
int clampedWeekday(int weekday)
|
||||
{
|
||||
return std::clamp(weekday, 1, 7);
|
||||
}
|
||||
|
||||
int clampedHour(int hour)
|
||||
{
|
||||
return std::clamp(hour, 0, 23);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
EnergyProfile EnergyProfile::defaults()
|
||||
{
|
||||
EnergyProfile profile;
|
||||
for (int weekday = 1; weekday <= 7; ++weekday)
|
||||
{
|
||||
for (int hour = 0; hour < 24; ++hour)
|
||||
{
|
||||
int level = 0;
|
||||
if (weekday <= 5)
|
||||
{
|
||||
if (hour >= 9 && hour <= 11)
|
||||
{
|
||||
level = 2;
|
||||
}
|
||||
else if (hour == 8 || hour == 12 || hour == 14 || (hour >= 15 && hour <= 18))
|
||||
{
|
||||
level = 1;
|
||||
}
|
||||
}
|
||||
else if ((hour >= 10 && hour <= 11) || (hour >= 14 && hour <= 17))
|
||||
{
|
||||
level = 1;
|
||||
}
|
||||
profile.m_levels[weekday][hour] = level;
|
||||
}
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
EnergyProfile EnergyProfile::fromLevels(const QVector<EnergyLevel>& levels)
|
||||
{
|
||||
EnergyProfile profile = defaults();
|
||||
for (const EnergyLevel& level : levels)
|
||||
{
|
||||
profile.m_levels[clampedWeekday(level.weekday)][clampedHour(level.hour)] =
|
||||
clampedLevel(level.level);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
QString EnergyProfile::label(int level)
|
||||
{
|
||||
switch (clampedLevel(level))
|
||||
{
|
||||
case 2:
|
||||
return QStringLiteral("高");
|
||||
case 1:
|
||||
return QStringLiteral("中");
|
||||
default:
|
||||
return QStringLiteral("低");
|
||||
}
|
||||
}
|
||||
|
||||
int EnergyProfile::level(int weekday, int hour) const
|
||||
{
|
||||
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
return m_levels[weekday][hour];
|
||||
}
|
||||
|
||||
int EnergyProfile::level(const QDateTime& localDateTime) const
|
||||
{
|
||||
if (!localDateTime.isValid())
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
return level(localDateTime.date().dayOfWeek(), localDateTime.time().hour());
|
||||
}
|
||||
|
||||
bool EnergyProfile::setLevel(int weekday, int hour, int levelValue)
|
||||
{
|
||||
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
m_levels[weekday][hour] = clampedLevel(levelValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
QVector<EnergyLevel> EnergyProfile::levels() const
|
||||
{
|
||||
QVector<EnergyLevel> result;
|
||||
result.reserve(7 * 24);
|
||||
for (int weekday = 1; weekday <= 7; ++weekday)
|
||||
{
|
||||
for (int hour = 0; hour < 24; ++hour)
|
||||
{
|
||||
result.append({weekday, hour, m_levels[weekday][hour]});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void EnergyProfile::learn(const QVector<EnergySample>& samples)
|
||||
{
|
||||
std::array<std::array<int, 24>, 8> sums{};
|
||||
std::array<std::array<int, 24>, 8> counts{};
|
||||
for (const EnergySample& sample : samples)
|
||||
{
|
||||
if (sample.weekday < 1 || sample.weekday > 7 || sample.hour < 0 || sample.hour > 23)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sums[sample.weekday][sample.hour] += clampedLevel(sample.level);
|
||||
++counts[sample.weekday][sample.hour];
|
||||
}
|
||||
|
||||
for (int weekday = 1; weekday <= 7; ++weekday)
|
||||
{
|
||||
for (int hour = 0; hour < 24; ++hour)
|
||||
{
|
||||
if (counts[weekday][hour] == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const double average =
|
||||
static_cast<double>(sums[weekday][hour]) / counts[weekday][hour];
|
||||
m_levels[weekday][hour] =
|
||||
std::clamp(static_cast<int>(std::lround(average)), 0, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
#include <array>
|
||||
|
||||
/*
|
||||
* 类名: EnergyProfile
|
||||
* 功能: 按星期与小时保存精力水平(0 低 / 1 中 / 2 高),并从完成记录学习
|
||||
* 线程安全: 否(值类型)
|
||||
*/
|
||||
struct EnergyLevel
|
||||
{
|
||||
int weekday = 1;
|
||||
int hour = 0;
|
||||
int level = 1;
|
||||
};
|
||||
|
||||
struct EnergySample
|
||||
{
|
||||
int weekday = 1;
|
||||
int hour = 0;
|
||||
int level = 1;
|
||||
};
|
||||
|
||||
class EnergyProfile
|
||||
{
|
||||
public:
|
||||
static EnergyProfile defaults();
|
||||
static EnergyProfile fromLevels(const QVector<EnergyLevel>& levels);
|
||||
static QString label(int level);
|
||||
|
||||
int level(int weekday, int hour) const;
|
||||
int level(const QDateTime& localDateTime) const;
|
||||
bool setLevel(int weekday, int hour, int level);
|
||||
QVector<EnergyLevel> levels() const;
|
||||
void learn(const QVector<EnergySample>& samples);
|
||||
|
||||
private:
|
||||
std::array<std::array<int, 24>, 8> m_levels{};
|
||||
};
|
||||
@@ -65,47 +65,62 @@ std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
|
||||
SysTime rangeStart,
|
||||
std::optional<SysTime> deadline,
|
||||
std::chrono::seconds duration,
|
||||
int granularityMinutes)
|
||||
int granularityMinutes,
|
||||
int energyRequired,
|
||||
const Options& options)
|
||||
{
|
||||
const auto energySatisfied = [&](SysTime start) {
|
||||
if (energyRequired < 0 || !options.energyAt)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
const int level = options.energyAt(start);
|
||||
return level < 0 || level >= energyRequired;
|
||||
};
|
||||
const auto nextGrid = [granularityMinutes](SysTime value) {
|
||||
return ceilToGranularity(value + std::chrono::seconds{std::max(1, granularityMinutes) * 60},
|
||||
granularityMinutes);
|
||||
};
|
||||
|
||||
for (const TimeRange& window : windows)
|
||||
{
|
||||
SysTime cursor = ceilToGranularity(std::max(window.start, rangeStart), granularityMinutes);
|
||||
if (cursor >= window.end)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const TimeRange& occupied : busy)
|
||||
{
|
||||
if (occupied.end <= cursor)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (occupied.start >= cursor + duration)
|
||||
{
|
||||
if (deadline && cursor + duration > *deadline)
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
return TimeRange{cursor, cursor + duration};
|
||||
}
|
||||
if (occupied.end > cursor)
|
||||
{
|
||||
cursor = ceilToGranularity(occupied.end, granularityMinutes);
|
||||
if (cursor >= window.end)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cursor + duration <= window.end)
|
||||
while (cursor + duration <= window.end)
|
||||
{
|
||||
if (deadline && cursor + duration > *deadline)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
SysTime occupiedUntil = cursor;
|
||||
bool conflict = false;
|
||||
for (const TimeRange& occupied : busy)
|
||||
{
|
||||
if (occupied.end <= cursor)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (occupied.start >= cursor + duration)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (occupied.start < cursor + duration && occupied.end > cursor)
|
||||
{
|
||||
occupiedUntil = std::max(occupiedUntil, occupied.end);
|
||||
conflict = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (conflict)
|
||||
{
|
||||
cursor = ceilToGranularity(occupiedUntil, granularityMinutes);
|
||||
continue;
|
||||
}
|
||||
return TimeRange{cursor, cursor + duration};
|
||||
if (energySatisfied(cursor))
|
||||
{
|
||||
return TimeRange{cursor, cursor + duration};
|
||||
}
|
||||
cursor = nextGrid(cursor);
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
@@ -212,7 +227,9 @@ Result schedule(const std::vector<TaskInput>& tasks,
|
||||
rangeStart,
|
||||
deadline,
|
||||
duration,
|
||||
options.granularityMinutes);
|
||||
options.granularityMinutes,
|
||||
task.energyRequired,
|
||||
options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +237,14 @@ Result schedule(const std::vector<TaskInput>& tasks,
|
||||
{
|
||||
const SysTime upper = deadline.value_or(rangeEnd);
|
||||
const std::vector<TimeRange> generalWindows = intersect(windows, rangeStart, upper);
|
||||
slot = findSlot(generalWindows, busy, rangeStart, deadline, duration, options.granularityMinutes);
|
||||
slot = findSlot(generalWindows,
|
||||
busy,
|
||||
rangeStart,
|
||||
deadline,
|
||||
duration,
|
||||
options.granularityMinutes,
|
||||
task.energyRequired,
|
||||
options);
|
||||
}
|
||||
|
||||
if (!slot.has_value())
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -50,6 +51,8 @@ struct Failure
|
||||
struct Options
|
||||
{
|
||||
int granularityMinutes = 15;
|
||||
// 返回某个开始时刻的精力水平(0 低 / 1 中 / 2 高);返回 -1 表示未知。
|
||||
std::function<int(SysTime)> energyAt;
|
||||
};
|
||||
|
||||
struct Result
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "core/DailyInsights.h"
|
||||
#include "core/DateTimeUtils.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
|
||||
@@ -21,6 +22,36 @@ QDateTime truncateToMinute(const QDateTime& value)
|
||||
{
|
||||
return QDateTime(value.date(), QTime(value.time().hour(), value.time().minute()), value.timeSpec());
|
||||
}
|
||||
|
||||
QString energySummaryForDate(const EnergyProfile& profile, const QDate& date)
|
||||
{
|
||||
if (!date.isValid())
|
||||
{
|
||||
return {};
|
||||
}
|
||||
QStringList windows;
|
||||
int runStart = -1;
|
||||
for (int hour = 0; hour <= 24; ++hour)
|
||||
{
|
||||
const bool high = hour < 24 && profile.level(date.dayOfWeek(), hour) == 2;
|
||||
if (high && runStart < 0)
|
||||
{
|
||||
runStart = hour;
|
||||
}
|
||||
else if (!high && runStart >= 0)
|
||||
{
|
||||
windows.append(QStringLiteral("%1:00–%2:00")
|
||||
.arg(runStart, 2, 10, QLatin1Char('0'))
|
||||
.arg(hour, 2, 10, QLatin1Char('0')));
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
if (windows.isEmpty())
|
||||
{
|
||||
return QStringLiteral("今天没有明显的高精力时段");
|
||||
}
|
||||
return QStringLiteral("精力高峰:%1").arg(windows.join(QStringLiteral("、")));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject* parent)
|
||||
@@ -28,6 +59,7 @@ ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject*
|
||||
, m_store(store)
|
||||
, m_deviceId(std::move(deviceId))
|
||||
{
|
||||
rebuildEnergyProfile();
|
||||
}
|
||||
|
||||
bool ScheduleService::validateRange(const QDateTime& start, const QDateTime& end, QString* error)
|
||||
@@ -315,6 +347,7 @@ bool ScheduleService::setBlockStatus(const QString& blockId, const QString& stat
|
||||
return false;
|
||||
}
|
||||
m_lastError.clear();
|
||||
rebuildEnergyProfile();
|
||||
Q_EMIT dataChanged();
|
||||
return true;
|
||||
}
|
||||
@@ -404,6 +437,7 @@ bool ScheduleService::deleteBlock(const QString& blockId, QString* error)
|
||||
}
|
||||
|
||||
m_lastError.clear();
|
||||
rebuildEnergyProfile();
|
||||
Q_EMIT dataChanged();
|
||||
return true;
|
||||
}
|
||||
@@ -889,6 +923,7 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
|
||||
}
|
||||
|
||||
m_lastError.clear();
|
||||
rebuildEnergyProfile();
|
||||
Q_EMIT dataChanged();
|
||||
return true;
|
||||
}
|
||||
@@ -948,5 +983,42 @@ QString ScheduleService::lastError() const
|
||||
|
||||
void ScheduleService::notifyDataChanged()
|
||||
{
|
||||
rebuildEnergyProfile();
|
||||
Q_EMIT dataChanged();
|
||||
}
|
||||
|
||||
const EnergyProfile& ScheduleService::energyProfile() const
|
||||
{
|
||||
return m_energyProfile;
|
||||
}
|
||||
|
||||
int ScheduleService::energyLevelFor(const QDateTime& localDateTime) const
|
||||
{
|
||||
return m_energyProfile.level(localDateTime);
|
||||
}
|
||||
|
||||
DailyReview ScheduleService::dailyReview(const QDate& date) const
|
||||
{
|
||||
QDateTime now = QDateTime::currentDateTime();
|
||||
if (date != now.date())
|
||||
{
|
||||
now = date < now.date() ? QDateTime(date, QTime(23, 59), Qt::LocalTime)
|
||||
: QDateTime(date, QTime(0, 0), Qt::LocalTime);
|
||||
}
|
||||
DailyReview review = buildDailyReview(itemsForDay(date), date, now);
|
||||
review.energySummary = energySummaryForDate(m_energyProfile, date);
|
||||
return review;
|
||||
}
|
||||
|
||||
QVector<Suggestion> ScheduleService::suggestions(const QDateTime& now) const
|
||||
{
|
||||
return buildSuggestions(itemsForDay(now.date()), now);
|
||||
}
|
||||
|
||||
void ScheduleService::rebuildEnergyProfile()
|
||||
{
|
||||
EnergyProfile profile = EnergyProfile::defaults();
|
||||
profile.learn(m_store.completedEnergySamples());
|
||||
m_energyProfile = profile;
|
||||
m_store.replaceEnergyLevels(m_energyProfile.levels());
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
#include "core/DailyInsights.h"
|
||||
#include "core/EnergyProfile.h"
|
||||
#include "core/ProposedDiff.h"
|
||||
#include "core/ScheduleItem.h"
|
||||
|
||||
@@ -52,6 +54,14 @@ public:
|
||||
QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const;
|
||||
QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const;
|
||||
QString lastError() const;
|
||||
|
||||
const EnergyProfile& energyProfile() const;
|
||||
int energyLevelFor(const QDateTime& localDateTime) const;
|
||||
void rebuildEnergyProfile();
|
||||
|
||||
DailyReview dailyReview(const QDate& date) const;
|
||||
QVector<Suggestion> suggestions(const QDateTime& now = QDateTime::currentDateTime()) const;
|
||||
|
||||
// 供同步层在外部写入后通知 UI 刷新。
|
||||
void notifyDataChanged();
|
||||
|
||||
@@ -67,4 +77,5 @@ private:
|
||||
SqliteStore& m_store;
|
||||
QString m_deviceId;
|
||||
QString m_lastError;
|
||||
EnergyProfile m_energyProfile;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "SqliteStore.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <QDir>
|
||||
#include <QJsonDocument>
|
||||
#include <QFileInfo>
|
||||
@@ -1053,6 +1055,106 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
|
||||
return true;
|
||||
}
|
||||
|
||||
QVector<EnergyLevel> SqliteStore::energyLevels() const
|
||||
{
|
||||
m_lastError.clear();
|
||||
QVector<EnergyLevel> levels;
|
||||
if (!isOpenInternal())
|
||||
{
|
||||
setError(QStringLiteral("数据库未打开"));
|
||||
return levels;
|
||||
}
|
||||
QSqlQuery query(m_database);
|
||||
if (!query.exec(QStringLiteral(
|
||||
"SELECT weekday, hour_slot, level FROM energy_profile ORDER BY weekday, hour_slot")))
|
||||
{
|
||||
setError(QStringLiteral("查询精力档案失败: %1").arg(query.lastError().text()));
|
||||
return levels;
|
||||
}
|
||||
while (query.next())
|
||||
{
|
||||
levels.append({query.value(0).toInt(), query.value(1).toInt(), query.value(2).toInt()});
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
bool SqliteStore::replaceEnergyLevels(const QVector<EnergyLevel>& levels)
|
||||
{
|
||||
m_lastError.clear();
|
||||
if (!isOpenInternal())
|
||||
{
|
||||
return setError(QStringLiteral("数据库未打开"));
|
||||
}
|
||||
if (!m_database.transaction())
|
||||
{
|
||||
return setError(QStringLiteral("开启精力档案事务失败: %1").arg(m_database.lastError().text()));
|
||||
}
|
||||
QSqlQuery clear(m_database);
|
||||
if (!clear.exec(QStringLiteral("DELETE FROM energy_profile")))
|
||||
{
|
||||
m_database.rollback();
|
||||
return setError(QStringLiteral("清理精力档案失败: %1").arg(clear.lastError().text()));
|
||||
}
|
||||
QSqlQuery insert(m_database);
|
||||
insert.prepare(QStringLiteral(
|
||||
"INSERT OR REPLACE INTO energy_profile(id, weekday, hour_slot, level) "
|
||||
"VALUES (:id, :weekday, :hour_slot, :level)"));
|
||||
for (const EnergyLevel& level : levels)
|
||||
{
|
||||
insert.bindValue(QStringLiteral(":id"),
|
||||
QStringLiteral("%1-%2").arg(level.weekday).arg(level.hour));
|
||||
insert.bindValue(QStringLiteral(":weekday"), level.weekday);
|
||||
insert.bindValue(QStringLiteral(":hour_slot"), level.hour);
|
||||
insert.bindValue(QStringLiteral(":level"), std::clamp(level.level, 0, 2));
|
||||
if (!insert.exec())
|
||||
{
|
||||
m_database.rollback();
|
||||
return setError(QStringLiteral("写入精力档案失败: %1").arg(insert.lastError().text()));
|
||||
}
|
||||
}
|
||||
if (!m_database.commit())
|
||||
{
|
||||
m_database.rollback();
|
||||
return setError(QStringLiteral("提交精力档案失败: %1").arg(m_database.lastError().text()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
QVector<EnergySample> SqliteStore::completedEnergySamples() const
|
||||
{
|
||||
m_lastError.clear();
|
||||
QVector<EnergySample> samples;
|
||||
if (!isOpenInternal())
|
||||
{
|
||||
setError(QStringLiteral("数据库未打开"));
|
||||
return samples;
|
||||
}
|
||||
QSqlQuery query(m_database);
|
||||
if (!query.exec(QStringLiteral(
|
||||
"SELECT t.energy_req, b.start_at, b.end_at FROM timeblock b "
|
||||
"JOIN task t ON t.id = b.task_id "
|
||||
"WHERE b.status = 'done' AND t.energy_req IS NOT NULL")))
|
||||
{
|
||||
setError(QStringLiteral("查询精力样本失败: %1").arg(query.lastError().text()));
|
||||
return samples;
|
||||
}
|
||||
while (query.next())
|
||||
{
|
||||
const int level = std::clamp(query.value(0).toInt(), 0, 2);
|
||||
const QDateTime start = DateTimeUtils::fromDb(query.value(1).toString());
|
||||
const QDateTime end = DateTimeUtils::fromDb(query.value(2).toString());
|
||||
if (!start.isValid() || !end.isValid() || start >= end)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (QDateTime cursor = start; cursor < end; cursor = cursor.addSecs(3600))
|
||||
{
|
||||
samples.append({cursor.date().dayOfWeek(), cursor.time().hour(), level});
|
||||
}
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
qint64 SqliteStore::syncCursor(const QString& deviceId, QString* error) const
|
||||
{
|
||||
m_lastError.clear();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <atomic>
|
||||
#include <optional>
|
||||
|
||||
#include "core/EnergyProfile.h"
|
||||
#include "core/ProposedDiff.h"
|
||||
#include "core/SyncTypes.h"
|
||||
#include "core/ScheduleItem.h"
|
||||
@@ -64,6 +65,10 @@ public:
|
||||
qint64 syncCursor(const QString& deviceId, QString* error = nullptr) const;
|
||||
bool setSyncCursor(const QString& deviceId, qint64 seq, QString* error = nullptr);
|
||||
|
||||
QVector<EnergyLevel> energyLevels() const;
|
||||
bool replaceEnergyLevels(const QVector<EnergyLevel>& levels);
|
||||
QVector<EnergySample> completedEnergySamples() const;
|
||||
|
||||
private:
|
||||
bool openDatabase(QString* error);
|
||||
bool configureConnection(QString* error);
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "sync/SyncService.h"
|
||||
#include "ui/MainWindow.h"
|
||||
#include "ui/dialogs/BlockEditDialog.h"
|
||||
#include "ui/dialogs/DailyReviewDialog.h"
|
||||
#include "ui/dialogs/SettingsDialog.h"
|
||||
#include "ui/panels/ChatPanel.h"
|
||||
#include "ui/panels/TodayPanel.h"
|
||||
@@ -175,6 +176,8 @@ void CompactWindow::buildUi()
|
||||
connect(openShortcut, &QShortcut::activated, this, &CompactWindow::openSchedule);
|
||||
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
|
||||
connect(settingsShortcut, &QShortcut::activated, this, &CompactWindow::openSettings);
|
||||
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
|
||||
connect(reviewShortcut, &QShortcut::activated, this, &CompactWindow::openDailyReview);
|
||||
}
|
||||
|
||||
void CompactWindow::setupTray()
|
||||
@@ -244,6 +247,7 @@ void CompactWindow::connectSignals()
|
||||
m_scheduleWindow->focusBlock(QDate::currentDate(), id);
|
||||
}
|
||||
});
|
||||
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &CompactWindow::openDailyReview);
|
||||
|
||||
connect(&m_notificationService,
|
||||
&NotificationService::overdueListChanged,
|
||||
@@ -332,8 +336,13 @@ void CompactWindow::reloadToday()
|
||||
.arg(today.day())
|
||||
.arg(weekdayLabel(today)));
|
||||
m_todayItems = m_scheduleService.itemsForDay(today);
|
||||
const QDateTime now = QDateTime::currentDateTime();
|
||||
m_todayPanel->setDate(today);
|
||||
m_todayPanel->setItems(m_todayItems, QDateTime::currentDateTime());
|
||||
m_todayPanel->setItems(m_todayItems, now);
|
||||
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
|
||||
m_todayPanel->setInsightText(
|
||||
suggestions.isEmpty() ? QString()
|
||||
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
|
||||
}
|
||||
|
||||
void CompactWindow::openSchedule()
|
||||
@@ -362,6 +371,13 @@ void CompactWindow::openSettings()
|
||||
dialog.exec();
|
||||
}
|
||||
|
||||
void CompactWindow::openDailyReview()
|
||||
{
|
||||
DailyReviewDialog dialog(m_scheduleService.dailyReview(QDate::currentDate()), m_tokens, this);
|
||||
dialog.moveToCenter();
|
||||
dialog.exec();
|
||||
}
|
||||
|
||||
void CompactWindow::updateSyncStatus(const QString& status)
|
||||
{
|
||||
if (!m_syncLabel)
|
||||
|
||||
@@ -62,6 +62,7 @@ private:
|
||||
void reloadToday();
|
||||
void openSchedule();
|
||||
void openSettings();
|
||||
void openDailyReview();
|
||||
void openEditDialog(const QString& blockId);
|
||||
void showError(const QString& title, const QString& message);
|
||||
void updateSyncStatus(const QString& status);
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
#include "services/ScheduleService.h"
|
||||
#include "sync/SyncService.h"
|
||||
#include "ui/dialogs/BlockEditDialog.h"
|
||||
#include "ui/dialogs/DailyReviewDialog.h"
|
||||
#include "ui/dialogs/SettingsDialog.h"
|
||||
#include "ui/panels/TodayPanel.h"
|
||||
#include "ui/theme/ThemeManager.h"
|
||||
@@ -144,10 +145,10 @@ void MainWindow::buildUi()
|
||||
m_newButton->setToolTip(QStringLiteral("新建日程 (Ctrl+N)"));
|
||||
|
||||
m_searchEdit = new ElaLineEdit(m_toolbar);
|
||||
m_searchEdit->setPlaceholderText(QStringLiteral("搜索(阶段 4)"));
|
||||
m_searchEdit->setPlaceholderText(QStringLiteral("搜索(后续版本)"));
|
||||
m_searchEdit->setFixedSize(140, 30);
|
||||
m_searchEdit->setEnabled(false);
|
||||
m_searchEdit->setToolTip(QStringLiteral("搜索将在阶段 4 接入"));
|
||||
m_searchEdit->setToolTip(QStringLiteral("搜索将在后续版本接入"));
|
||||
|
||||
m_snapCombo = new ElaComboBox(m_toolbar);
|
||||
m_snapCombo->addItems({QStringLiteral("吸附 15 分"),
|
||||
@@ -310,6 +311,9 @@ void MainWindow::buildUi()
|
||||
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
|
||||
connect(settingsShortcut, &QShortcut::activated, this, &MainWindow::openSettings);
|
||||
|
||||
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
|
||||
connect(reviewShortcut, &QShortcut::activated, this, &MainWindow::openDailyReview);
|
||||
|
||||
auto* compactShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+W")), this);
|
||||
connect(compactShortcut, &QShortcut::activated, this, &MainWindow::close);
|
||||
}
|
||||
@@ -405,6 +409,7 @@ void MainWindow::connectSignals()
|
||||
m_grid->scrollToBlock(id);
|
||||
m_grid->setFocus(Qt::OtherFocusReason);
|
||||
});
|
||||
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &MainWindow::openDailyReview);
|
||||
|
||||
connect(&m_notificationService,
|
||||
&NotificationService::overdueListChanged,
|
||||
@@ -590,8 +595,30 @@ void MainWindow::reloadCurrentView()
|
||||
}
|
||||
}
|
||||
|
||||
if (m_currentView == View::Day)
|
||||
{
|
||||
const QDateTime ghostFrom =
|
||||
m_currentDate == now.date() ? now : QDateTime(m_currentDate, QTime(8, 0), Qt::LocalTime);
|
||||
m_grid->setGhostWindows(findFreeWindows(agendaItems, m_currentDate, ghostFrom, 8, 22, 30));
|
||||
}
|
||||
else
|
||||
{
|
||||
m_grid->setGhostWindows({});
|
||||
}
|
||||
|
||||
m_todayPanel->setDate(m_currentDate);
|
||||
m_todayPanel->setItems(agendaItems, now);
|
||||
if (m_currentDate == QDate::currentDate())
|
||||
{
|
||||
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
|
||||
m_todayPanel->setInsightText(
|
||||
suggestions.isEmpty() ? QString()
|
||||
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
|
||||
}
|
||||
else
|
||||
{
|
||||
m_todayPanel->setInsightText(QString());
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::navigateToDate(const QDate& date)
|
||||
@@ -816,6 +843,13 @@ void MainWindow::openSettings()
|
||||
dialog.exec();
|
||||
}
|
||||
|
||||
void MainWindow::openDailyReview()
|
||||
{
|
||||
DailyReviewDialog dialog(m_scheduleService.dailyReview(m_currentDate), m_tokens, this);
|
||||
dialog.moveToCenter();
|
||||
dialog.exec();
|
||||
}
|
||||
|
||||
void MainWindow::updateSyncStatus(const QString& status)
|
||||
{
|
||||
if (!m_syncLabel)
|
||||
|
||||
@@ -89,6 +89,7 @@ private:
|
||||
void openCreateDialogForNew();
|
||||
void openEditDialog(const QString& blockId);
|
||||
void openSettings();
|
||||
void openDailyReview();
|
||||
void updateOverdueBanner(const QVector<ScheduleItem>& items);
|
||||
void showError(const QString& title, const QString& message);
|
||||
void updateSyncStatus(const QString& status);
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
#include "DailyReviewDialog.h"
|
||||
|
||||
#include <QGridLayout>
|
||||
|
||||
#include <algorithm>
|
||||
#include <QHBoxLayout>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include "ElaPushButton.h"
|
||||
#include "ElaText.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
QString formatWindow(const FreeWindow& window)
|
||||
{
|
||||
return QStringLiteral("%1–%2 · %3")
|
||||
.arg(window.start.toString(QStringLiteral("HH:mm")),
|
||||
window.end.toString(QStringLiteral("HH:mm")),
|
||||
window.minutes >= 60
|
||||
? QStringLiteral("%1 小时 %2 分").arg(window.minutes / 60).arg(window.minutes % 60)
|
||||
: QStringLiteral("%1 分钟").arg(window.minutes));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DailyReviewDialog::DailyReviewDialog(const DailyReview& review,
|
||||
const ThemeTokens& tokens,
|
||||
QWidget* parent)
|
||||
: ElaDialog(parent)
|
||||
{
|
||||
setWindowTitle(QStringLiteral("今日复盘"));
|
||||
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
|
||||
resize(520, 560);
|
||||
setMinimumWidth(480);
|
||||
|
||||
auto* root = new QVBoxLayout(this);
|
||||
root->setContentsMargins(24, 8, 24, 18);
|
||||
root->setSpacing(10);
|
||||
|
||||
auto* title = new ElaText(QStringLiteral("%1月%2日 · %3复盘")
|
||||
.arg(review.date.month())
|
||||
.arg(review.date.day())
|
||||
.arg(weekdayLabel(review.date)),
|
||||
17,
|
||||
this);
|
||||
QFont titleFont = title->font();
|
||||
titleFont.setWeight(QFont::DemiBold);
|
||||
title->setFont(titleFont);
|
||||
root->addWidget(title);
|
||||
|
||||
auto* summary = new ElaText(review.summary, 14, this);
|
||||
summary->setWordWrap(true);
|
||||
summary->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.textPrimary.name()));
|
||||
root->addWidget(summary);
|
||||
|
||||
auto* grid = new QGridLayout();
|
||||
grid->setHorizontalSpacing(28);
|
||||
grid->setVerticalSpacing(8);
|
||||
const auto addStat = [this, grid](int row, int column, const QString& label, const QString& value) {
|
||||
auto* labelText = new ElaText(label, 11, this);
|
||||
labelText->setTextStyle(ElaTextType::Caption);
|
||||
auto* valueText = new ElaText(value, 14, this);
|
||||
QFont valueFont = valueText->font();
|
||||
valueFont.setWeight(QFont::DemiBold);
|
||||
valueText->setFont(valueFont);
|
||||
grid->addWidget(labelText, row, column);
|
||||
grid->addWidget(valueText, row + 1, column);
|
||||
};
|
||||
addStat(0, 0, QStringLiteral("完成"), QStringLiteral("%1 / %2").arg(review.done).arg(review.total));
|
||||
addStat(0, 1, QStringLiteral("完成率"), QStringLiteral("%1%").arg(review.completionPercent));
|
||||
addStat(0, 2, QStringLiteral("专注"), QStringLiteral("%1 分钟").arg(review.focusedMinutes));
|
||||
addStat(2, 0, QStringLiteral("待办"), QString::number(review.active));
|
||||
addStat(2, 1, QStringLiteral("超时"), QString::number(review.overdue));
|
||||
addStat(2, 2, QStringLiteral("错过 / 放弃"),
|
||||
QStringLiteral("%1 / %2").arg(review.missed).arg(review.dropped));
|
||||
root->addLayout(grid);
|
||||
|
||||
if (!review.energySummary.isEmpty())
|
||||
{
|
||||
auto* energy = new ElaText(review.energySummary, 12, this);
|
||||
energy->setWordWrap(true);
|
||||
energy->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
|
||||
root->addWidget(energy);
|
||||
}
|
||||
|
||||
auto* highlightsTitle = new ElaText(QStringLiteral("今日概览"), 13, this);
|
||||
QFont sectionFont = highlightsTitle->font();
|
||||
sectionFont.setWeight(QFont::DemiBold);
|
||||
highlightsTitle->setFont(sectionFont);
|
||||
root->addWidget(highlightsTitle);
|
||||
for (const QString& highlight : review.highlights)
|
||||
{
|
||||
auto* line = new ElaText(QStringLiteral("· %1").arg(highlight), 12, this);
|
||||
line->setWordWrap(true);
|
||||
root->addWidget(line);
|
||||
}
|
||||
|
||||
auto* ghostTitle = new ElaText(QStringLiteral("幽灵时间"), 13, this);
|
||||
ghostTitle->setFont(sectionFont);
|
||||
root->addWidget(ghostTitle);
|
||||
if (review.ghostWindows.isEmpty())
|
||||
{
|
||||
auto* empty = new ElaText(QStringLiteral("今天没有 30 分钟以上的空档。"), 12, this);
|
||||
empty->setTextStyle(ElaTextType::Caption);
|
||||
root->addWidget(empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
const qsizetype count = std::min<qsizetype>(5, review.ghostWindows.size());
|
||||
for (int i = 0; i < count; ++i)
|
||||
{
|
||||
auto* line = new ElaText(QStringLiteral("· %1").arg(formatWindow(review.ghostWindows.at(i))),
|
||||
12,
|
||||
this);
|
||||
root->addWidget(line);
|
||||
}
|
||||
if (review.ghostWindows.size() > count)
|
||||
{
|
||||
auto* more = new ElaText(QStringLiteral("还有 %1 段空档")
|
||||
.arg(review.ghostWindows.size() - count),
|
||||
11,
|
||||
this);
|
||||
more->setTextStyle(ElaTextType::Caption);
|
||||
root->addWidget(more);
|
||||
}
|
||||
}
|
||||
|
||||
root->addStretch(1);
|
||||
auto* buttonRow = new QHBoxLayout();
|
||||
buttonRow->addStretch(1);
|
||||
auto* closeButton = new ElaPushButton(QStringLiteral("完成"), this);
|
||||
closeButton->setFixedSize(88, 34);
|
||||
closeButton->setDefault(true);
|
||||
buttonRow->addWidget(closeButton);
|
||||
root->addLayout(buttonRow);
|
||||
connect(closeButton, &ElaPushButton::clicked, this, &DailyReviewDialog::accept);
|
||||
}
|
||||
|
||||
QString DailyReviewDialog::weekdayLabel(const QDate& date) const
|
||||
{
|
||||
if (!date.isValid())
|
||||
{
|
||||
return {};
|
||||
}
|
||||
static const char* labels[] = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
|
||||
return QString::fromUtf8(labels[date.dayOfWeek() - 1]);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "ElaDialog.h"
|
||||
#include "core/DailyInsights.h"
|
||||
#include "ui/theme/ThemeTokens.h"
|
||||
|
||||
/*
|
||||
* 类名: DailyReviewDialog
|
||||
* 功能: 展示每日完成情况、精力高峰与幽灵时间
|
||||
* 线程安全: 否;UI 线程
|
||||
*/
|
||||
class DailyReviewDialog : public ElaDialog
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
DailyReviewDialog(const DailyReview& review, const ThemeTokens& tokens, QWidget* parent = nullptr);
|
||||
|
||||
private:
|
||||
QString weekdayLabel(const QDate& date) const;
|
||||
};
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "ElaScrollArea.h"
|
||||
#include "ElaText.h"
|
||||
#include "ElaToolButton.h"
|
||||
#include "TodayItemCard.h"
|
||||
|
||||
TodayPanel::TodayPanel(QWidget* parent)
|
||||
@@ -31,11 +32,26 @@ TodayPanel::TodayPanel(QWidget* parent)
|
||||
m_titleLabel->setFont(titleFont);
|
||||
m_countLabel = new ElaText(this);
|
||||
m_countLabel->setTextPixelSize(11);
|
||||
m_reviewButton = new ElaToolButton(this);
|
||||
m_reviewButton->setIsTransparent(true);
|
||||
m_reviewButton->setElaIcon(ElaIconType::ClipboardCheck);
|
||||
m_reviewButton->setFixedSize(26, 26);
|
||||
m_reviewButton->setToolTip(QStringLiteral("今日复盘 (Ctrl+R)"));
|
||||
connect(m_reviewButton, &ElaToolButton::clicked, this, &TodayPanel::reviewRequested);
|
||||
|
||||
header->addWidget(m_titleLabel);
|
||||
header->addStretch(1);
|
||||
header->addWidget(m_countLabel, 0, Qt::AlignVCenter);
|
||||
header->addWidget(m_reviewButton, 0, Qt::AlignVCenter);
|
||||
root->addLayout(header);
|
||||
|
||||
m_insightLabel = new ElaText(this);
|
||||
m_insightLabel->setTextPixelSize(11);
|
||||
m_insightLabel->setTextStyle(ElaTextType::Caption);
|
||||
m_insightLabel->setWordWrap(true);
|
||||
m_insightLabel->setVisible(false);
|
||||
root->addWidget(m_insightLabel);
|
||||
|
||||
m_scrollArea = new ElaScrollArea(this);
|
||||
m_scrollArea->setWidgetResizable(true);
|
||||
m_scrollArea->setFrameShape(QFrame::NoFrame);
|
||||
@@ -59,9 +75,23 @@ TodayPanel::TodayPanel(QWidget* parent)
|
||||
void TodayPanel::setTokens(const ThemeTokens& tokens)
|
||||
{
|
||||
m_tokens = tokens;
|
||||
if (m_insightLabel)
|
||||
{
|
||||
m_insightLabel->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
|
||||
}
|
||||
rebuild();
|
||||
}
|
||||
|
||||
void TodayPanel::setInsightText(const QString& text)
|
||||
{
|
||||
if (!m_insightLabel)
|
||||
{
|
||||
return;
|
||||
}
|
||||
m_insightLabel->setText(text);
|
||||
m_insightLabel->setVisible(!text.trimmed().isEmpty());
|
||||
}
|
||||
|
||||
void TodayPanel::setDate(const QDate& date)
|
||||
{
|
||||
if (!m_titleLabel)
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
class ElaScrollArea;
|
||||
class ElaText;
|
||||
class ElaToolButton;
|
||||
class QVBoxLayout;
|
||||
|
||||
/*
|
||||
@@ -26,6 +27,7 @@ public:
|
||||
void setTokens(const ThemeTokens& tokens);
|
||||
void setDate(const QDate& date);
|
||||
void setItems(const QVector<ScheduleItem>& items, const QDateTime& now);
|
||||
void setInsightText(const QString& text);
|
||||
|
||||
signals:
|
||||
void editRequested(const QString& blockId);
|
||||
@@ -33,6 +35,7 @@ signals:
|
||||
void postponeRequested(const QString& blockId, int minutes);
|
||||
void deleteRequested(const QString& blockId);
|
||||
void focusRequested(const QString& blockId);
|
||||
void reviewRequested();
|
||||
|
||||
private:
|
||||
void rebuild();
|
||||
@@ -44,6 +47,8 @@ private:
|
||||
|
||||
ElaText* m_titleLabel = nullptr;
|
||||
ElaText* m_countLabel = nullptr;
|
||||
ElaText* m_insightLabel = nullptr;
|
||||
ElaToolButton* m_reviewButton = nullptr;
|
||||
ElaScrollArea* m_scrollArea = nullptr;
|
||||
QWidget* m_listWidget = nullptr;
|
||||
QVBoxLayout* m_listLayout = nullptr;
|
||||
|
||||
@@ -102,6 +102,12 @@ const QVector<ScheduleItem>& ScheduleGridView::blocks() const
|
||||
return m_blocks;
|
||||
}
|
||||
|
||||
void ScheduleGridView::setGhostWindows(const QVector<FreeWindow>& windows)
|
||||
{
|
||||
m_ghostWindows = windows;
|
||||
viewport()->update();
|
||||
}
|
||||
|
||||
void ScheduleGridView::setTokens(const ThemeTokens& tokens)
|
||||
{
|
||||
m_tokens = tokens;
|
||||
@@ -958,12 +964,54 @@ void ScheduleGridView::paintEvent(QPaintEvent* event)
|
||||
}
|
||||
|
||||
const int scroll = verticalScrollBar()->value();
|
||||
paintGhostWindows(painter, scroll);
|
||||
paintBlocks(painter, scroll);
|
||||
paintNowLine(painter, scroll);
|
||||
paintCreatePreview(painter, scroll);
|
||||
paintEmptyHint(painter, scroll);
|
||||
}
|
||||
|
||||
void ScheduleGridView::paintGhostWindows(QPainter& painter, int scrollY)
|
||||
{
|
||||
if (m_ghostWindows.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
painter.save();
|
||||
painter.setClipRect(QRectF(m_axisWidth + 1,
|
||||
0,
|
||||
viewport()->width() - m_axisWidth - 1,
|
||||
viewport()->height()));
|
||||
painter.translate(0, -scrollY);
|
||||
QColor fill = m_tokens.accent;
|
||||
fill.setAlpha(m_tokens.dark ? 24 : 18);
|
||||
QColor border = m_tokens.accent;
|
||||
border.setAlpha(m_tokens.dark ? 100 : 80);
|
||||
QFont font = painter.font();
|
||||
font.setPixelSize(11);
|
||||
painter.setFont(font);
|
||||
for (const FreeWindow& window : m_ghostWindows)
|
||||
{
|
||||
QRectF rect = rectForTimes(window.start, window.end).adjusted(4, 2, -4, -2);
|
||||
if (rect.height() < 16)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
QPainterPath path;
|
||||
path.addRoundedRect(rect, 6, 6);
|
||||
painter.fillPath(path, fill);
|
||||
QPen pen(border, 1.0, Qt::DashLine);
|
||||
painter.setPen(pen);
|
||||
painter.setBrush(Qt::NoBrush);
|
||||
painter.drawPath(path);
|
||||
painter.setPen(m_tokens.textMuted);
|
||||
const QString text = QStringLiteral("幽灵时间 · %1")
|
||||
.arg(DateTimeUtils::formatDuration(window.minutes));
|
||||
painter.drawText(rect.adjusted(10, 0, -8, 0), Qt::AlignLeft | Qt::AlignVCenter, text);
|
||||
}
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
void ScheduleGridView::paintBlocks(QPainter& painter, int scrollY)
|
||||
{
|
||||
painter.save();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <QSize>
|
||||
#include <QVector>
|
||||
|
||||
#include "core/DailyInsights.h"
|
||||
#include "core/ScheduleItem.h"
|
||||
#include "ui/theme/ThemeTokens.h"
|
||||
|
||||
@@ -27,6 +28,7 @@ public:
|
||||
|
||||
void setBlocks(const QVector<ScheduleItem>& blocks);
|
||||
const QVector<ScheduleItem>& blocks() const;
|
||||
void setGhostWindows(const QVector<FreeWindow>& windows);
|
||||
|
||||
void setTokens(const ThemeTokens& tokens);
|
||||
void setSnapMinutes(int minutes);
|
||||
@@ -84,6 +86,7 @@ private:
|
||||
void ensureGridCache();
|
||||
void invalidateGridCache();
|
||||
void paintGrid(QPainter& painter);
|
||||
void paintGhostWindows(QPainter& painter, int scrollY);
|
||||
void paintBlocks(QPainter& painter, int scrollY);
|
||||
void paintBlock(QPainter& painter, const VisualBlock& visual);
|
||||
void paintNowLine(QPainter& painter, int scrollY);
|
||||
@@ -117,6 +120,7 @@ private:
|
||||
|
||||
QDate m_date;
|
||||
QVector<ScheduleItem> m_blocks;
|
||||
QVector<FreeWindow> m_ghostWindows;
|
||||
QVector<VisualBlock> m_visuals;
|
||||
ThemeTokens m_tokens;
|
||||
int m_snapMinutes = 15;
|
||||
|
||||
@@ -26,6 +26,10 @@ add_executable(test_scheduler test_scheduler.cpp)
|
||||
target_link_libraries(test_scheduler PRIVATE schedule_core Qt6::Test schedule_warnings)
|
||||
add_test(NAME scheduler COMMAND test_scheduler)
|
||||
|
||||
add_executable(test_energy test_energy.cpp)
|
||||
target_link_libraries(test_energy PRIVATE schedule_core Qt6::Test schedule_warnings)
|
||||
add_test(NAME energy COMMAND test_energy)
|
||||
|
||||
add_executable(test_ai test_ai.cpp)
|
||||
target_link_libraries(test_ai PRIVATE schedule_ai Qt6::Test schedule_warnings)
|
||||
add_test(NAME ai COMMAND test_ai)
|
||||
@@ -47,7 +51,7 @@ endif()
|
||||
if(WIN32)
|
||||
set_target_properties(
|
||||
test_storage test_services test_grid test_mainwindow test_compactwindow
|
||||
test_config test_scheduler test_ai test_openai_provider test_sync_integration
|
||||
test_config test_scheduler test_energy test_ai test_openai_provider test_sync_integration
|
||||
PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "storage/SqliteStore.h"
|
||||
#include "ui/CompactWindow.h"
|
||||
#include "ui/MainWindow.h"
|
||||
#include "ui/dialogs/DailyReviewDialog.h"
|
||||
#include "ui/dialogs/SettingsDialog.h"
|
||||
#include "ui/panels/DiffPreviewCard.h"
|
||||
#include "ui/theme/ThemeManager.h"
|
||||
@@ -60,6 +61,7 @@ class TestCompactWindow : public QObject
|
||||
private slots:
|
||||
void initTestCase();
|
||||
void compactOpensScheduleAndReturns();
|
||||
void opensDailyReview();
|
||||
void aiChatShowsDiffAndAccepts();
|
||||
void aiChatShowsMultiOperationDiff();
|
||||
|
||||
@@ -217,6 +219,13 @@ void TestCompactWindow::compactOpensScheduleAndReturns()
|
||||
}
|
||||
saveWindow(scheduleWindow, QStringLiteral("schedule-day.png"));
|
||||
|
||||
if (auto* grid = scheduleWindow->findChild<ScheduleGridView*>())
|
||||
{
|
||||
grid->scrollToHour(18);
|
||||
QTest::qWait(80);
|
||||
}
|
||||
saveWindow(scheduleWindow, QStringLiteral("schedule-ghost.png"));
|
||||
|
||||
scheduleWindow->setView(MainWindow::View::Month);
|
||||
QTest::qWait(200);
|
||||
QCOMPARE(scheduleWindow->view(), MainWindow::View::Month);
|
||||
@@ -266,6 +275,59 @@ void TestCompactWindow::compactOpensScheduleAndReturns()
|
||||
QTest::mouseClick(settingsButton, Qt::LeftButton);
|
||||
}
|
||||
|
||||
void TestCompactWindow::opensDailyReview()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
QVERIFY(databaseDir.isValid());
|
||||
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
ThemeManager theme(*m_settings);
|
||||
theme.initialize();
|
||||
ScheduleService service(store, QStringLiteral("review-test"));
|
||||
NotificationService notifications(service);
|
||||
AIService aiService(service, store, *m_settings);
|
||||
createSampleData(service, QDate::currentDate());
|
||||
|
||||
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
|
||||
compact.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&compact));
|
||||
QTest::qWait(300);
|
||||
|
||||
ElaToolButton* reviewButton = nullptr;
|
||||
for (ElaToolButton* button : compact.findChildren<ElaToolButton*>())
|
||||
{
|
||||
if (button->toolTip().startsWith(QStringLiteral("今日复盘")))
|
||||
{
|
||||
reviewButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(reviewButton);
|
||||
|
||||
QTimer::singleShot(400, []() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* dialog = qobject_cast<DailyReviewDialog*>(widget))
|
||||
{
|
||||
saveWindow(dialog, QStringLiteral("review.png"));
|
||||
dialog->reject();
|
||||
}
|
||||
}
|
||||
});
|
||||
QTimer::singleShot(2000, []() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* dialog = qobject_cast<DailyReviewDialog*>(widget))
|
||||
{
|
||||
dialog->reject();
|
||||
}
|
||||
}
|
||||
});
|
||||
QTest::mouseClick(reviewButton, Qt::LeftButton);
|
||||
}
|
||||
|
||||
void TestCompactWindow::aiChatShowsDiffAndAccepts()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include "core/DailyInsights.h"
|
||||
#include "core/EnergyProfile.h"
|
||||
|
||||
class TestEnergy : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void defaultProfileHasCurve();
|
||||
void learnsFromSamples();
|
||||
void rejectsInvalidCoordinates();
|
||||
void findsGhostWindows();
|
||||
void buildsDailyReviewAndSuggestions();
|
||||
};
|
||||
|
||||
void TestEnergy::defaultProfileHasCurve()
|
||||
{
|
||||
const EnergyProfile profile = EnergyProfile::defaults();
|
||||
QCOMPARE(profile.level(1, 9), 2);
|
||||
QCOMPARE(profile.level(1, 13), 0);
|
||||
QCOMPARE(profile.level(7, 9), 0);
|
||||
QCOMPARE(profile.level(7, 10), 1);
|
||||
QCOMPARE(profile.level(0, 9), -1);
|
||||
QCOMPARE(EnergyProfile::label(2), QStringLiteral("高"));
|
||||
QCOMPARE(profile.levels().size(), 7 * 24);
|
||||
}
|
||||
|
||||
void TestEnergy::learnsFromSamples()
|
||||
{
|
||||
EnergyProfile profile = EnergyProfile::defaults();
|
||||
profile.learn({{1, 13, 2}, {1, 13, 2}, {1, 9, 0}});
|
||||
QCOMPARE(profile.level(1, 13), 2);
|
||||
QCOMPARE(profile.level(1, 9), 0);
|
||||
QCOMPARE(profile.level(2, 9), 2);
|
||||
|
||||
profile.setLevel(1, 13, 1);
|
||||
QCOMPARE(profile.level(1, 13), 1);
|
||||
}
|
||||
|
||||
void TestEnergy::rejectsInvalidCoordinates()
|
||||
{
|
||||
EnergyProfile profile = EnergyProfile::defaults();
|
||||
QVERIFY(!profile.setLevel(0, 9, 2));
|
||||
QVERIFY(!profile.setLevel(8, 9, 2));
|
||||
QVERIFY(!profile.setLevel(1, 24, 2));
|
||||
QCOMPARE(profile.level(1, 24), -1);
|
||||
QCOMPARE(profile.level(QDateTime()), -1);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
QDate testDate()
|
||||
{
|
||||
return QDate(2026, 1, 5);
|
||||
}
|
||||
|
||||
ScheduleItem item(int startHour, int endHour, const QString& status, const QString& title)
|
||||
{
|
||||
ScheduleItem result;
|
||||
result.task.title = title;
|
||||
result.task.energyReq = 1;
|
||||
result.block.startAt = QDateTime(testDate(), QTime(startHour, 0), Qt::LocalTime);
|
||||
result.block.endAt = QDateTime(testDate(), QTime(endHour, 0), Qt::LocalTime);
|
||||
result.block.status = status;
|
||||
return result;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void TestEnergy::findsGhostWindows()
|
||||
{
|
||||
const QVector<ScheduleItem> items = {
|
||||
item(9, 10, QStringLiteral("done"), QStringLiteral("A")),
|
||||
item(13, 14, QStringLiteral("scheduled"), QStringLiteral("B")),
|
||||
item(11, 12, QStringLiteral("dropped"), QStringLiteral("C")),
|
||||
};
|
||||
const auto windows = findFreeWindows(items,
|
||||
testDate(),
|
||||
QDateTime(testDate(), QTime(8, 0), Qt::LocalTime),
|
||||
8,
|
||||
22,
|
||||
30);
|
||||
QCOMPARE(windows.size(), 3);
|
||||
QCOMPARE(windows[0].minutes, 60);
|
||||
QCOMPARE(windows[0].start.time(), QTime(8, 0));
|
||||
QCOMPARE(windows[1].minutes, 180);
|
||||
QCOMPARE(windows[1].start.time(), QTime(10, 0));
|
||||
QCOMPARE(windows[2].minutes, 8 * 60);
|
||||
QCOMPARE(windows[2].start.time(), QTime(14, 0));
|
||||
}
|
||||
|
||||
void TestEnergy::buildsDailyReviewAndSuggestions()
|
||||
{
|
||||
const QVector<ScheduleItem> items = {
|
||||
item(9, 10, QStringLiteral("done"), QStringLiteral("完成")),
|
||||
item(13, 14, QStringLiteral("scheduled"), QStringLiteral("超时")),
|
||||
};
|
||||
const QDateTime now(testDate(), QTime(15, 0), Qt::LocalTime);
|
||||
const DailyReview review = buildDailyReview(items, testDate(), now);
|
||||
QCOMPARE(review.total, 2);
|
||||
QCOMPARE(review.done, 1);
|
||||
QCOMPARE(review.active, 1);
|
||||
QCOMPARE(review.overdue, 1);
|
||||
QCOMPARE(review.focusedMinutes, 60);
|
||||
QCOMPARE(review.completionPercent, 50);
|
||||
QVERIFY(!review.ghostWindows.isEmpty());
|
||||
|
||||
const auto suggestions = buildSuggestions(items, now, 3);
|
||||
QCOMPARE(suggestions.size(), 2);
|
||||
QCOMPARE(suggestions[0].kind, Suggestion::Kind::Overdue);
|
||||
QCOMPARE(suggestions[1].kind, Suggestion::Kind::GhostTime);
|
||||
|
||||
const auto evening = buildSuggestions(items,
|
||||
QDateTime(testDate(), QTime(19, 0), Qt::LocalTime),
|
||||
3);
|
||||
QCOMPARE(evening.size(), 3);
|
||||
QCOMPARE(evening[2].kind, Suggestion::Kind::Review);
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestEnergy)
|
||||
#include "test_energy.moc"
|
||||
@@ -47,6 +47,7 @@ class TestOpenAiProvider : public QObject
|
||||
|
||||
private slots:
|
||||
void streamsSseContent();
|
||||
void streamsLocalWithoutApiKey();
|
||||
void reportsHttpError();
|
||||
};
|
||||
|
||||
@@ -92,6 +93,45 @@ void TestOpenAiProvider::streamsSseContent()
|
||||
QCOMPARE(text, QStringLiteral("你好,世界"));
|
||||
}
|
||||
|
||||
void TestOpenAiProvider::streamsLocalWithoutApiKey()
|
||||
{
|
||||
FakeSseServer server;
|
||||
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
|
||||
server.response =
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/event-stream\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n"
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\"local\"}}]}\n\n"
|
||||
"data: [DONE]\n\n";
|
||||
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
|
||||
config.model = QStringLiteral("local-model");
|
||||
|
||||
QJsonArray messages;
|
||||
QJsonObject message;
|
||||
message.insert(QStringLiteral("role"), QStringLiteral("user"));
|
||||
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
|
||||
messages.append(message);
|
||||
|
||||
OpenAiProvider provider;
|
||||
QString text;
|
||||
QString error;
|
||||
bool finished = false;
|
||||
provider.streamCompletion(
|
||||
config,
|
||||
messages,
|
||||
{
|
||||
[&text](const QString& delta) { text += delta; },
|
||||
[&error](const QString& message) { error = message; },
|
||||
[&finished]() { finished = true; },
|
||||
});
|
||||
QTRY_VERIFY_WITH_TIMEOUT(finished, 5000);
|
||||
QCOMPARE(error, QString());
|
||||
QCOMPARE(text, QStringLiteral("local"));
|
||||
}
|
||||
|
||||
void TestOpenAiProvider::reportsHttpError()
|
||||
{
|
||||
FakeSseServer server;
|
||||
|
||||
@@ -57,6 +57,7 @@ private slots:
|
||||
void fallsBackWhenPreferredIsFull();
|
||||
void preferredWindowCanOverrideDefaultHours();
|
||||
void reportsFailureWhenNoRoom();
|
||||
void usesEnergyProfile();
|
||||
};
|
||||
|
||||
void TestScheduler::skipsBusyIntervals()
|
||||
@@ -157,5 +158,33 @@ void TestScheduler::reportsFailureWhenNoRoom()
|
||||
QCOMPARE(result.failures.size(), std::size_t(1));
|
||||
}
|
||||
|
||||
void TestScheduler::usesEnergyProfile()
|
||||
{
|
||||
scheduler::Options options;
|
||||
options.energyAt = [](SysTime value) {
|
||||
const int hour = static_cast<int>((value.time_since_epoch().count() / 3600) % 24);
|
||||
return hour < 14 ? 0 : 2;
|
||||
};
|
||||
|
||||
auto high = task(QStringLiteral("high").toStdString(), 60);
|
||||
high.energyRequired = 2;
|
||||
auto result = scheduler::schedule({high}, {}, workWindows(1), at(0, 8), at(0, 22), options);
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 14));
|
||||
QVERIFY(result.placements[0].end == at(0, 15));
|
||||
|
||||
auto medium = task(QStringLiteral("medium").toStdString(), 60);
|
||||
medium.energyRequired = 1;
|
||||
result = scheduler::schedule({medium}, {}, workWindows(1), at(0, 8), at(0, 22), options);
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 14));
|
||||
|
||||
auto strictHigh = task(QStringLiteral("strict-high").toStdString(), 60);
|
||||
strictHigh.energyRequired = 2;
|
||||
result = scheduler::schedule({strictHigh}, {}, workWindows(1), at(0, 8), at(0, 13), options);
|
||||
QVERIFY(result.placements.empty());
|
||||
QCOMPARE(result.failures.size(), std::size_t(1));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestScheduler)
|
||||
#include "test_scheduler.moc"
|
||||
|
||||
@@ -25,6 +25,7 @@ private slots:
|
||||
void overdueAndNotificationDedup();
|
||||
void invalidRangeRejected();
|
||||
void applyProposedCreatesOnlySelected();
|
||||
void energyProfileLearnsFromHistory();
|
||||
};
|
||||
|
||||
namespace
|
||||
@@ -313,5 +314,53 @@ void TestServices::applyProposedCreatesOnlySelected()
|
||||
QVERIFY(!context.service->applyProposedCreates(diff, {}, &error));
|
||||
}
|
||||
|
||||
void TestServices::energyProfileLearnsFromHistory()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDate date = QDate::currentDate();
|
||||
QJsonObject task;
|
||||
task.insert(QStringLiteral("title"), QStringLiteral("高精力任务"));
|
||||
task.insert(QStringLiteral("priority"), 2);
|
||||
task.insert(QStringLiteral("energy_req"), 2);
|
||||
QJsonObject block;
|
||||
block.insert(QStringLiteral("start_at"),
|
||||
DateTimeUtils::toDb(QDateTime(date, QTime(13, 0), Qt::LocalTime)));
|
||||
block.insert(QStringLiteral("end_at"),
|
||||
DateTimeUtils::toDb(QDateTime(date, QTime(14, 0), Qt::LocalTime)));
|
||||
QJsonObject create;
|
||||
create.insert(QStringLiteral("temp_id"), QStringLiteral("energy"));
|
||||
create.insert(QStringLiteral("task"), task);
|
||||
create.insert(QStringLiteral("block"), block);
|
||||
ProposedDiff diff;
|
||||
diff.id = QStringLiteral("energy-diff");
|
||||
diff.createdAt = DateTimeUtils::toDb(QDateTime::currentDateTimeUtc());
|
||||
diff.state = QStringLiteral("pending");
|
||||
diff.payload = QJsonObject{
|
||||
{QStringLiteral("creates"), QJsonArray{create}},
|
||||
{QStringLiteral("updates"), QJsonArray{}},
|
||||
{QStringLiteral("deletes"), QJsonArray{}},
|
||||
};
|
||||
|
||||
QString error;
|
||||
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("energy")}, &error),
|
||||
qPrintable(error));
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(date);
|
||||
QCOMPARE(items.size(), 1);
|
||||
const QString blockId = items.first().block.id;
|
||||
|
||||
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 0);
|
||||
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("done"), &error), qPrintable(error));
|
||||
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 2);
|
||||
QVERIFY(context.service->dailyReview(date).energySummary.contains(QStringLiteral("13:00–14:00")));
|
||||
|
||||
ScheduleService reloaded(*context.store, QStringLiteral("test-device"));
|
||||
QCOMPARE(reloaded.energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 2);
|
||||
|
||||
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("scheduled"), &error), qPrintable(error));
|
||||
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 0);
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestServices)
|
||||
#include "test_services.moc"
|
||||
|
||||
Reference in New Issue
Block a user