diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f6ee25..83afedc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,5 @@ # 变更记录 -## 2026-11-28 · 同步插件源代码 - -- 同步源码更新 1 个文件(新增/修改 0,删除 1)。 - ## 2026-11-27 · v0.2.0(versionCode 2):交互重构、重复任务、任务分布 首版反馈的集中修订。数据库 v1 → v2 自动迁移,旧数据保留。 diff --git a/src/main/java/com/focusbox/app/data/Store.kt b/src/main/java/com/focusbox/app/data/Store.kt new file mode 100644 index 0000000..9c44227 --- /dev/null +++ b/src/main/java/com/focusbox/app/data/Store.kt @@ -0,0 +1,531 @@ +package com.focusbox.app.data + +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.database.sqlite.SQLiteDatabase +import android.database.sqlite.SQLiteOpenHelper +import com.focusbox.app.model.DayPoint +import com.focusbox.app.model.Project +import com.focusbox.app.model.ProjectSlice +import com.focusbox.app.model.Repeat +import com.focusbox.app.model.SessionSpan +import com.focusbox.app.model.Task +import com.focusbox.app.model.TodayStat +import com.focusbox.app.model.Totals +import com.focusbox.app.util.Dates +import java.util.Calendar + +/** + * 单文件 SQLite,不引 Room。 + * + * 自用应用只有三张表、查询都在主线程几毫秒内完成,Room 的注解处理器会额外 + * 拉进 ksp/kapt 一条编译链,在这台只能单线程构建的机器上不划算。 + */ +object Store { + + const val INBOX_ID = 1L + + private const val DB_NAME = "focusbox.db" + private const val DB_VERSION = 2 + + private lateinit var helper: Helper + + fun init(context: Context) { + helper = Helper(context.applicationContext) + } + + private val db: SQLiteDatabase get() = helper.writableDatabase + + private class Helper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { + override fun onCreate(db: SQLiteDatabase) { + db.execSQL( + """ + CREATE TABLE projects ( + _id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + color INTEGER NOT NULL, + archived INTEGER NOT NULL DEFAULT 0, + sort INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ) + """.trimIndent() + ) + db.execSQL( + """ + CREATE TABLE tasks ( + _id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + note TEXT NOT NULL DEFAULT '', + project_id INTEGER NOT NULL DEFAULT 1, + priority INTEGER NOT NULL DEFAULT 1, + est_pomodoros INTEGER NOT NULL DEFAULT 1, + done_pomodoros INTEGER NOT NULL DEFAULT 0, + due INTEGER NOT NULL DEFAULT 0, + done INTEGER NOT NULL DEFAULT 0, + done_at INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + sort INTEGER NOT NULL DEFAULT 0, + focus_min INTEGER NOT NULL DEFAULT 25, + repeat_type INTEGER NOT NULL DEFAULT 0, + repeat_every INTEGER NOT NULL DEFAULT 1 + ) + """.trimIndent() + ) + db.execSQL( + """ + CREATE TABLE sessions ( + _id INTEGER PRIMARY KEY AUTOINCREMENT, + task_id INTEGER NOT NULL DEFAULT 0, + project_id INTEGER NOT NULL DEFAULT 0, + start_at INTEGER NOT NULL, + end_at INTEGER NOT NULL, + seconds INTEGER NOT NULL, + completed INTEGER NOT NULL DEFAULT 1 + ) + """.trimIndent() + ) + db.execSQL("CREATE INDEX idx_sessions_start ON sessions(start_at)") + db.execSQL("CREATE INDEX idx_tasks_project ON tasks(project_id, done)") + + val now = System.currentTimeMillis() + db.execSQL( + "INSERT INTO projects (name, color, archived, sort, created_at) VALUES (?,?,?,?,?)", + arrayOf("收件箱", 0xFF7A756C.toInt(), 0, 0, now) + ) + } + + override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + // v1 → v2:任务从"预估番茄数"改为"单轮专注分钟",并加上重复规则。 + // 旧值按 1 番茄 = 25 分钟换算,保证升级后时长不丢。 + if (oldVersion < 2) { + db.execSQL("ALTER TABLE tasks ADD COLUMN focus_min INTEGER NOT NULL DEFAULT 25") + db.execSQL("ALTER TABLE tasks ADD COLUMN repeat_type INTEGER NOT NULL DEFAULT 0") + db.execSQL("ALTER TABLE tasks ADD COLUMN repeat_every INTEGER NOT NULL DEFAULT 1") + db.execSQL("UPDATE tasks SET focus_min = est_pomodoros * 25 WHERE est_pomodoros > 0") + } + } + } + + // ---------------------------------------------------------------- 项目 + + fun projects(includeArchived: Boolean = false): List { + val sql = """ + SELECT p._id, p.name, p.color, p.archived, p.sort, + (SELECT COUNT(*) FROM tasks t WHERE t.project_id = p._id AND t.done = 0) AS open_tasks, + (SELECT COUNT(*) FROM tasks t WHERE t.project_id = p._id AND t.done = 1) AS done_tasks, + (SELECT IFNULL(SUM(s.seconds), 0) FROM sessions s WHERE s.project_id = p._id) AS focus_sec, + (SELECT COUNT(*) FROM sessions s WHERE s.project_id = p._id AND s.completed = 1) AS pomos + FROM projects p + WHERE p.archived = 0 OR ${if (includeArchived) 1 else 0} = 1 + ORDER BY p.archived ASC, p.sort ASC, p._id ASC + """.trimIndent() + val list = ArrayList() + db.rawQuery(sql, null).use { c -> + while (c.moveToNext()) { + list.add( + Project( + id = c.getLong(0), + name = c.getString(1), + color = c.getInt(2), + archived = c.getInt(3) == 1, + sort = c.getInt(4), + openTasks = c.getInt(5), + doneTasks = c.getInt(6), + focusSeconds = c.getInt(7), + pomodoros = c.getInt(8), + ) + ) + } + } + return list + } + + fun project(id: Long): Project? = projects(true).firstOrNull { it.id == id } + + fun addProject(name: String, color: Int): Long { + val cv = ContentValues().apply { + put("name", name) + put("color", color) + put("archived", 0) + put("sort", System.currentTimeMillis() / 1000) + put("created_at", System.currentTimeMillis()) + } + return db.insert("projects", null, cv) + } + + fun updateProject(id: Long, name: String, color: Int, archived: Boolean) { + val cv = ContentValues().apply { + put("name", name) + put("color", color) + put("archived", if (archived) 1 else 0) + } + db.update("projects", cv, "_id = ?", arrayOf(id.toString())) + } + + /** 项目删除后任务不删,统一落到收件箱,避免历史专注记录失去归属。 */ + fun deleteProject(id: Long) { + if (id == INBOX_ID) return + db.update("tasks", ContentValues().apply { put("project_id", INBOX_ID) }, "project_id = ?", arrayOf(id.toString())) + db.delete("projects", "_id = ?", arrayOf(id.toString())) + } + + // ---------------------------------------------------------------- 任务 + + private fun cursorToTask(c: Cursor) = Task( + id = c.getLong(0), + title = c.getString(1), + note = c.getString(2), + projectId = c.getLong(3), + priority = c.getInt(4), + focusMinutes = c.getInt(5), + donePomodoros = c.getInt(6), + due = c.getLong(7), + done = c.getInt(8) == 1, + doneAt = c.getLong(9), + createdAt = c.getLong(10), + sort = c.getInt(11), + repeatType = c.getInt(12), + repeatEvery = c.getInt(13), + ) + + private val taskColumns = + "_id, title, note, project_id, priority, focus_min, done_pomodoros, due, done, done_at, " + + "created_at, sort, repeat_type, repeat_every" + + fun tasks(projectId: Long = 0L, includeDone: Boolean = true): List { + val where = StringBuilder("1 = 1") + val args = ArrayList() + if (projectId > 0) { + where.append(" AND project_id = ?") + args.add(projectId.toString()) + } + if (!includeDone) where.append(" AND done = 0") + // 已完成的按完成时间倒序(最近做完的排前面),未完成的按截止/优先级 + val sql = "SELECT $taskColumns FROM tasks WHERE $where " + + "ORDER BY done ASC, CASE WHEN done = 1 THEN done_at ELSE 0 END DESC, " + + "CASE WHEN due = 0 THEN 1 ELSE 0 END ASC, due ASC, priority DESC, _id DESC" + val list = ArrayList() + db.rawQuery(sql, args.toTypedArray()).use { c -> + while (c.moveToNext()) list.add(cursorToTask(c)) + } + return list + } + + fun task(id: Long): Task? { + db.rawQuery("SELECT $taskColumns FROM tasks WHERE _id = ?", arrayOf(id.toString())).use { c -> + return if (c.moveToFirst()) cursorToTask(c) else null + } + } + + fun addTask( + title: String, + note: String, + projectId: Long, + priority: Int, + focusMinutes: Int, + due: Long, + repeatType: Int, + repeatEvery: Int, + ): Long { + val cv = ContentValues().apply { + put("title", title) + put("note", note) + put("project_id", projectId) + put("priority", priority) + put("focus_min", focusMinutes) + put("est_pomodoros", (focusMinutes / 25).coerceAtLeast(1)) + put("done_pomodoros", 0) + put("due", due) + put("done", 0) + put("done_at", 0) + put("created_at", System.currentTimeMillis()) + put("sort", 0) + put("repeat_type", repeatType) + put("repeat_every", repeatEvery.coerceAtLeast(1)) + } + return db.insert("tasks", null, cv) + } + + fun updateTask(task: Task) { + val cv = ContentValues().apply { + put("title", task.title) + put("note", task.note) + put("project_id", task.projectId) + put("priority", task.priority) + put("focus_min", task.focusMinutes) + put("est_pomodoros", (task.focusMinutes / 25).coerceAtLeast(1)) + put("due", task.due) + put("repeat_type", task.repeatType) + put("repeat_every", task.repeatEvery.coerceAtLeast(1)) + } + db.update("tasks", cv, "_id = ?", arrayOf(task.id.toString())) + } + + /** + * 勾选完成时,重复任务会立刻生成下一周期的一条新任务。 + * 这里只做"生成",不改动当前任务的统计归属。 + */ + fun setTaskDone(id: Long, done: Boolean) { + if (!done) { + db.update( + "tasks", + ContentValues().apply { + put("done", 0) + put("done_at", 0) + }, + "_id = ?", arrayOf(id.toString()) + ) + return + } + val t = task(id) ?: return + if (t.done) return + val now = System.currentTimeMillis() + db.update( + "tasks", + ContentValues().apply { + put("done", 1) + put("done_at", now) + }, + "_id = ?", arrayOf(id.toString()) + ) + if (t.repeating) createNextOccurrence(t) + } + + private fun createNextOccurrence(t: Task) { + val base = if (t.due > 0) t.due else Dates.todayStart() + val n = t.repeatEvery.coerceAtLeast(1) + val next = when (t.repeatType) { + Repeat.DAY -> Dates.addDays(base, n) + Repeat.WEEK -> Dates.addDays(base, n * 7) + Repeat.MONTH -> Dates.addMonths(base, n) + else -> return + } + // 下一次的截止日至少比今天晚一天,否则刚生成就会显示"已逾期" + val due = if (next <= Dates.todayStart()) Dates.addDays(Dates.todayStart(), 1) else next + addTask( + title = t.title, + note = t.note, + projectId = t.projectId, + priority = t.priority, + focusMinutes = t.focusMinutes, + due = due, + repeatType = t.repeatType, + repeatEvery = t.repeatEvery, + ) + } + + fun deleteTask(id: Long) { + db.delete("tasks", "_id = ?", arrayOf(id.toString())) + db.update("sessions", ContentValues().apply { put("task_id", 0) }, "task_id = ?", arrayOf(id.toString())) + } + + fun incrementTaskPomodoro(id: Long) { + db.execSQL("UPDATE tasks SET done_pomodoros = done_pomodoros + 1 WHERE _id = ?", arrayOf(id)) + } + + // ---------------------------------------------------------------- 专注记录 + + fun addSession(taskId: Long, projectId: Long, startAt: Long, endAt: Long, seconds: Int, completed: Boolean) { + val pid = if (projectId > 0) projectId else if (taskId > 0) task(taskId)?.projectId ?: INBOX_ID else INBOX_ID + val cv = ContentValues().apply { + put("task_id", taskId) + put("project_id", pid) + put("start_at", startAt) + put("end_at", endAt) + put("seconds", seconds) + put("completed", if (completed) 1 else 0) + } + db.insert("sessions", null, cv) + if (completed && taskId > 0) incrementTaskPomodoro(taskId) + } + + fun todayStat(goalMinutes: Int): TodayStat { + val from = Dates.todayStart() + db.rawQuery( + "SELECT IFNULL(SUM(seconds),0), IFNULL(SUM(completed),0) FROM sessions WHERE start_at >= ?", + arrayOf(from.toString()) + ).use { c -> + if (c.moveToFirst()) { + val doneTasks = countScalar( + "SELECT COUNT(*) FROM tasks WHERE done = 1 AND done_at >= ?", + arrayOf(from.toString()) + ) + return TodayStat( + minutes = c.getInt(0) / 60, + pomodoros = c.getInt(1), + doneTasks = doneTasks, + goalMinutes = goalMinutes, + ) + } + } + return TodayStat(goalMinutes = goalMinutes) + } + + /** 从某天起的每日序列,缺失日期补 0,图表不能留下空洞 */ + fun dailySeries(fromDayStart: Long, days: Int): List { + val totals = HashMap>() + db.rawQuery( + """ + SELECT strftime('%Y-%m-%d', start_at / 1000, 'unixepoch', 'localtime') AS d, + IFNULL(SUM(seconds),0), IFNULL(SUM(completed),0) + FROM sessions WHERE start_at >= ? GROUP BY d + """.trimIndent(), + arrayOf(fromDayStart.toString()) + ).use { c -> + while (c.moveToNext()) totals[c.getString(0)] = c.getInt(1) to c.getInt(2) + } + val out = ArrayList(days) + for (i in 0 until days) { + val ms = Dates.addDays(fromDayStart, i) + val key = Dates.dayKey(ms) + val (sec, pomo) = totals[key] ?: (0 to 0) + out.add(DayPoint(key = key, label = Dates.md(ms), minutes = sec / 60, pomodoros = pomo)) + } + return out + } + + fun distribution(fromMs: Long): List { + val list = ArrayList() + db.rawQuery( + """ + SELECT COALESCE(p._id, 0), COALESCE(p.name, '未归类'), COALESCE(p.color, -1), + IFNULL(SUM(s.seconds),0), IFNULL(SUM(CASE WHEN s.completed = 1 THEN 1 ELSE 0 END),0) + FROM sessions s LEFT JOIN projects p ON p._id = s.project_id + WHERE s.start_at >= ? + GROUP BY s.project_id HAVING SUM(s.seconds) > 0 + ORDER BY 4 DESC + """.trimIndent(), + arrayOf(fromMs.toString()) + ).use { c -> + while (c.moveToNext()) { + list.add( + ProjectSlice( + projectId = c.getLong(0), + name = c.getString(1), + color = c.getInt(2), + seconds = c.getInt(3), + pomodoros = c.getInt(4), + ) + ) + } + } + return list + } + + /** 按任务汇总的专注时长,用于统计页的"任务分布" */ + fun taskSlices(fromMs: Long): List { + val list = ArrayList() + db.rawQuery( + """ + SELECT COALESCE(t._id, 0), COALESCE(t.title, '未关联任务'), COALESCE(p.color, -1), + IFNULL(SUM(s.seconds),0), COUNT(*) + FROM sessions s + LEFT JOIN tasks t ON t._id = s.task_id + LEFT JOIN projects p ON p._id = t.project_id + WHERE s.start_at >= ? + GROUP BY s.task_id HAVING SUM(s.seconds) > 0 + ORDER BY 4 DESC + """.trimIndent(), + arrayOf(fromMs.toString()) + ).use { c -> + while (c.moveToNext()) { + list.add( + ProjectSlice( + projectId = c.getLong(0), + name = c.getString(1), + color = c.getInt(2), + seconds = c.getInt(3), + pomodoros = c.getInt(4), + ) + ) + } + } + return list + } + + /** + * 每个任务最近一条专注记录的起止时刻。 + * 已完成任务要显示"09:12:03-09:37:03",数据只能来自 sessions, + * 一次性取回比在列表里逐行查库更省。 + */ + fun lastSessions(): HashMap { + val map = HashMap() + db.rawQuery( + """ + SELECT s.task_id, s.start_at, s.end_at FROM sessions s + JOIN ( + SELECT task_id, MAX(end_at) AS max_end FROM sessions + WHERE task_id > 0 GROUP BY task_id + ) m ON m.task_id = s.task_id AND m.max_end = s.end_at + """.trimIndent(), + null + ).use { c -> + while (c.moveToNext()) { + val id = c.getLong(0) + if (!map.containsKey(id)) map[id] = SessionSpan(c.getLong(1), c.getLong(2)) + } + } + return map + } + + fun totals(): Totals { + val seconds = countScalar("SELECT IFNULL(SUM(seconds),0) FROM sessions", null) + val pomos = countScalar("SELECT COUNT(*) FROM sessions WHERE completed = 1", null) + val doneTasks = countScalar("SELECT COUNT(*) FROM tasks WHERE done = 1", null) + return Totals(seconds = seconds, pomodoros = pomos, doneTasks = doneTasks, streak = streak()) + } + + /** + * 连续打卡:以"有专注记录的自然日"为单位。 + * 今天还没开始练不算断,从昨天往前数;昨天也没练则连续为 0。 + */ + fun streak(): Int { + val days = HashSet() + db.rawQuery( + """ + SELECT DISTINCT strftime('%Y-%m-%d', start_at / 1000, 'unixepoch', 'localtime') + FROM sessions WHERE seconds >= 60 ORDER BY 1 DESC LIMIT 400 + """.trimIndent(), + null + ).use { c -> + while (c.moveToNext()) days.add(c.getString(0)) + } + if (days.isEmpty()) return 0 + var cursor = Dates.todayStart() + if (!days.contains(Dates.dayKey(cursor))) { + cursor = Dates.addDays(cursor, -1) + if (!days.contains(Dates.dayKey(cursor))) return 0 + } + var n = 0 + while (days.contains(Dates.dayKey(cursor))) { + n++ + cursor = Dates.addDays(cursor, -1) + } + return n + } + + private fun countScalar(sql: String, args: Array?): Int { + db.rawQuery(sql, args).use { c -> + return if (c.moveToFirst()) c.getInt(0) else 0 + } + } + + /** 本月起点的毫秒值(一号 00:00) */ + fun monthStart(): Long { + val c = Calendar.getInstance() + c.timeInMillis = Dates.todayStart() + c.set(Calendar.DAY_OF_MONTH, 1) + return c.timeInMillis + } + + fun clearAll() { + db.delete("sessions", null, null) + db.delete("tasks", null, null) + db.delete("projects", null, null) + db.execSQL( + "INSERT INTO projects (name, color, archived, sort, created_at) VALUES (?,?,?,?,?)", + arrayOf("收件箱", 0xFF7A756C.toInt(), 0, 0, System.currentTimeMillis()) + ) + } +}