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 /** * 单文件 SQLite,不引 Room。 * * 自用应用只有三张表、查询都在主线程几毫秒内完成,Room 的注解处理器会额外 * 拉进 ksp/kapt 一条编译链,在这台只能单线程构建的机器上不划算。 */ object Store { const val INBOX_ID = 1L private const val DB_NAME = "focusbox.db" private const val DB_VERSION = 7 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, sort_index INTEGER NOT NULL DEFAULT 0, pinned_at 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, origin_id INTEGER NOT NULL DEFAULT 0, log_seconds INTEGER NOT NULL DEFAULT 0, urgency 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") } // v2 → v3:记录重复任务的来源,取消完成时能精确删掉自动生成的新一条 if (oldVersion < 3) { db.execSQL("ALTER TABLE tasks ADD COLUMN origin_id INTEGER NOT NULL DEFAULT 0") } // v3 → v4:早期版本的原因备注带【】方括号,一次性清掉历史数据 if (oldVersion < 4) { db.execSQL( "UPDATE tasks SET note = REPLACE(REPLACE(note, '【', ''), '】', '') " + "WHERE note LIKE '%【%' OR note LIKE '%】%'" ) } // v4 → v5:每次专注单独成条完成记录,存本轮秒数以显示真实起止 if (oldVersion < 5) { db.execSQL("ALTER TABLE tasks ADD COLUMN log_seconds INTEGER NOT NULL DEFAULT 0") } // v5 → v6:紧急度(0 不急 / 1 中 / 2 紧急),旧任务统一归为中 if (oldVersion < 6) { db.execSQL("ALTER TABLE tasks ADD COLUMN urgency INTEGER NOT NULL DEFAULT 1") } // v6 → v7:项目排序模式——序号(非置顶按序号升序)+ 置顶时间(置顶排最前,越近越靠前) if (oldVersion < 7) { db.execSQL("ALTER TABLE projects ADD COLUMN sort_index INTEGER NOT NULL DEFAULT 0") db.execSQL("ALTER TABLE projects ADD COLUMN pinned_at INTEGER NOT NULL DEFAULT 0") } } } // ---------------------------------------------------------------- 项目 fun projects(includeArchived: Boolean = false): List { val sql = """ SELECT p._id, p.name, p.color, p.archived, p.sort, p.sort_index, p.pinned_at, (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, CASE WHEN p.pinned_at > 0 THEN 1 ELSE 0 END DESC, CASE WHEN p.pinned_at > 0 THEN p.pinned_at ELSE 0 END DESC, p.sort_index 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), sortIndex = c.getInt(5), pinnedAt = c.getLong(6), openTasks = c.getInt(7), doneTasks = c.getInt(8), focusSeconds = c.getInt(9), pomodoros = c.getInt(10), ) ) } } return list } fun project(id: Long): Project? = projects(true).firstOrNull { it.id == id } fun addProject(name: String, color: Int, sortIndex: Int = 0, pinned: Boolean = false): Long { val now = System.currentTimeMillis() val cv = ContentValues().apply { put("name", name) put("color", color) put("archived", 0) put("sort", now / 1000) put("sort_index", sortIndex) put("pinned_at", if (pinned) now else 0L) put("created_at", now) } return db.insert("projects", null, cv) } /** * pinnedAt 语义:pinned=true 且原值 0 → 取传入值(新建置顶时由调用方给 now); * 已置顶保持置顶 → 保留原置顶时间(重复保存不刷新排序);取消置顶 → 归 0。 */ fun updateProject( id: Long, name: String, color: Int, archived: Boolean, sortIndex: Int = 0, pinned: Boolean = false, pinnedAt: Long = 0, ) { val cv = ContentValues().apply { put("name", name) put("color", color) put("archived", if (archived) 1 else 0) put("sort_index", sortIndex) put("pinned_at", if (pinned) pinnedAt else 0L) } 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), originId = c.getLong(14), logSeconds = c.getInt(15), urgency = c.getInt(16), ) private val taskColumns = "_id, title, note, project_id, priority, focus_min, done_pomodoros, due, done, done_at, " + "created_at, sort, repeat_type, repeat_every, origin_id, log_seconds, urgency" 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") // 已完成的按完成时间倒序(最近做完的排前面)。未完成分组依次是: // ①「随时」置顶(repeat_type=4)②已逾期(有截止日且早于今天 0 点) // ③其余按截止日升序/优先级——逾期只提升位置,不改变组内原有顺序 val todayStart = com.focusbox.app.util.Dates.todayStart() 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 done = 0 AND repeat_type = ${Repeat.ANYTIME} THEN 0 ELSE 1 END ASC, " + "CASE WHEN done = 0 AND due > 0 AND due < $todayStart THEN 0 ELSE 1 END ASC, " + "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, urgency: Int = 1, ): Long { val cv = ContentValues().apply { put("title", title) put("note", note) put("project_id", projectId) put("priority", priority) put("urgency", urgency.coerceIn(0, 2)) 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("urgency", task.urgency.coerceIn(0, 2)) 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())) } /** * 勾选完成只标记当前这一次,不再立刻生成下一条。 * 新实例由 [rollRepeatingTasks] 按周期(跨零点)自动创建, * 因此原因备注只留在已完成的那一条上,不会污染后续周期。 */ fun setTaskDone(id: Long, done: Boolean) { val t = task(id) ?: return if (done == t.done) return val now = System.currentTimeMillis() db.update( "tasks", ContentValues().apply { put("done", if (done) 1 else 0) put("done_at", if (done) now else 0L) }, "_id = ?", arrayOf(id.toString()) ) } /** * 已被"提前完成"关闭的源任务 id 集合。 * * 提前完成 = 源任务标记已完成 + 一条带备注的独立完成记录(origin_id 指回源任务), * 列表里只应显示带备注的记录那条;完成记录的特征是 repeat_type = 0 * (重复任务实例虽然也有 origin_id,但 repeat_type > 0,不会误伤)。 */ fun completedSourceIds(): Set { val ids = HashSet() db.rawQuery( "SELECT DISTINCT origin_id FROM tasks WHERE done = 1 AND origin_id > 0 AND repeat_type = 0", null, ).use { c -> while (c.moveToNext()) ids.add(c.getLong(0)) } return ids } /** * 一次专注结束 = 一条独立的完成任务记录。 * * 每次点「完成」都新建一条已完成的任务副本,备注只属于这一次, * 不再往源任务的备注里累加;源任务保持待办,可以继续下一轮。 * origin_id 指回源任务(仅用于取这次专注的起止时刻),repeat_type 清零, * 这样完成记录不会被重复任务滚动逻辑当成新周期实例。 */ fun addCompletionRecord( sourceId: Long, note: String, startAt: Long, endAt: Long, seconds: Int, ): Long { val source = if (sourceId > 0) task(sourceId) else null val cv = ContentValues().apply { put("title", source?.title ?: "未关联任务") put("note", note) put("project_id", source?.projectId ?: INBOX_ID) put("priority", source?.priority ?: 1) put("urgency", source?.urgency?.coerceIn(0, 2) ?: 1) put("focus_min", source?.focusMinutes ?: 25) put("est_pomodoros", 1) put("done_pomodoros", 1) put("due", source?.due ?: 0L) put("done", 1) put("done_at", endAt) put("created_at", if (startAt > 0) startAt else endAt) put("sort", 0) put("repeat_type", Repeat.NONE) put("repeat_every", 1) put("origin_id", sourceId) put("log_seconds", seconds) } return db.insert("tasks", null, cv) } /** 为重复系列生成一条全新实例:备注永远从空开始 */ private fun createSeriesInstance(rootId: Long, source: Task, due: Long): Long { val id = addTask( title = source.title, note = "", projectId = source.projectId, priority = source.priority, focusMinutes = source.focusMinutes, due = due, repeatType = source.repeatType, repeatEvery = source.repeatEvery, urgency = source.urgency, ) if (id > 0) { db.update( "tasks", ContentValues().apply { put("origin_id", rootId) }, "_id = ?", arrayOf(id.toString()) ) } return id } /** 把日期按重复规则往后推一个周期 */ private fun shiftDue(from: Long, type: Int, every: Int): Long { val n = every.coerceAtLeast(1) return when (type) { Repeat.DAY -> Dates.addDays(from, n) Repeat.WEEK -> Dates.addDays(from, n * 7) Repeat.MONTH -> Dates.addMonths(from, n) else -> from } } /** * 重复任务按周期自动生成新实例。 * * 每个系列(根任务 origin_id=0,后续实例 origin_id=根 id)只保留"最新一条"作为节奏来源: * 当它的截止日已经过去,就创建一条全新的当日/本周期任务,旧任务原样留在列表里, * 这样完成原因只写在已完成的那一条上,循环任务本身不会越记越脏。 * * 启动、回前台、以及前台每 60 秒都会调用;跨零点后第一次调用即可生成当日任务。 * 幂等:最新一条的截止日不早于今天时不做任何事,重复调用无副作用。 */ fun rollRepeatingTasks(): Int { val today = Dates.todayStart() val all = ArrayList() db.rawQuery( // 只滚真正的周期重复(1-3);「随时」(4) 与不重复 (0) 不参与 "SELECT $taskColumns FROM tasks WHERE repeat_type IN (1, 2, 3) AND repeat_every > 0", null, ).use { c -> while (c.moveToNext()) all.add(cursorToTask(c)) } var changed = 0 val roots = all.map { if (it.originId > 0) it.originId else it.id }.distinct() for (root in roots) { val series = all.filter { if (it.originId > 0) it.originId == root else it.id == root } val latest = series.maxWith(compareBy { it.due }.thenBy { it.id }) if (latest.due >= today) continue val due = if (latest.due <= 0) { // 没设截止日的重复任务没有节奏可循,直接用今天作为新实例起点 today } else { var d = latest.due var guard = 0 while (d < today && guard < 500) { d = shiftDue(d, latest.repeatType, latest.repeatEvery) guard++ } d } if (due <= latest.due) continue if (createSeriesInstance(root, latest, due) > 0) changed++ } return changed } 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 } /** * 某一天的 24 小时分布。 * 统计页选"今日"时,按天的柱子只有一根、看不出节奏, * 换成小时粒度才能回答"今天是早上干的还是晚上干的"。 */ fun hourlySeries(dayStart: Long): List { val minutes = IntArray(24) val pomos = IntArray(24) db.rawQuery( """ SELECT CAST(strftime('%H', start_at / 1000, 'unixepoch', 'localtime') AS INTEGER) AS h, IFNULL(SUM(seconds),0), IFNULL(SUM(completed),0) FROM sessions WHERE start_at >= ? AND start_at < ? GROUP BY h """.trimIndent(), arrayOf(dayStart.toString(), Dates.addDays(dayStart, 1).toString()) ).use { c -> while (c.moveToNext()) { val h = c.getInt(0).coerceIn(0, 23) minutes[h] = c.getInt(1) / 60 pomos[h] = c.getInt(2) } } val out = ArrayList(24) for (h in 0 until 24) { out.add(DayPoint(key = "%02d".format(h), label = "$h", minutes = minutes[h], pomodoros = pomos[h])) } return out } /** * 按项目汇总的专注时长,区间是左闭右开 [fromMs, toMs)。 * 统计页的日/周/月/年四档都要能看历史区间,所以必须带上界; * 只给下界的话「11月26日」会一路把 26 号之后的记录也算进来。 */ fun distribution(fromMs: Long, toMs: 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 >= ? AND s.start_at < ? GROUP BY s.project_id HAVING SUM(s.seconds) > 0 ORDER BY 4 DESC """.trimIndent(), arrayOf(fromMs.toString(), toMs.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 } /** 按任务汇总的专注时长,区间同样是 [fromMs, toMs) */ fun taskSlices(fromMs: Long, toMs: 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 >= ? AND s.start_at < ? GROUP BY s.task_id HAVING SUM(s.seconds) > 0 ORDER BY 4 DESC """.trimIndent(), arrayOf(fromMs.toString(), toMs.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, s.seconds 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), c.getInt(3)) } } 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 } } fun clearAll() { db.delete("sessions", null, null) db.delete("tasks", null, null) db.delete("projects", null, null) // 不清自增序列的话,清空后第一个项目 id 会继续往上跑,永远不再是收件箱的 1 db.delete("sqlite_sequence", "name IN (?,?,?)", arrayOf("projects", "tasks", "sessions")) db.execSQL( "INSERT INTO projects (name, color, archived, sort, created_at) VALUES (?,?,?,?,?)", arrayOf("收件箱", 0xFF7A756C.toInt(), 0, 0, System.currentTimeMillis()) ) } }