From 49fd19bbf4e7ca248b99077a886f1973ca5becc2 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 13:16:22 +0300 Subject: [PATCH 01/43] Give each settings page's rows a file of their own SettingsScreen.kt had grown to 1374 lines: the section enum, the two screens, and the rows of five pages with every label helper they use. A reader looking for the text-size picker had to scroll past the haptics, the sync interval and the sign-out sheet to find it, and a change to one page showed up in the history of all of them. The rows now sit beside the ones that already had a file, in the same `*Rows.kt` shape as ClassRows, NotificationRows and UpdateRows: AppearanceRows, FeelRows (with the edge-fade row the first run shares), ContentRows, SyncRows and AboutRows, plus SettingsSection for the enum the shell titles its pages from. SettingsScreen.kt keeps the two screens, the page shape, the group and the sheets only the section screen opens. Moved verbatim, comments included. The five row builders go from private to internal because the screen that calls them is now in another file; every label helper stays private to the file that uses it. Four imports that nothing in the old file used were not carried over. DebugReachTest read aboutRows out of SettingsScreen.kt by its declaration and now reads it from AboutRows.kt. It also asserts the declaration is there first: `substringAfter` returns the whole file when it is not, and the whole file could pass both of its checks. Refs #209 Co-Authored-By: Claude Opus 5.5 --- .../lessons/ui/settings/AboutRows.kt | 67 ++ .../lessons/ui/settings/AppearanceRows.kt | 183 ++++ .../lessons/ui/settings/ContentRows.kt | 171 ++++ .../lessons/ui/settings/FeelRows.kt | 246 +++++ .../lessons/ui/settings/SettingsScreen.kt | 910 +----------------- .../lessons/ui/settings/SettingsSection.kt | 170 ++++ .../lessons/ui/settings/SyncRows.kt | 111 +++ .../lessons/ui/debug/DebugReachTest.kt | 8 +- 8 files changed, 966 insertions(+), 900 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutRows.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AppearanceRows.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ContentRows.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/FeelRows.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSection.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SyncRows.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutRows.kt new file mode 100644 index 00000000..2a9eb1cf --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutRows.kt @@ -0,0 +1,67 @@ +package com.lumenpearson.lessons.ui.settings + +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import androidx.compose.material.icons.rounded.BugReport +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.GroupSwitchItem +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.debug.DebugRow + +internal fun LazyListScope.aboutRows( + state: SettingsUiState, + viewModel: SettingsViewModel, + onOpenDocs: () -> Unit, +) { + // First on the page, above the switch and the licences. The guide is the + // only row here somebody arrives *looking* for — everything else on this + // page is something you find — and a row you have to scroll to is a row a + // reader concludes does not exist. + item(key = "docs") { + SettingsGroup(title = correctedString(R.string.docs_group)) { + GroupLinkItem( + title = correctedString(R.string.docs_open), + subtitle = correctedString(R.string.docs_open_description), + icon = Icons.AutoMirrored.Rounded.MenuBook, + tone = accentTone(4), + onClick = onOpenDocs, + ) + } + } + item(key = "about") { + SettingsGroup(title = correctedString(R.string.settings_about_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_debug), + subtitle = correctedString(R.string.settings_debug_description), + icon = Icons.Rounded.BugReport, + tone = accentTone(2), + checked = state.settings.debugMode, + onCheckedChange = viewModel::setDebugMode, + ) + // Directly under the switch that writes them, and on the page + // everybody can reach. The reports used to be readable only from + // the two manager routes — the toolbar's bug button and the + // management page — while the switch was here, so a reader who was + // not an administrator could record a crash and never see it. + DebugRow( + enabled = state.settings.debugMode, + onEnabledChange = viewModel::setDebugMode, + ) + } + } + // The last thing on the last page, which is where an about block belongs and + // where Essentials puts its own. It carries the version, the description and + // the design credit, so the three rows that used to state those separately + // are gone rather than repeated above it. + item(key = "about_card") { + // No horizontal padding of its own. The list already insets every item + // by `ScreenPadding`, so this added a second one and the card came out + // 32 dp narrower on each side than every group above it — which is + // most of why its two link buttons were breaking «Essentials» into + // «Essent / ials». + AboutCard(serverStatus = state.serverStatus) + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AppearanceRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AppearanceRows.kt new file mode 100644 index 00000000..16e56620 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AppearanceRows.kt @@ -0,0 +1,183 @@ +package com.lumenpearson.lessons.ui.settings + +import android.os.Build +import androidx.annotation.StringRes +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Contrast +import androidx.compose.material.icons.rounded.DarkMode +import androidx.compose.material.icons.rounded.FormatSize +import androidx.compose.material.icons.rounded.Language +import androidx.compose.material.icons.rounded.Palette +import androidx.compose.material.icons.rounded.TextFields +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.designsystem.component.GroupSegmentedItem +import com.lumenpearson.lessons.core.designsystem.component.GroupSwitchItem +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.ThemeRevealAnchor +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.model.AppFont +import com.lumenpearson.lessons.core.model.AppLanguage +import com.lumenpearson.lessons.core.model.ThemeMode + +/** + * Typography lands here rather than in a section of its own. + * + * A third page called «Шрифт и движение» was the obvious move and the wrong one: + * it would have put the type on a page with the animation switches, which are + * the same decision as the ripple, the theme wipe and the two blurs — all of + * which live under «Взаимодействие». Splitting motion across two pages to keep + * the font company costs more than the font gains. So the face and its size go + * where everything else that repaints the whole app already is, and motion joins + * the effects it belongs with. + */ +internal fun LazyListScope.appearanceRows( + state: SettingsUiState, + viewModel: SettingsViewModel, +) { + item(key = "appearance") { + // Every row in this group repaints the whole app, so every row opens the + // circle from itself. The anchor is what makes the wavefront look like it + // came out from under the finger rather than from the middle of nowhere. + SettingsGroup(title = correctedString(R.string.settings_theme)) { + ThemeRevealAnchor { reveal -> + GroupSegmentedItem( + title = correctedString(R.string.settings_theme_mode), + icon = Icons.Rounded.Contrast, + tone = accentTone(4), + items = ThemeMode.entries, + selectedItem = state.settings.themeMode, + onItemSelected = { mode -> reveal { viewModel.setThemeMode(mode) } }, + labelProvider = { mode -> correctedString(mode.labelRes) }, + ) + } + ThemeRevealAnchor { reveal -> + GroupSwitchItem( + title = correctedString(R.string.settings_dynamic_color), + subtitle = if (SupportsDynamicColor) { + correctedString(R.string.settings_dynamic_color_description) + } else { + correctedString(R.string.settings_dynamic_color_unavailable) + }, + icon = Icons.Rounded.Palette, + tone = accentTone(0), + checked = state.settings.dynamicColor && SupportsDynamicColor, + enabled = SupportsDynamicColor, + onCheckedChange = { on -> reveal { viewModel.setDynamicColor(on) } }, + ) + } + ThemeRevealAnchor { reveal -> + GroupSwitchItem( + title = correctedString(R.string.settings_pitch_black), + subtitle = correctedString(R.string.settings_pitch_black_description), + icon = Icons.Rounded.DarkMode, + tone = accentTone(5), + checked = state.settings.pitchBlack, + onCheckedChange = { on -> reveal { viewModel.setPitchBlack(on) } }, + ) + } + } + } + + item(key = "typography") { + SettingsGroup(title = correctedString(R.string.settings_type_group)) { + GroupSegmentedItem( + title = correctedString(R.string.settings_font), + subtitle = correctedString(R.string.settings_font_description), + icon = Icons.Rounded.TextFields, + tone = accentTone(2), + items = AppFont.entries, + selectedItem = state.settings.appFont, + onItemSelected = viewModel::setAppFont, + labelProvider = { font -> correctedString(font.labelRes) }, + ) + // Four named steps rather than a slider: a size is something a + // person has to be able to put back, and "около одной целой семи" + // is not a place anybody can return to. The labels say what each + // step is for; the numbers behind them are in AppSettings. + GroupSegmentedItem( + title = correctedString(R.string.settings_text_size), + subtitle = correctedString(R.string.settings_text_size_description), + icon = Icons.Rounded.FormatSize, + tone = accentTone(4), + items = AppSettings.TEXT_SCALE_OPTIONS, + // Matched by value rather than by identity, and against the + // stored float rather than a remembered index: the store clamps + // what it reads, so a value from an older build lands on the + // nearest step instead of leaving every segment unselected. + selectedItem = nearestTextScale(state.settings.textScale), + onItemSelected = viewModel::setTextScale, + labelProvider = { scale -> correctedString(textScaleLabelRes(scale)) }, + ) + } + } + + // The language sits under the type rather than beside the theme: it is the + // other thing on this page that changes every word on every screen, and + // like the font it takes effect the moment it is tapped — below Android 13 + // by recreating the activity, above it by the system restarting it for us. + item(key = "language") { + SettingsGroup(title = correctedString(R.string.settings_language_group)) { + GroupSegmentedItem( + title = correctedString(R.string.settings_language), + subtitle = correctedString(R.string.settings_language_description), + icon = Icons.Rounded.Language, + tone = accentTone(1), + items = AppLanguage.entries, + selectedItem = state.settings.language, + onItemSelected = viewModel::setLanguage, + labelProvider = { language -> correctedString(language.labelRes) }, + ) + } + } +} + +/** Label of a language in the segmented picker. */ +private val AppLanguage.labelRes: Int + get() = when (this) { + AppLanguage.SYSTEM -> R.string.settings_language_system + AppLanguage.RUSSIAN -> R.string.settings_language_russian + AppLanguage.ENGLISH -> R.string.settings_language_english + } + +/** + * The offered step closest to [scale]. + * + * The picker has to have exactly one segment selected, and the stored value is + * a float that a previous build — or a clamp — may have left between two steps. + * Nearest is the only answer that never shows a picker with nothing chosen. + */ +private fun nearestTextScale(scale: Float): Float = + AppSettings.TEXT_SCALE_OPTIONS.minBy { kotlin.math.abs(it - scale) } + +/** Label of a text-size step; see `AppSettings.TEXT_SCALE_OPTIONS`. */ +@StringRes +private fun textScaleLabelRes(scale: Float): Int = when (scale) { + AppSettings.TEXT_SCALE_OPTIONS[0] -> R.string.settings_text_size_small + AppSettings.TEXT_SCALE_OPTIONS[2] -> R.string.settings_text_size_large + AppSettings.TEXT_SCALE_OPTIONS[3] -> R.string.settings_text_size_huge + else -> R.string.settings_text_size_normal +} + +/** Label of a typeface in the segmented picker. */ +private val AppFont.labelRes: Int + get() = when (this) { + AppFont.BUNDLED -> R.string.settings_font_bundled + AppFont.SYSTEM -> R.string.settings_font_system + } + +/** Label of a theme mode in the segmented picker. */ +internal val ThemeMode.labelRes: Int + get() = when (this) { + ThemeMode.SYSTEM -> R.string.settings_theme_system + ThemeMode.LIGHT -> R.string.settings_theme_light + ThemeMode.DARK -> R.string.settings_theme_dark + } + +/** + * Dynamic colour is a wallpaper-derived palette, which only exists from Android + * 12 on. Below that the row stays visible but disabled — hiding it would make + * the setting look like a bug on the phones that do have it. + */ +internal val SupportsDynamicColor: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ContentRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ContentRows.kt new file mode 100644 index 00000000..2f32ab9f --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ContentRows.kt @@ -0,0 +1,171 @@ +package com.lumenpearson.lessons.ui.settings + +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.EventNote +import androidx.compose.material.icons.rounded.CalendarViewWeek +import androidx.compose.material.icons.rounded.EditNote +import androidx.compose.material.icons.rounded.MoreHoriz +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material.icons.rounded.Reorder +import androidx.compose.material.icons.rounded.Timer +import androidx.compose.material.icons.rounded.ViewDay +import androidx.compose.material.icons.rounded.Weekend +import androidx.compose.material.icons.rounded.Widgets +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.designsystem.component.GroupSegmentedItem +import com.lumenpearson.lessons.core.designsystem.component.GroupSwitchItem +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.model.TodayLayout +import com.lumenpearson.lessons.core.model.WeekStart + +/** + * Three groups rather than one list of twelve rows. + * + * The first group is what every surface shares. The other two are one screen + * each, in the order the bottom bar draws them, so somebody who came here to + * change the home screen reads five titles about the home screen instead of + * twelve about everything. + */ +internal fun LazyListScope.contentRows( + state: SettingsUiState, + viewModel: SettingsViewModel, +) { + item(key = "content") { + SettingsGroup(title = correctedString(R.string.settings_content_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_show_teacher), + subtitle = correctedString(R.string.settings_show_teacher_description), + icon = Icons.Rounded.Person, + tone = accentTone(3), + checked = state.settings.showTeacher, + onCheckedChange = viewModel::setShowTeacher, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_widget_progress), + subtitle = correctedString(R.string.settings_widget_progress_description), + icon = Icons.Rounded.Widgets, + tone = accentTone(1), + checked = state.settings.widgetShowProgress, + onCheckedChange = viewModel::setWidgetShowProgress, + ) + } + } + + item(key = "content_home") { + SettingsGroup(title = correctedString(R.string.settings_home_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_today_hero), + subtitle = correctedString(R.string.settings_today_hero_description), + icon = Icons.Rounded.Timer, + tone = accentTone(0), + checked = state.settings.todayShowHero, + onCheckedChange = viewModel::setTodayShowHero, + ) + GroupSegmentedItem( + title = correctedString(R.string.settings_today_layout), + subtitle = correctedString(R.string.settings_today_layout_description), + icon = Icons.Rounded.Reorder, + tone = accentTone(2), + items = TodayLayout.entries, + selectedItem = state.settings.todayLayout, + onItemSelected = viewModel::setTodayLayout, + labelProvider = { layout -> correctedString(layout.labelRes) }, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_today_whole_day), + subtitle = correctedString(R.string.settings_today_whole_day_description), + icon = Icons.Rounded.ViewDay, + tone = accentTone(4), + checked = state.settings.todayWholeDay, + onCheckedChange = viewModel::setTodayWholeDay, + ) + GroupSegmentedItem( + title = correctedString(R.string.settings_today_homework_count), + subtitle = correctedString(R.string.settings_today_homework_count_description), + icon = Icons.Rounded.EditNote, + tone = accentTone(5), + items = AppSettings.HOMEWORK_PREVIEW_OPTIONS, + // No nearest-match here, unlike the text-size picker above: the + // store snaps this number to one of the three steps on the way + // in and on the way out, so what it hands over is always one of + // the segments. + selectedItem = state.settings.todayHomeworkPreview, + onItemSelected = viewModel::setTodayHomeworkPreview, + labelProvider = { count -> count.toString() }, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_today_events), + subtitle = correctedString(R.string.settings_today_events_description), + icon = Icons.AutoMirrored.Rounded.EventNote, + tone = accentTone(1), + checked = state.settings.todayShowEvents, + onCheckedChange = viewModel::setTodayShowEvents, + ) + } + } + + item(key = "content_calendar") { + SettingsGroup(title = correctedString(R.string.settings_calendar_group)) { + GroupSegmentedItem( + title = correctedString(R.string.settings_week_start), + subtitle = correctedString(R.string.settings_week_start_description), + icon = Icons.Rounded.CalendarViewWeek, + tone = accentTone(3), + items = WeekStart.entries, + selectedItem = state.settings.weekStart, + onItemSelected = viewModel::setWeekStart, + labelProvider = { start -> correctedString(start.labelRes) }, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_week_weekends), + subtitle = correctedString(R.string.settings_week_weekends_description), + icon = Icons.Rounded.Weekend, + tone = accentTone(0), + checked = state.settings.weekShowWeekends, + onCheckedChange = viewModel::setWeekShowWeekends, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_week_load), + subtitle = correctedString(R.string.settings_week_load_description), + icon = Icons.Rounded.MoreHoriz, + tone = accentTone(2), + checked = state.settings.weekShowLoad, + onCheckedChange = viewModel::setWeekShowLoad, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_week_events), + subtitle = correctedString(R.string.settings_week_events_description), + icon = Icons.AutoMirrored.Rounded.EventNote, + tone = accentTone(4), + checked = state.settings.weekShowEvents, + onCheckedChange = viewModel::setWeekShowEvents, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_week_homework), + subtitle = correctedString(R.string.settings_week_homework_description), + icon = Icons.Rounded.EditNote, + tone = accentTone(5), + checked = state.settings.weekShowHomework, + onCheckedChange = viewModel::setWeekShowHomework, + ) + } + } +} + +/** Label of a home-screen order in the segmented picker. */ +private val TodayLayout.labelRes: Int + get() = when (this) { + TodayLayout.AUTOMATIC -> R.string.settings_today_layout_auto + TodayLayout.LESSONS_FIRST -> R.string.settings_today_layout_lessons + TodayLayout.HOMEWORK_FIRST -> R.string.settings_today_layout_homework + } + +/** Label of a week start in the segmented picker. */ +private val WeekStart.labelRes: Int + get() = when (this) { + WeekStart.MONDAY -> R.string.settings_week_start_monday + WeekStart.TODAY -> R.string.settings_week_start_today + } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/FeelRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/FeelRows.kt new file mode 100644 index 00000000..912e7124 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/FeelRows.kt @@ -0,0 +1,246 @@ +package com.lumenpearson.lessons.ui.settings + +import android.os.Build +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Animation +import androidx.compose.material.icons.rounded.BlurLinear +import androidx.compose.material.icons.rounded.BlurOn +import androidx.compose.material.icons.rounded.Contrast +import androidx.compose.material.icons.rounded.MotionPhotosOn +import androidx.compose.material.icons.rounded.Speed +import androidx.compose.material.icons.rounded.Swipe +import androidx.compose.material.icons.rounded.Vibration +import androidx.compose.material.icons.rounded.Waves +import androidx.compose.material.icons.rounded.Widgets +import androidx.compose.runtime.Composable +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.designsystem.component.GroupSegmentedItem +import com.lumenpearson.lessons.core.designsystem.component.GroupSliderItem +import com.lumenpearson.lessons.core.designsystem.component.GroupSwitchItem +import com.lumenpearson.lessons.core.designsystem.modifier.LiquidRippleAnchor +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.AccentTone +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.model.HapticStrength +import com.lumenpearson.lessons.navigation.labelRes + +/** + * @param tabs whether the phone has the class tabs these rows are about — the + * swipe between them and the one it opens on. The diary home has neither. + */ +internal fun LazyListScope.feelRows( + state: SettingsUiState, + viewModel: SettingsViewModel, + tabs: Boolean, +) { + item(key = "haptics") { + SettingsGroup(title = correctedString(R.string.settings_haptics_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_haptics), + subtitle = correctedString(R.string.settings_haptics_description), + icon = Icons.Rounded.Vibration, + tone = accentTone(2), + checked = state.settings.hapticsEnabled, + onCheckedChange = viewModel::setHapticsEnabled, + ) + if (state.settings.hapticsEnabled) { + GroupSegmentedItem( + title = correctedString(R.string.settings_haptic_strength), + icon = Icons.Rounded.Vibration, + tone = accentTone(3), + items = HapticStrength.entries, + selectedItem = state.settings.hapticStrength, + onItemSelected = viewModel::setHapticStrength, + labelProvider = { strength -> correctedString(strength.labelRes) }, + ) + } + } + } + + if (tabs) item(key = "navigation") { + SettingsGroup(title = correctedString(R.string.settings_navigation_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_swipe_tabs), + subtitle = correctedString(R.string.settings_swipe_tabs_description), + icon = Icons.Rounded.Swipe, + tone = accentTone(1), + checked = state.settings.swipeTabs, + onCheckedChange = viewModel::setSwipeTabs, + ) + GroupSegmentedItem( + title = correctedString(R.string.settings_default_tab), + subtitle = correctedString(R.string.settings_default_tab_description), + icon = Icons.Rounded.Widgets, + tone = accentTone(4), + // The reader's own order, not the declaration order. This row is + // a picture of the bar it is about — its own comment below says + // the glyphs would only repeat it — and a picture that lists the + // three tabs in an order the bar no longer uses makes the reader + // map between two of them to answer one question. + items = state.settings.tabOrder, + selectedItem = state.settings.defaultTab, + onItemSelected = viewModel::setDefaultTab, + // No icons here: even at three segments a 360 dp screen leaves + // about 60 dp of label once an 18 dp glyph and its spacer are + // taken out, and the glyphs would only repeat the toolbar this + // row is about. + labelProvider = { tab -> correctedString(tab.labelRes) }, + ) + } + } + + item(key = "motion") { + SettingsGroup(title = correctedString(R.string.settings_motion_group)) { + GroupSwitchItem( + title = correctedString(R.string.settings_animations), + subtitle = correctedString(R.string.settings_animations_description), + icon = Icons.Rounded.Animation, + tone = accentTone(5), + checked = state.settings.animations, + onCheckedChange = viewModel::setAnimations, + ) + // Hidden rather than disabled when animations are off: a speed for + // something that does not move is not a dimmed control, it is a + // question with no answer. + if (state.settings.animations) { + GroupSliderItem( + title = correctedString(R.string.settings_motion_speed), + subtitle = correctedString(R.string.settings_motion_speed_description), + icon = Icons.Rounded.Speed, + tone = accentTone(1), + value = state.settings.motionSpeed, + onValueChange = viewModel::setMotionSpeed, + valueRange = AppSettings.MOTION_SPEED_RANGE, + increment = 0.1f, + valueFormatter = { speed -> "%.1f×".format(speed) }, + ) + } + } + } + + item(key = "effects") { + SettingsGroup(title = correctedString(R.string.settings_effects_group)) { + EdgeFadeRow( + checked = state.settings.edgeBlur, + tone = accentTone(0), + onCheckedChange = viewModel::setEdgeBlur, + ) + GroupSwitchItem( + title = correctedString(R.string.settings_motion_blur), + subtitle = if (SupportsShaders) { + correctedString(R.string.settings_motion_blur_description) + } else { + correctedString(R.string.settings_blur_unavailable) + }, + icon = Icons.Rounded.BlurOn, + tone = accentTone(5), + enabled = SupportsShaders, + checked = state.settings.motionBlur && SupportsShaders, + onCheckedChange = viewModel::setMotionBlur, + ) + if (state.settings.motionBlur && SupportsShaders) { + GroupSliderItem( + title = correctedString(R.string.settings_motion_blur_amount), + icon = Icons.Rounded.MotionPhotosOn, + tone = accentTone(3), + value = state.settings.motionBlurScale, + onValueChange = viewModel::setMotionBlurScale, + valueRange = AppSettings.MOTION_BLUR_SCALE_RANGE, + increment = 0.1f, + valueFormatter = { amount -> "%.1f×".format(amount) }, + ) + } + // The two whole-screen ornaments, each on its own switch. The + // ripple is a shader and shares the blur rows' availability; the + // wipe is a bitmap and runs on anything, so it is never disabled. + // Turning the wave on plays one, from the switch that turned it + // on. A setting whose whole subject is a visual effect can answer + // "what is this?" by doing it once, and the answer is only honest + // if it starts where the finger was — which is what the anchor is + // for. Switching it off plays nothing: the modifier is already + // disabled by the time the wave would be drawn, and a wave + // acknowledging its own removal would be a lie about the setting. + LiquidRippleAnchor { fire -> + GroupSwitchItem( + title = correctedString(R.string.settings_ripple), + subtitle = if (SupportsShaders) { + correctedString(R.string.settings_ripple_description) + } else { + correctedString(R.string.settings_blur_unavailable) + }, + icon = Icons.Rounded.Waves, + tone = accentTone(2), + enabled = SupportsShaders, + checked = state.settings.rippleEffects && SupportsShaders, + onCheckedChange = { on -> + viewModel.setRippleEffects(on) + if (on) fire() + }, + ) + } + GroupSwitchItem( + title = correctedString(R.string.settings_theme_reveal), + subtitle = correctedString(R.string.settings_theme_reveal_description), + icon = Icons.Rounded.Contrast, + tone = accentTone(4), + checked = state.settings.themeReveal, + onCheckedChange = viewModel::setThemeReveal, + ) + } + } +} + +/** Label of a haptic level in the segmented picker. */ +private val HapticStrength.labelRes: Int + get() = when (this) { + HapticStrength.NONE -> R.string.settings_haptic_none + HapticStrength.SUBTLE -> R.string.settings_haptic_subtle + HapticStrength.DOUBLE -> R.string.settings_haptic_double + HapticStrength.CLICK -> R.string.settings_haptic_click + } + +/** + * The edge fade, as one row that the settings page and the first-run flow both + * draw. + * + * **It is not gated on [SupportsShaders], and that is the fix rather than an + * oversight.** The setting turns on two things and only one of them is a + * shader: the blur arrived in Android 13, the gradient wash under the status + * bar and behind the toolbar is a `drawRect` that `progressiveBlur` draws on + * everything — deliberately, because that wash is what stops a scrolled list + * colliding with the clock on the devices that get no blur at all. The shell + * asks for it from `AppSettings.edgeBlur` alone, and `edgeBlur` defaults to + * true, so below Android 13 the wash was on every screen while the one switch + * that names it read «выключено» and refused to be pressed. `minSdk` is 26, so + * that is Android 8 through 12. + * + * Two copies of the row is how it got there: the first-run flow's said + * «Доступно на Android 13 и новее» under a switch nobody could move, and the + * settings page's said nothing at all. One row now, and the sentence it carries + * where there is no blur says what the switch still does rather than that it + * does nothing. + */ +@Composable +internal fun EdgeFadeRow( + checked: Boolean, + tone: AccentTone, + onCheckedChange: (Boolean) -> Unit, +) { + GroupSwitchItem( + title = correctedString(R.string.settings_edge_blur), + subtitle = if (SupportsShaders) { + correctedString(R.string.settings_edge_blur_description) + } else { + correctedString(R.string.settings_edge_blur_no_shader) + }, + icon = Icons.Rounded.BlurLinear, + tone = tone, + checked = checked, + onCheckedChange = onCheckedChange, + ) +} + +/** Both blur effects are AGSL runtime shaders, which arrived in Android 13. */ +internal val SupportsShaders: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt index 84e99a16..d4ef0b41 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt @@ -1,12 +1,9 @@ package com.lumenpearson.lessons.ui.settings -import android.os.Build -import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -16,45 +13,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.EventNote -import androidx.compose.material.icons.automirrored.rounded.Logout -import androidx.compose.material.icons.automirrored.rounded.MenuBook -import androidx.compose.material.icons.rounded.AdminPanelSettings -import androidx.compose.material.icons.rounded.Animation -import androidx.compose.material.icons.rounded.BlurLinear -import androidx.compose.material.icons.rounded.BlurOn -import androidx.compose.material.icons.rounded.BugReport -import androidx.compose.material.icons.rounded.CalendarViewWeek -import androidx.compose.material.icons.rounded.CloudSync -import androidx.compose.material.icons.rounded.Contrast -import androidx.compose.material.icons.rounded.DarkMode -import androidx.compose.material.icons.rounded.Dns -import androidx.compose.material.icons.rounded.EditNote -import androidx.compose.material.icons.rounded.FormatSize -import androidx.compose.material.icons.rounded.Info -import androidx.compose.material.icons.rounded.Language -import androidx.compose.material.icons.rounded.MoreHoriz -import androidx.compose.material.icons.rounded.MotionPhotosOn -import androidx.compose.material.icons.rounded.NotificationsActive -import androidx.compose.material.icons.rounded.Palette -import androidx.compose.material.icons.rounded.Person -import androidx.compose.material.icons.rounded.Refresh -import androidx.compose.material.icons.rounded.Reorder import androidx.compose.material.icons.rounded.School -import androidx.compose.material.icons.rounded.Speed -import androidx.compose.material.icons.rounded.Shield -import androidx.compose.material.icons.rounded.Swipe -import androidx.compose.material.icons.rounded.SystemUpdate -import androidx.compose.material.icons.rounded.TextFields -import androidx.compose.material.icons.rounded.Timer -import androidx.compose.material.icons.rounded.TouchApp -import androidx.compose.material.icons.rounded.Update -import androidx.compose.material.icons.rounded.Vibration -import androidx.compose.material.icons.rounded.ViewAgenda -import androidx.compose.material.icons.rounded.ViewDay -import androidx.compose.material.icons.rounded.Waves -import androidx.compose.material.icons.rounded.Weekend -import androidx.compose.material.icons.rounded.Widgets import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme @@ -70,212 +29,37 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel -import com.lumenpearson.lessons.BuildConfig import com.lumenpearson.lessons.R -import com.lumenpearson.lessons.core.data.repository.AppSettings import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile -import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem -import com.lumenpearson.lessons.core.designsystem.component.GroupItem import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem import com.lumenpearson.lessons.core.designsystem.component.GroupRow -import com.lumenpearson.lessons.core.designsystem.component.GroupSegmentedItem -import com.lumenpearson.lessons.core.designsystem.component.GroupSliderItem -import com.lumenpearson.lessons.core.designsystem.component.GroupSwitchItem import com.lumenpearson.lessons.core.designsystem.component.LessonsBottomSheet -import com.lumenpearson.lessons.core.designsystem.component.PillChip import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader import com.lumenpearson.lessons.core.designsystem.component.SectionHeader -import com.lumenpearson.lessons.core.designsystem.modifier.LiquidRippleAnchor import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString -import com.lumenpearson.lessons.core.designsystem.theme.AccentTone import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace import com.lumenpearson.lessons.core.designsystem.theme.ReportScrollOffset import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding -import com.lumenpearson.lessons.core.designsystem.theme.ThemeRevealAnchor import com.lumenpearson.lessons.core.designsystem.theme.accentTone import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur -import com.lumenpearson.lessons.core.designsystem.theme.errorTone import com.lumenpearson.lessons.core.designsystem.theme.statusBarSpace -import com.lumenpearson.lessons.core.model.AppFont -import com.lumenpearson.lessons.core.model.AppLanguage -import com.lumenpearson.lessons.core.model.HapticStrength -import com.lumenpearson.lessons.core.model.ThemeMode -import com.lumenpearson.lessons.core.model.TodayLayout -import com.lumenpearson.lessons.core.model.WeekStart -import com.lumenpearson.lessons.navigation.labelRes -import com.lumenpearson.lessons.ui.debug.DebugRow import com.lumenpearson.lessons.ui.common.ServerUrlSheet import com.lumenpearson.lessons.ui.diary.DiaryAccountPage import com.lumenpearson.lessons.ui.diary.DiaryScreen import com.lumenpearson.lessons.ui.diary.DiaryViewModel import com.lumenpearson.lessons.navigation.isInsecure -import com.lumenpearson.lessons.ui.common.SyncIntervalOptionsMinutes import com.lumenpearson.lessons.ui.common.asText -import com.lumenpearson.lessons.ui.common.syncIntervalLabel import com.lumenpearson.lessons.ui.admin.adminRows import com.lumenpearson.lessons.ui.admin.isClassManager import com.lumenpearson.lessons.ui.translate.translationRows -/** - * One page of the settings tree. - * - * The preferences used to be a single scroll of six labelled groups, which is - * how Essentials' own settings screen started and is not where it ended up: it - * splits them across pages you drop into, each with its own title in the pill at - * the bottom and its own way back. Two dozen rows on one page means scrolling - * past five things you did not come for, and the row you want is never where you - * left it because the groups above it grow and shrink with their own switches. - * - * The enum is the single definition of the split. The root screen lists it, the - * section screen renders one of it, and the shell titles the toolbar from it, so - * a new section is one entry here and one branch in [SettingsSectionScreen]. - * Which of them the root offers is [listedOn], one rule for both homes. - * - * @param tone which accent slot the row's tile takes on the root page. - */ -enum class SettingsSection( - @param:StringRes val titleRes: Int, - @param:StringRes val subtitleRes: Int, - val icon: ImageVector, - val tone: Int, -) { - APPEARANCE( - R.string.settings_appearance, - R.string.settings_appearance_summary, - Icons.Rounded.Palette, - 4, - ), - FEEL( - R.string.settings_feel, - R.string.settings_feel_summary, - Icons.Rounded.TouchApp, - 2, - ), - CONTENT( - R.string.settings_content, - R.string.settings_content_summary, - Icons.Rounded.ViewAgenda, - 3, - ), - // There are six accent slots and nine rows on the landing page, so three - // hues are used twice. Each pair is put as far apart as the list allows: - // this one shares slot 5 with "О приложении", last of the nine. - ALERTS( - R.string.settings_alerts, - R.string.settings_alerts_summary, - Icons.Rounded.NotificationsActive, - 5, - ), - SYNC( - R.string.settings_sync, - R.string.settings_sync_summary, - Icons.Rounded.CloudSync, - 0, - ), - ACCOUNT( - R.string.settings_class, - R.string.settings_class_summary, - Icons.Rounded.School, - 1, - ), - /** - * The diary: a second account, in a service this app does not own, that - * most installs in a class will never have — and, on a phone in no class, - * the only account there is. - * - * In a class it is a section rather than a fourth tab because a tab would - * show a sign-in wall in the bottom bar of everybody without such an - * account, for good — the toolbar never hides a destination. Next to - * «Класс» because the two rows are the same kind of thing: which account - * this phone is signed in to. The page it opens is not a list of - * preferences, which is why [SettingsSectionScreen] hands it over whole: the - * diary itself in a class, the account page on the diary home, where the - * diary already is the home. - */ - DIARY( - R.string.diary_title, - R.string.diary_section_summary, - Icons.AutoMirrored.Rounded.MenuBook, - 4, - ), - UPDATES( - R.string.settings_updates, - R.string.settings_updates_summary, - Icons.Rounded.SystemUpdate, - 2, - ), - ABOUT( - R.string.settings_about, - R.string.settings_about_summary, - Icons.Rounded.Info, - 5, - ), - - /** - * The pages only an administrator or the owner of the class has. - * - * Listed by [listedOn] only once the server has said who this phone belongs - * to — the same shape as [PERMISSIONS], for a different reason: that one - * appears when something is wrong, this one when somebody is allowed. - */ - ADMIN( - R.string.settings_admin, - R.string.settings_admin_summary, - Icons.Rounded.AdminPanelSettings, - 1, - ), - - /** - * Reached from the notifications page, never from the root list. - * - * It is a page about a fault, so it exists only while there is one: a - * permanent "Разрешения" row on the landing page would be one more thing to - * read past on every visit, and would say nothing on the phones — most of - * them — where everything is granted. [listedOn] is what keeps it off. - */ - PERMISSIONS( - R.string.permissions_title, - R.string.permissions_banner_description, - Icons.Rounded.Shield, - 5, - ), - ; - - /** - * Whether the landing page offers a row for this section, on a phone in - * [mode] — [manager] being whether the server has said this phone may - * manage its class. - * - * One rule for both homes, replacing a flag that could only say «never on - * the root». On the diary home the rows that are about a class go: its - * timetable and widget ([CONTENT]), its alerts ([ALERTS]) — planned from a - * class timetable only, so a switch there would be a promise nothing keeps - * — and the class account itself ([ACCOUNT]), whose `/me` and Telegram link - * need a class token this phone does not have. What stays is what is about - * the phone ([APPEARANCE], [FEEL], [UPDATES], [ABOUT]), the server address - * every diary read goes through ([SYNC]), and the diary. - */ - fun listedOn(mode: ShellMode, manager: Boolean): Boolean = when (this) { - PERMISSIONS -> false - ADMIN -> mode == ShellMode.CLASS && manager - CONTENT, ALERTS, ACCOUNT -> mode != ShellMode.DIARY - APPEARANCE, FEEL, SYNC, DIARY, UPDATES, ABOUT -> true - } - - companion object { - /** `null` for anything this build does not have, including `null` itself. */ - fun fromName(name: String?): SettingsSection? = entries.firstOrNull { it.name == name } - } -} - /** * The settings landing page: who you are, and where the preferences live. * @@ -589,6 +373,18 @@ private fun SettingsPage( } } +/** A labelled group; the one place the label-to-group spacing is decided. */ +@Composable +internal fun SettingsGroup( + title: String, + content: @Composable ColumnScope.() -> Unit, +) { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = title) + RoundedCardContainer(content = content) + } +} + /** * The card at the top of the root page on the diary home: the pupil and the * school, from the diary view model the home already holds (the activity's). @@ -635,688 +431,6 @@ private fun ClassHeroCard( } } -/** - * Typography lands here rather than in a section of its own. - * - * A third page called «Шрифт и движение» was the obvious move and the wrong one: - * it would have put the type on a page with the animation switches, which are - * the same decision as the ripple, the theme wipe and the two blurs — all of - * which live under «Взаимодействие». Splitting motion across two pages to keep - * the font company costs more than the font gains. So the face and its size go - * where everything else that repaints the whole app already is, and motion joins - * the effects it belongs with. - */ -private fun LazyListScope.appearanceRows( - state: SettingsUiState, - viewModel: SettingsViewModel, -) { - item(key = "appearance") { - // Every row in this group repaints the whole app, so every row opens the - // circle from itself. The anchor is what makes the wavefront look like it - // came out from under the finger rather than from the middle of nowhere. - SettingsGroup(title = correctedString(R.string.settings_theme)) { - ThemeRevealAnchor { reveal -> - GroupSegmentedItem( - title = correctedString(R.string.settings_theme_mode), - icon = Icons.Rounded.Contrast, - tone = accentTone(4), - items = ThemeMode.entries, - selectedItem = state.settings.themeMode, - onItemSelected = { mode -> reveal { viewModel.setThemeMode(mode) } }, - labelProvider = { mode -> correctedString(mode.labelRes) }, - ) - } - ThemeRevealAnchor { reveal -> - GroupSwitchItem( - title = correctedString(R.string.settings_dynamic_color), - subtitle = if (SupportsDynamicColor) { - correctedString(R.string.settings_dynamic_color_description) - } else { - correctedString(R.string.settings_dynamic_color_unavailable) - }, - icon = Icons.Rounded.Palette, - tone = accentTone(0), - checked = state.settings.dynamicColor && SupportsDynamicColor, - enabled = SupportsDynamicColor, - onCheckedChange = { on -> reveal { viewModel.setDynamicColor(on) } }, - ) - } - ThemeRevealAnchor { reveal -> - GroupSwitchItem( - title = correctedString(R.string.settings_pitch_black), - subtitle = correctedString(R.string.settings_pitch_black_description), - icon = Icons.Rounded.DarkMode, - tone = accentTone(5), - checked = state.settings.pitchBlack, - onCheckedChange = { on -> reveal { viewModel.setPitchBlack(on) } }, - ) - } - } - } - - item(key = "typography") { - SettingsGroup(title = correctedString(R.string.settings_type_group)) { - GroupSegmentedItem( - title = correctedString(R.string.settings_font), - subtitle = correctedString(R.string.settings_font_description), - icon = Icons.Rounded.TextFields, - tone = accentTone(2), - items = AppFont.entries, - selectedItem = state.settings.appFont, - onItemSelected = viewModel::setAppFont, - labelProvider = { font -> correctedString(font.labelRes) }, - ) - // Four named steps rather than a slider: a size is something a - // person has to be able to put back, and "около одной целой семи" - // is not a place anybody can return to. The labels say what each - // step is for; the numbers behind them are in AppSettings. - GroupSegmentedItem( - title = correctedString(R.string.settings_text_size), - subtitle = correctedString(R.string.settings_text_size_description), - icon = Icons.Rounded.FormatSize, - tone = accentTone(4), - items = AppSettings.TEXT_SCALE_OPTIONS, - // Matched by value rather than by identity, and against the - // stored float rather than a remembered index: the store clamps - // what it reads, so a value from an older build lands on the - // nearest step instead of leaving every segment unselected. - selectedItem = nearestTextScale(state.settings.textScale), - onItemSelected = viewModel::setTextScale, - labelProvider = { scale -> correctedString(textScaleLabelRes(scale)) }, - ) - } - } - - // The language sits under the type rather than beside the theme: it is the - // other thing on this page that changes every word on every screen, and - // like the font it takes effect the moment it is tapped — below Android 13 - // by recreating the activity, above it by the system restarting it for us. - item(key = "language") { - SettingsGroup(title = correctedString(R.string.settings_language_group)) { - GroupSegmentedItem( - title = correctedString(R.string.settings_language), - subtitle = correctedString(R.string.settings_language_description), - icon = Icons.Rounded.Language, - tone = accentTone(1), - items = AppLanguage.entries, - selectedItem = state.settings.language, - onItemSelected = viewModel::setLanguage, - labelProvider = { language -> correctedString(language.labelRes) }, - ) - } - } -} - -/** Label of a language in the segmented picker. */ -private val AppLanguage.labelRes: Int - get() = when (this) { - AppLanguage.SYSTEM -> R.string.settings_language_system - AppLanguage.RUSSIAN -> R.string.settings_language_russian - AppLanguage.ENGLISH -> R.string.settings_language_english - } - -/** - * The offered step closest to [scale]. - * - * The picker has to have exactly one segment selected, and the stored value is - * a float that a previous build — or a clamp — may have left between two steps. - * Nearest is the only answer that never shows a picker with nothing chosen. - */ -private fun nearestTextScale(scale: Float): Float = - AppSettings.TEXT_SCALE_OPTIONS.minBy { kotlin.math.abs(it - scale) } - -/** Label of a text-size step; see `AppSettings.TEXT_SCALE_OPTIONS`. */ -@StringRes -private fun textScaleLabelRes(scale: Float): Int = when (scale) { - AppSettings.TEXT_SCALE_OPTIONS[0] -> R.string.settings_text_size_small - AppSettings.TEXT_SCALE_OPTIONS[2] -> R.string.settings_text_size_large - AppSettings.TEXT_SCALE_OPTIONS[3] -> R.string.settings_text_size_huge - else -> R.string.settings_text_size_normal -} - -/** Label of a typeface in the segmented picker. */ -private val AppFont.labelRes: Int - get() = when (this) { - AppFont.BUNDLED -> R.string.settings_font_bundled - AppFont.SYSTEM -> R.string.settings_font_system - } - -/** - * @param tabs whether the phone has the class tabs these rows are about — the - * swipe between them and the one it opens on. The diary home has neither. - */ -private fun LazyListScope.feelRows( - state: SettingsUiState, - viewModel: SettingsViewModel, - tabs: Boolean, -) { - item(key = "haptics") { - SettingsGroup(title = correctedString(R.string.settings_haptics_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_haptics), - subtitle = correctedString(R.string.settings_haptics_description), - icon = Icons.Rounded.Vibration, - tone = accentTone(2), - checked = state.settings.hapticsEnabled, - onCheckedChange = viewModel::setHapticsEnabled, - ) - if (state.settings.hapticsEnabled) { - GroupSegmentedItem( - title = correctedString(R.string.settings_haptic_strength), - icon = Icons.Rounded.Vibration, - tone = accentTone(3), - items = HapticStrength.entries, - selectedItem = state.settings.hapticStrength, - onItemSelected = viewModel::setHapticStrength, - labelProvider = { strength -> correctedString(strength.labelRes) }, - ) - } - } - } - - if (tabs) item(key = "navigation") { - SettingsGroup(title = correctedString(R.string.settings_navigation_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_swipe_tabs), - subtitle = correctedString(R.string.settings_swipe_tabs_description), - icon = Icons.Rounded.Swipe, - tone = accentTone(1), - checked = state.settings.swipeTabs, - onCheckedChange = viewModel::setSwipeTabs, - ) - GroupSegmentedItem( - title = correctedString(R.string.settings_default_tab), - subtitle = correctedString(R.string.settings_default_tab_description), - icon = Icons.Rounded.Widgets, - tone = accentTone(4), - // The reader's own order, not the declaration order. This row is - // a picture of the bar it is about — its own comment below says - // the glyphs would only repeat it — and a picture that lists the - // three tabs in an order the bar no longer uses makes the reader - // map between two of them to answer one question. - items = state.settings.tabOrder, - selectedItem = state.settings.defaultTab, - onItemSelected = viewModel::setDefaultTab, - // No icons here: even at three segments a 360 dp screen leaves - // about 60 dp of label once an 18 dp glyph and its spacer are - // taken out, and the glyphs would only repeat the toolbar this - // row is about. - labelProvider = { tab -> correctedString(tab.labelRes) }, - ) - } - } - - item(key = "motion") { - SettingsGroup(title = correctedString(R.string.settings_motion_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_animations), - subtitle = correctedString(R.string.settings_animations_description), - icon = Icons.Rounded.Animation, - tone = accentTone(5), - checked = state.settings.animations, - onCheckedChange = viewModel::setAnimations, - ) - // Hidden rather than disabled when animations are off: a speed for - // something that does not move is not a dimmed control, it is a - // question with no answer. - if (state.settings.animations) { - GroupSliderItem( - title = correctedString(R.string.settings_motion_speed), - subtitle = correctedString(R.string.settings_motion_speed_description), - icon = Icons.Rounded.Speed, - tone = accentTone(1), - value = state.settings.motionSpeed, - onValueChange = viewModel::setMotionSpeed, - valueRange = AppSettings.MOTION_SPEED_RANGE, - increment = 0.1f, - valueFormatter = { speed -> "%.1f×".format(speed) }, - ) - } - } - } - - item(key = "effects") { - SettingsGroup(title = correctedString(R.string.settings_effects_group)) { - EdgeFadeRow( - checked = state.settings.edgeBlur, - tone = accentTone(0), - onCheckedChange = viewModel::setEdgeBlur, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_motion_blur), - subtitle = if (SupportsShaders) { - correctedString(R.string.settings_motion_blur_description) - } else { - correctedString(R.string.settings_blur_unavailable) - }, - icon = Icons.Rounded.BlurOn, - tone = accentTone(5), - enabled = SupportsShaders, - checked = state.settings.motionBlur && SupportsShaders, - onCheckedChange = viewModel::setMotionBlur, - ) - if (state.settings.motionBlur && SupportsShaders) { - GroupSliderItem( - title = correctedString(R.string.settings_motion_blur_amount), - icon = Icons.Rounded.MotionPhotosOn, - tone = accentTone(3), - value = state.settings.motionBlurScale, - onValueChange = viewModel::setMotionBlurScale, - valueRange = AppSettings.MOTION_BLUR_SCALE_RANGE, - increment = 0.1f, - valueFormatter = { amount -> "%.1f×".format(amount) }, - ) - } - // The two whole-screen ornaments, each on its own switch. The - // ripple is a shader and shares the blur rows' availability; the - // wipe is a bitmap and runs on anything, so it is never disabled. - // Turning the wave on plays one, from the switch that turned it - // on. A setting whose whole subject is a visual effect can answer - // "what is this?" by doing it once, and the answer is only honest - // if it starts where the finger was — which is what the anchor is - // for. Switching it off plays nothing: the modifier is already - // disabled by the time the wave would be drawn, and a wave - // acknowledging its own removal would be a lie about the setting. - LiquidRippleAnchor { fire -> - GroupSwitchItem( - title = correctedString(R.string.settings_ripple), - subtitle = if (SupportsShaders) { - correctedString(R.string.settings_ripple_description) - } else { - correctedString(R.string.settings_blur_unavailable) - }, - icon = Icons.Rounded.Waves, - tone = accentTone(2), - enabled = SupportsShaders, - checked = state.settings.rippleEffects && SupportsShaders, - onCheckedChange = { on -> - viewModel.setRippleEffects(on) - if (on) fire() - }, - ) - } - GroupSwitchItem( - title = correctedString(R.string.settings_theme_reveal), - subtitle = correctedString(R.string.settings_theme_reveal_description), - icon = Icons.Rounded.Contrast, - tone = accentTone(4), - checked = state.settings.themeReveal, - onCheckedChange = viewModel::setThemeReveal, - ) - } - } -} - -/** - * Three groups rather than one list of twelve rows. - * - * The first group is what every surface shares. The other two are one screen - * each, in the order the bottom bar draws them, so somebody who came here to - * change the home screen reads five titles about the home screen instead of - * twelve about everything. - */ -private fun LazyListScope.contentRows( - state: SettingsUiState, - viewModel: SettingsViewModel, -) { - item(key = "content") { - SettingsGroup(title = correctedString(R.string.settings_content_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_show_teacher), - subtitle = correctedString(R.string.settings_show_teacher_description), - icon = Icons.Rounded.Person, - tone = accentTone(3), - checked = state.settings.showTeacher, - onCheckedChange = viewModel::setShowTeacher, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_widget_progress), - subtitle = correctedString(R.string.settings_widget_progress_description), - icon = Icons.Rounded.Widgets, - tone = accentTone(1), - checked = state.settings.widgetShowProgress, - onCheckedChange = viewModel::setWidgetShowProgress, - ) - } - } - - item(key = "content_home") { - SettingsGroup(title = correctedString(R.string.settings_home_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_today_hero), - subtitle = correctedString(R.string.settings_today_hero_description), - icon = Icons.Rounded.Timer, - tone = accentTone(0), - checked = state.settings.todayShowHero, - onCheckedChange = viewModel::setTodayShowHero, - ) - GroupSegmentedItem( - title = correctedString(R.string.settings_today_layout), - subtitle = correctedString(R.string.settings_today_layout_description), - icon = Icons.Rounded.Reorder, - tone = accentTone(2), - items = TodayLayout.entries, - selectedItem = state.settings.todayLayout, - onItemSelected = viewModel::setTodayLayout, - labelProvider = { layout -> correctedString(layout.labelRes) }, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_today_whole_day), - subtitle = correctedString(R.string.settings_today_whole_day_description), - icon = Icons.Rounded.ViewDay, - tone = accentTone(4), - checked = state.settings.todayWholeDay, - onCheckedChange = viewModel::setTodayWholeDay, - ) - GroupSegmentedItem( - title = correctedString(R.string.settings_today_homework_count), - subtitle = correctedString(R.string.settings_today_homework_count_description), - icon = Icons.Rounded.EditNote, - tone = accentTone(5), - items = AppSettings.HOMEWORK_PREVIEW_OPTIONS, - // No nearest-match here, unlike the text-size picker above: the - // store snaps this number to one of the three steps on the way - // in and on the way out, so what it hands over is always one of - // the segments. - selectedItem = state.settings.todayHomeworkPreview, - onItemSelected = viewModel::setTodayHomeworkPreview, - labelProvider = { count -> count.toString() }, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_today_events), - subtitle = correctedString(R.string.settings_today_events_description), - icon = Icons.AutoMirrored.Rounded.EventNote, - tone = accentTone(1), - checked = state.settings.todayShowEvents, - onCheckedChange = viewModel::setTodayShowEvents, - ) - } - } - - item(key = "content_calendar") { - SettingsGroup(title = correctedString(R.string.settings_calendar_group)) { - GroupSegmentedItem( - title = correctedString(R.string.settings_week_start), - subtitle = correctedString(R.string.settings_week_start_description), - icon = Icons.Rounded.CalendarViewWeek, - tone = accentTone(3), - items = WeekStart.entries, - selectedItem = state.settings.weekStart, - onItemSelected = viewModel::setWeekStart, - labelProvider = { start -> correctedString(start.labelRes) }, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_week_weekends), - subtitle = correctedString(R.string.settings_week_weekends_description), - icon = Icons.Rounded.Weekend, - tone = accentTone(0), - checked = state.settings.weekShowWeekends, - onCheckedChange = viewModel::setWeekShowWeekends, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_week_load), - subtitle = correctedString(R.string.settings_week_load_description), - icon = Icons.Rounded.MoreHoriz, - tone = accentTone(2), - checked = state.settings.weekShowLoad, - onCheckedChange = viewModel::setWeekShowLoad, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_week_events), - subtitle = correctedString(R.string.settings_week_events_description), - icon = Icons.AutoMirrored.Rounded.EventNote, - tone = accentTone(4), - checked = state.settings.weekShowEvents, - onCheckedChange = viewModel::setWeekShowEvents, - ) - GroupSwitchItem( - title = correctedString(R.string.settings_week_homework), - subtitle = correctedString(R.string.settings_week_homework_description), - icon = Icons.Rounded.EditNote, - tone = accentTone(5), - checked = state.settings.weekShowHomework, - onCheckedChange = viewModel::setWeekShowHomework, - ) - } - } -} - -/** - * The edge fade, as one row that the settings page and the first-run flow both - * draw. - * - * **It is not gated on [SupportsShaders], and that is the fix rather than an - * oversight.** The setting turns on two things and only one of them is a - * shader: the blur arrived in Android 13, the gradient wash under the status - * bar and behind the toolbar is a `drawRect` that `progressiveBlur` draws on - * everything — deliberately, because that wash is what stops a scrolled list - * colliding with the clock on the devices that get no blur at all. The shell - * asks for it from `AppSettings.edgeBlur` alone, and `edgeBlur` defaults to - * true, so below Android 13 the wash was on every screen while the one switch - * that names it read «выключено» and refused to be pressed. `minSdk` is 26, so - * that is Android 8 through 12. - * - * Two copies of the row is how it got there: the first-run flow's said - * «Доступно на Android 13 и новее» under a switch nobody could move, and the - * settings page's said nothing at all. One row now, and the sentence it carries - * where there is no blur says what the switch still does rather than that it - * does nothing. - */ -@Composable -internal fun EdgeFadeRow( - checked: Boolean, - tone: AccentTone, - onCheckedChange: (Boolean) -> Unit, -) { - GroupSwitchItem( - title = correctedString(R.string.settings_edge_blur), - subtitle = if (SupportsShaders) { - correctedString(R.string.settings_edge_blur_description) - } else { - correctedString(R.string.settings_edge_blur_no_shader) - }, - icon = Icons.Rounded.BlurLinear, - tone = tone, - checked = checked, - onCheckedChange = onCheckedChange, - ) -} - -/** Label of a home-screen order in the segmented picker. */ -private val TodayLayout.labelRes: Int - get() = when (this) { - TodayLayout.AUTOMATIC -> R.string.settings_today_layout_auto - TodayLayout.LESSONS_FIRST -> R.string.settings_today_layout_lessons - TodayLayout.HOMEWORK_FIRST -> R.string.settings_today_layout_homework - } - -/** Label of a week start in the segmented picker. */ -private val WeekStart.labelRes: Int - get() = when (this) { - WeekStart.MONDAY -> R.string.settings_week_start_monday - WeekStart.TODAY -> R.string.settings_week_start_today - } - - -/** - * @param classSync whether the phone has a class for the background sync to - * refresh. Without one — the diary home — the interval and «Обновить сейчас» - * drive a worker that syncs a class only, so they would be switches that do - * nothing; the server address stays, because every diary read goes through - * it. - */ -private fun LazyListScope.syncRows( - state: SettingsUiState, - viewModel: SettingsViewModel, - classSync: Boolean, - onEditServer: () -> Unit, -) = item(key = "sync") { - SettingsGroup(title = correctedString(R.string.settings_sync_group)) { - if (classSync) { - SyncIntervalRow( - selectedMinutes = state.settings.syncIntervalMinutes, - onSelect = viewModel::setSyncInterval, - ) - } - GroupLinkItem( - title = correctedString(R.string.settings_server_url), - subtitle = state.settings.baseUrl.takeIf { it.isNotBlank() } - ?: correctedString(R.string.settings_server_url_unset), - icon = Icons.Rounded.Dns, - tone = accentTone(0), - onClick = onEditServer, - ) - // Filled and full width, as the last row of the group, because it is - // the one thing on this page that *does* something the moment it is - // pressed rather than storing a preference. Essentials closes its own - // updates group with the same shape. - if (classSync) { - GroupActionItem( - label = correctedString(R.string.settings_refresh_now), - icon = Icons.Rounded.Refresh, - busy = state.isRefreshing, - onClick = viewModel::refreshNow, - ) - } - } -} - -private fun LazyListScope.aboutRows( - state: SettingsUiState, - viewModel: SettingsViewModel, - onOpenDocs: () -> Unit, -) { - // First on the page, above the switch and the licences. The guide is the - // only row here somebody arrives *looking* for — everything else on this - // page is something you find — and a row you have to scroll to is a row a - // reader concludes does not exist. - item(key = "docs") { - SettingsGroup(title = correctedString(R.string.docs_group)) { - GroupLinkItem( - title = correctedString(R.string.docs_open), - subtitle = correctedString(R.string.docs_open_description), - icon = Icons.AutoMirrored.Rounded.MenuBook, - tone = accentTone(4), - onClick = onOpenDocs, - ) - } - } - item(key = "about") { - SettingsGroup(title = correctedString(R.string.settings_about_group)) { - GroupSwitchItem( - title = correctedString(R.string.settings_debug), - subtitle = correctedString(R.string.settings_debug_description), - icon = Icons.Rounded.BugReport, - tone = accentTone(2), - checked = state.settings.debugMode, - onCheckedChange = viewModel::setDebugMode, - ) - // Directly under the switch that writes them, and on the page - // everybody can reach. The reports used to be readable only from - // the two manager routes — the toolbar's bug button and the - // management page — while the switch was here, so a reader who was - // not an administrator could record a crash and never see it. - DebugRow( - enabled = state.settings.debugMode, - onEnabledChange = viewModel::setDebugMode, - ) - } - } - // The last thing on the last page, which is where an about block belongs and - // where Essentials puts its own. It carries the version, the description and - // the design credit, so the three rows that used to state those separately - // are gone rather than repeated above it. - item(key = "about_card") { - // No horizontal padding of its own. The list already insets every item - // by `ScreenPadding`, so this added a second one and the card came out - // 32 dp narrower on each side than every group above it — which is - // most of why its two link buttons were breaking «Essentials» into - // «Essent / ials». - AboutCard(serverStatus = state.serverStatus) - } -} - -/** - * Dynamic colour is a wallpaper-derived palette, which only exists from Android - * 12 on. Below that the row stays visible but disabled — hiding it would make - * the setting look like a bug on the phones that do have it. - */ -internal val SupportsDynamicColor: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S - -/** Both blur effects are AGSL runtime shaders, which arrived in Android 13. */ -internal val SupportsShaders: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU - -/** A labelled group; the one place the label-to-group spacing is decided. */ -@Composable -internal fun SettingsGroup( - title: String, - content: @Composable ColumnScope.() -> Unit, -) { - Column(modifier = Modifier.fillMaxWidth()) { - SectionHeader(title = title) - RoundedCardContainer(content = content) - } -} - -/** Label of a theme mode in the segmented picker. */ -internal val ThemeMode.labelRes: Int - get() = when (this) { - ThemeMode.SYSTEM -> R.string.settings_theme_system - ThemeMode.LIGHT -> R.string.settings_theme_light - ThemeMode.DARK -> R.string.settings_theme_dark - } - -/** Label of a haptic level in the segmented picker. */ -private val HapticStrength.labelRes: Int - get() = when (this) { - HapticStrength.NONE -> R.string.settings_haptic_none - HapticStrength.SUBTLE -> R.string.settings_haptic_subtle - HapticStrength.DOUBLE -> R.string.settings_haptic_double - HapticStrength.CLICK -> R.string.settings_haptic_click - } - -/** - * Sync cadence as chips rather than a slider: the values are not continuous — - * WorkManager will not run periodic work more often than every 15 minutes — and - * a chip row makes the actual choices legible. - */ -@Composable -private fun SyncIntervalRow( - selectedMinutes: Int, - onSelect: (Int) -> Unit, - modifier: Modifier = Modifier, -) { - GroupRow( - modifier = modifier, - verticalAlignment = Alignment.Top, - ) { - AccentIconTile(icon = Icons.Rounded.Update, tone = accentTone(4)) - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - Text( - text = correctedString(R.string.settings_sync_interval), - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - // FlowRow because six chips do not fit one line on a small phone. - FlowRow( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - SyncIntervalOptionsMinutes.forEach { minutes -> - PillChip( - text = syncIntervalLabel(minutes), - selected = minutes == selectedMinutes, - onClick = { onSelect(minutes) }, - ) - } - } - } - } -} - /** * Confirmation before signing out. * diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSection.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSection.kt new file mode 100644 index 00000000..127cafff --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSection.kt @@ -0,0 +1,170 @@ +package com.lumenpearson.lessons.ui.settings + +import androidx.annotation.StringRes +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import androidx.compose.material.icons.rounded.AdminPanelSettings +import androidx.compose.material.icons.rounded.CloudSync +import androidx.compose.material.icons.rounded.Info +import androidx.compose.material.icons.rounded.NotificationsActive +import androidx.compose.material.icons.rounded.Palette +import androidx.compose.material.icons.rounded.School +import androidx.compose.material.icons.rounded.Shield +import androidx.compose.material.icons.rounded.SystemUpdate +import androidx.compose.material.icons.rounded.TouchApp +import androidx.compose.material.icons.rounded.ViewAgenda +import androidx.compose.ui.graphics.vector.ImageVector +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.ShellMode + +/** + * One page of the settings tree. + * + * The preferences used to be a single scroll of six labelled groups, which is + * how Essentials' own settings screen started and is not where it ended up: it + * splits them across pages you drop into, each with its own title in the pill at + * the bottom and its own way back. Two dozen rows on one page means scrolling + * past five things you did not come for, and the row you want is never where you + * left it because the groups above it grow and shrink with their own switches. + * + * The enum is the single definition of the split. The root screen lists it, the + * section screen renders one of it, and the shell titles the toolbar from it, so + * a new section is one entry here and one branch in [SettingsSectionScreen]. + * Which of them the root offers is [listedOn], one rule for both homes. + * + * @param tone which accent slot the row's tile takes on the root page. + */ +enum class SettingsSection( + @param:StringRes val titleRes: Int, + @param:StringRes val subtitleRes: Int, + val icon: ImageVector, + val tone: Int, +) { + APPEARANCE( + R.string.settings_appearance, + R.string.settings_appearance_summary, + Icons.Rounded.Palette, + 4, + ), + FEEL( + R.string.settings_feel, + R.string.settings_feel_summary, + Icons.Rounded.TouchApp, + 2, + ), + CONTENT( + R.string.settings_content, + R.string.settings_content_summary, + Icons.Rounded.ViewAgenda, + 3, + ), + // There are six accent slots and nine rows on the landing page, so three + // hues are used twice. Each pair is put as far apart as the list allows: + // this one shares slot 5 with "О приложении", last of the nine. + ALERTS( + R.string.settings_alerts, + R.string.settings_alerts_summary, + Icons.Rounded.NotificationsActive, + 5, + ), + SYNC( + R.string.settings_sync, + R.string.settings_sync_summary, + Icons.Rounded.CloudSync, + 0, + ), + ACCOUNT( + R.string.settings_class, + R.string.settings_class_summary, + Icons.Rounded.School, + 1, + ), + /** + * The diary: a second account, in a service this app does not own, that + * most installs in a class will never have — and, on a phone in no class, + * the only account there is. + * + * In a class it is a section rather than a fourth tab because a tab would + * show a sign-in wall in the bottom bar of everybody without such an + * account, for good — the toolbar never hides a destination. Next to + * «Класс» because the two rows are the same kind of thing: which account + * this phone is signed in to. The page it opens is not a list of + * preferences, which is why [SettingsSectionScreen] hands it over whole: the + * diary itself in a class, the account page on the diary home, where the + * diary already is the home. + */ + DIARY( + R.string.diary_title, + R.string.diary_section_summary, + Icons.AutoMirrored.Rounded.MenuBook, + 4, + ), + UPDATES( + R.string.settings_updates, + R.string.settings_updates_summary, + Icons.Rounded.SystemUpdate, + 2, + ), + ABOUT( + R.string.settings_about, + R.string.settings_about_summary, + Icons.Rounded.Info, + 5, + ), + + /** + * The pages only an administrator or the owner of the class has. + * + * Listed by [listedOn] only once the server has said who this phone belongs + * to — the same shape as [PERMISSIONS], for a different reason: that one + * appears when something is wrong, this one when somebody is allowed. + */ + ADMIN( + R.string.settings_admin, + R.string.settings_admin_summary, + Icons.Rounded.AdminPanelSettings, + 1, + ), + + /** + * Reached from the notifications page, never from the root list. + * + * It is a page about a fault, so it exists only while there is one: a + * permanent "Разрешения" row on the landing page would be one more thing to + * read past on every visit, and would say nothing on the phones — most of + * them — where everything is granted. [listedOn] is what keeps it off. + */ + PERMISSIONS( + R.string.permissions_title, + R.string.permissions_banner_description, + Icons.Rounded.Shield, + 5, + ), + ; + + /** + * Whether the landing page offers a row for this section, on a phone in + * [mode] — [manager] being whether the server has said this phone may + * manage its class. + * + * One rule for both homes, replacing a flag that could only say «never on + * the root». On the diary home the rows that are about a class go: its + * timetable and widget ([CONTENT]), its alerts ([ALERTS]) — planned from a + * class timetable only, so a switch there would be a promise nothing keeps + * — and the class account itself ([ACCOUNT]), whose `/me` and Telegram link + * need a class token this phone does not have. What stays is what is about + * the phone ([APPEARANCE], [FEEL], [UPDATES], [ABOUT]), the server address + * every diary read goes through ([SYNC]), and the diary. + */ + fun listedOn(mode: ShellMode, manager: Boolean): Boolean = when (this) { + PERMISSIONS -> false + ADMIN -> mode == ShellMode.CLASS && manager + CONTENT, ALERTS, ACCOUNT -> mode != ShellMode.DIARY + APPEARANCE, FEEL, SYNC, DIARY, UPDATES, ABOUT -> true + } + + companion object { + /** `null` for anything this build does not have, including `null` itself. */ + fun fromName(name: String?): SettingsSection? = entries.firstOrNull { it.name == name } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SyncRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SyncRows.kt new file mode 100644 index 00000000..d7a20ac8 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SyncRows.kt @@ -0,0 +1,111 @@ +package com.lumenpearson.lessons.ui.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Dns +import androidx.compose.material.icons.rounded.Refresh +import androidx.compose.material.icons.rounded.Update +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile +import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.common.SyncIntervalOptionsMinutes +import com.lumenpearson.lessons.ui.common.syncIntervalLabel + +/** + * @param classSync whether the phone has a class for the background sync to + * refresh. Without one — the diary home — the interval and «Обновить сейчас» + * drive a worker that syncs a class only, so they would be switches that do + * nothing; the server address stays, because every diary read goes through + * it. + */ +internal fun LazyListScope.syncRows( + state: SettingsUiState, + viewModel: SettingsViewModel, + classSync: Boolean, + onEditServer: () -> Unit, +) = item(key = "sync") { + SettingsGroup(title = correctedString(R.string.settings_sync_group)) { + if (classSync) { + SyncIntervalRow( + selectedMinutes = state.settings.syncIntervalMinutes, + onSelect = viewModel::setSyncInterval, + ) + } + GroupLinkItem( + title = correctedString(R.string.settings_server_url), + subtitle = state.settings.baseUrl.takeIf { it.isNotBlank() } + ?: correctedString(R.string.settings_server_url_unset), + icon = Icons.Rounded.Dns, + tone = accentTone(0), + onClick = onEditServer, + ) + // Filled and full width, as the last row of the group, because it is + // the one thing on this page that *does* something the moment it is + // pressed rather than storing a preference. Essentials closes its own + // updates group with the same shape. + if (classSync) { + GroupActionItem( + label = correctedString(R.string.settings_refresh_now), + icon = Icons.Rounded.Refresh, + busy = state.isRefreshing, + onClick = viewModel::refreshNow, + ) + } + } +} + +/** + * Sync cadence as chips rather than a slider: the values are not continuous — + * WorkManager will not run periodic work more often than every 15 minutes — and + * a chip row makes the actual choices legible. + */ +@Composable +private fun SyncIntervalRow( + selectedMinutes: Int, + onSelect: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + GroupRow( + modifier = modifier, + verticalAlignment = Alignment.Top, + ) { + AccentIconTile(icon = Icons.Rounded.Update, tone = accentTone(4)) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text( + text = correctedString(R.string.settings_sync_interval), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + // FlowRow because six chips do not fit one line on a small phone. + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + SyncIntervalOptionsMinutes.forEach { minutes -> + PillChip( + text = syncIntervalLabel(minutes), + selected = minutes == selectedMinutes, + onClick = { onSelect(minutes) }, + ) + } + } + } + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/debug/DebugReachTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/debug/DebugReachTest.kt index 2aa2e87b..662e1ad2 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/debug/DebugReachTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/debug/DebugReachTest.kt @@ -60,8 +60,12 @@ class DebugReachTest { */ @Test fun `the way in is on the page that is not gated on a role`() { - val screen = sourceOf("ui/settings/SettingsScreen.kt") - val about = screen.substringAfter("private fun LazyListScope.aboutRows(") + val screen = sourceOf("ui/settings/AboutRows.kt") + val declaration = "internal fun LazyListScope.aboutRows(" + // `substringAfter` hands back the whole file when the declaration is + // not found, and the whole file could pass both checks below. + assertTrue("aboutRows is not declared where this test reads it", declaration in screen) + val about = screen.substringAfter(declaration) .substringBefore("\nprivate fun ") assertTrue( From 2196f6d2da2ef3179366c24576dd2187cf790ece Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 13:19:33 +0300 Subject: [PATCH 02/43] Give the calendar's header, grids, agenda, filters and day panel files of their own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WeekScreen.kt had grown to 1329 lines. The two layouts of the tab — the scrolling column and the «День» page — were the first four hundred of them, and the rest was every part either layout draws: the header and its arrows, the week strip and the month grid, the month as a list, the filter chips, and the panel under the grid with its empty states. Each of those is now a sibling in the same package — ScheduleHeader, CalendarGrids (the strip and the grid together, because both draw the same load dots and those stay private to the one file), AgendaList, FilterChips and DayPanel — and WeekScreen.kt keeps the two layouts and the labels only they use. Moved verbatim, comments included. WeekdaySelector, MonthGrid, AgendaList, FilterChips, DayPanel and DayChips go from private to internal because the layouts that call them are now in another file; everything else keeps its visibility. Four imports the old file never used, and one that only a lambda parameter's name matched, were not carried over. Refs #209 Co-Authored-By: Claude Opus 5.5 --- .../lessons/ui/week/AgendaList.kt | 214 +++++ .../lessons/ui/week/CalendarGrids.kt | 338 +++++++ .../lumenpearson/lessons/ui/week/DayPanel.kt | 190 ++++ .../lessons/ui/week/FilterChips.kt | 65 ++ .../lessons/ui/week/ScheduleHeader.kt | 163 ++++ .../lessons/ui/week/WeekScreen.kt | 875 ------------------ 6 files changed, 970 insertions(+), 875 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/AgendaList.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/CalendarGrids.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/DayPanel.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/FilterChips.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/ScheduleHeader.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/AgendaList.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/AgendaList.kt new file mode 100644 index 00000000..31a39362 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/AgendaList.kt @@ -0,0 +1,214 @@ +package com.lumenpearson.lessons.ui.week + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.EmptyState +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.LessonsShapeTokens +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.designsystem.theme.emphasised +import com.lumenpearson.lessons.core.designsystem.theme.rowContainer +import com.lumenpearson.lessons.core.model.DayKind +import com.lumenpearson.lessons.core.model.DayFilter +import com.lumenpearson.lessons.core.model.DayOrder +import com.lumenpearson.lessons.core.model.SchoolDay +import com.lumenpearson.lessons.ui.common.asShortWeekday +import java.time.LocalDate + +/** + * A month as a list, and the only view an order can apply to. + * + * Filtered days are dropped here rather than dimmed, which is the opposite of + * the grid and right for the same reason: a list has no shape to preserve, so + * a day that does not match is a row worth not drawing. The grid keeps its + * holes filled because a month with gaps stops lining up with its own header. + * + * Empty is a real answer and says which kind it is — a month with nothing in + * it at all reads differently from one where the filter is hiding everything, + * and telling somebody «ничего не найдено» when they have narrowed to «с ДЗ» + * in July would be blaming the month for the chip. + * + * Four kinds, not two, and for a long time it drew one. The same distinction + * the month grid and the ribbon already make: an empty list here is a year + * nobody has asked for, a year on its way, a month the filters have emptied, + * or a month that is genuinely blank — and the one sentence it had blamed the + * chips for all four, including a fresh install with no filter set at all. + * `days` cannot tell them apart on its own, which is why the other three + * arrive beside it. + */ +@Composable +internal fun AgendaList( + days: List, + today: LocalDate, + selected: LocalDate, + order: DayOrder, + /** The chips currently narrowing the month; empty is nobody's fault. */ + filters: Set, + /** Whether the month's school year is in the cache at all. */ + isFetched: Boolean, + /** Whether a fetch of it is in flight right now. */ + loadingYear: Boolean, + /** «2026/27», for the sentence that names the year being waited on. */ + yearName: String, + onOrder: (DayOrder) -> Unit, + onOpen: (LocalDate) -> Unit, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = ScreenPadding), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + DayOrder.entries.forEach { candidate -> + PillChip( + text = candidate.asLabel(), + selected = candidate == order, + onClick = { onOrder(candidate) }, + ) + } + } + + if (days.isEmpty()) { + EmptyState( + title = correctedString( + when { + !isFetched && loadingYear -> R.string.week_year_loading_title + !isFetched -> R.string.week_year_missing_title + filters.isEmpty() -> R.string.calendar_agenda_blank_title + else -> R.string.calendar_agenda_empty_title + }, + ), + description = if (!isFetched) { + correctedString( + if (loadingYear) { + R.string.week_year_loading_description + } else { + R.string.week_year_missing_description + }, + yearName, + ) + } else { + correctedString( + if (filters.isEmpty()) { + R.string.calendar_agenda_blank_description + } else { + R.string.calendar_agenda_empty_description + }, + ) + }, + ) + return@Column + } + + days.forEach { day -> + AgendaRow( + day = day, + isToday = day.date == today, + isSelected = day.date == selected, + onClick = { onOpen(day.date) }, + ) + } + } +} + +/** One day of the agenda: what it is, and how much of it there is. */ +@Composable +private fun AgendaRow( + day: SchoolDay, + isToday: Boolean, + isSelected: Boolean, + onClick: () -> Unit, +) { + val scheme = MaterialTheme.colorScheme + val accent = day.agendaAccent() + val accentColors = accent.colors() + val container = when { + isToday -> scheme.secondaryContainer + isSelected -> scheme.rowContainer + else -> accentColors.container + } + val content = when { + isToday -> scheme.onSecondaryContainer + isSelected -> scheme.onSurface + else -> accentColors.content + } + + Row( + modifier = Modifier + .fillMaxWidth() + .clip(LessonsShapeTokens.Row) + .background(container) + .clickable(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "${day.date.dayOfMonth} · ${day.date.asShortWeekday()}", + style = MaterialTheme.typography.titleSmall.emphasised(isToday), + color = content, + ) + val subtitle = day.holiday?.title + ?: day.kind.takeIf { it != DayKind.NORMAL }?.asLabel() + ?: day.offReason.takeIf { !day.hasLessons }?.asEmptyDescription() + if (subtitle != null) { + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = content.copy(alpha = 0.75f), + ) + } + } + Text( + text = pluralStringResource( + R.plurals.lessons_count, + day.activeLessons.size, + day.activeLessons.size, + ), + style = MaterialTheme.typography.labelMedium, + color = content.copy(alpha = 0.75f), + ) + } +} + +/** The accent an agenda row carries — the same vocabulary the grid uses. */ +private fun SchoolDay.agendaAccent(): DayAccent = WeekDayUi( + date = date, + day = this, + isToday = false, +).accent() + +/** What each order is called, out of resources so both languages have it. */ +@Composable +internal fun DayOrder.asLabel(): String = correctedString( + when (this) { + DayOrder.DATE_ASC -> R.string.calendar_order_date_asc + DayOrder.DATE_DESC -> R.string.calendar_order_date_desc + DayOrder.BUSIEST_FIRST -> R.string.calendar_order_busiest + }, +) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/CalendarGrids.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/CalendarGrids.kt new file mode 100644 index 00000000..13d03c2c --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/CalendarGrids.kt @@ -0,0 +1,338 @@ +package com.lumenpearson.lessons.ui.week + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.LessonsShapeTokens +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.designsystem.theme.emphasised +import com.lumenpearson.lessons.core.designsystem.theme.rowContainer +import com.lumenpearson.lessons.core.model.DayOffReason +import com.lumenpearson.lessons.ui.common.asShortWeekday +import java.time.LocalDate + +/** + * The week strip. + * + * Seven tiles need about 400 dp and a phone has 360, so the last day or two + * start off-screen; without the scroll-to below, the row never moved and the + * selected chip could not be seen at all. Five tiles — weekends hidden — fit, + * and the scroll-to costs nothing when there is nowhere to scroll. + */ +@Composable +internal fun WeekdaySelector( + days: List, + selected: LocalDate, + showLoad: Boolean, + onSelect: (LocalDate) -> Unit, + modifier: Modifier = Modifier, +) { + val listState = rememberLazyListState() + val selectedIndex = days.indexOfFirst { it.date == selected } + LaunchedEffect(selectedIndex, days.size) { + if (selectedIndex >= 0) listState.animateScrollToItem(selectedIndex) + } + + LazyRow( + state = listState, + modifier = modifier.fillMaxWidth(), + contentPadding = PaddingValues(horizontal = ScreenPadding), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + itemsIndexed(items = days, key = { _, day -> day.date.toString() }) { _, day -> + WeekdayTile( + weekday = day.date.asShortWeekday(), + dayOfMonth = day.date.dayOfMonth.toString(), + lessonCount = if (showLoad) day.day?.activeLessons?.size ?: 0 else 0, + selected = day.date == selected, + isToday = day.isToday, + onClick = { onSelect(day.date) }, + ) + } + } +} + +/** + * One day of the strip: the weekday over the date, in a rounded tile. + * + * Two lines rather than one chip because "чт" alone is ambiguous the moment the + * user steps away from the current week. + */ +@Composable +private fun WeekdayTile( + weekday: String, + dayOfMonth: String, + lessonCount: Int, + selected: Boolean, + isToday: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val scheme = MaterialTheme.colorScheme + val container = if (selected) scheme.primary else scheme.rowContainer + val content = if (selected) scheme.onPrimary else scheme.onSurfaceVariant + + Column( + modifier = modifier + .clip(LessonsShapeTokens.Row) + .background(container) + .clickable(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 10.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + text = weekday, + style = MaterialTheme.typography.labelSmall, + color = content, + ) + Text( + text = dayOfMonth, + // Bold for the day in view and for today, which has no fill of its + // own in the strip and would otherwise carry no mark at all. + style = MaterialTheme.typography.titleMedium.emphasised(selected || isToday), + color = if (selected) scheme.onPrimary else scheme.onSurface, + ) + LoadDots( + count = lessonCount, + color = if (selected) scheme.onPrimary else scheme.primary, + ) + } +} + +/** + * How busy a day is, as up to three dots. + * + * A number would be read; dots are seen. Three is the cap because the difference + * that matters in a grid is none / a few / a full day, and a fourth dot only + * makes the cell taller. + */ +@Composable +private fun LoadDots( + count: Int, + color: Color, + modifier: Modifier = Modifier, +) { + val dots = count.coerceAtMost(MaxLoadDots) + Row( + modifier = modifier.height(DotSize), + horizontalArrangement = Arrangement.spacedBy(3.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + repeat(dots) { + Box( + modifier = Modifier + .size(DotSize) + .clip(androidx.compose.foundation.shape.CircleShape) + .background(color), + ) + } + } +} + +private const val MaxLoadDots = 3 +private val DotSize: Dp = 4.dp + +/** + * A month as a seven-column grid. + * + * The corners are filled with the neighbouring months' days rather than left + * blank: a grid that starts mid-row is harder to read than one that does not, + * and a blank cell is a cell nobody can tap. They are drawn faint, and tapping + * one steps the month rather than selecting a date the grid does not own. + * + * A tap selects; a second tap on the same day opens its sheet. One gesture for + * "show me this day below" and one for "show me everything", which is what the + * month view is for — the grid itself has room for a number and three dots. + */ +@Composable +internal fun MonthGrid( + days: List, + selected: LocalDate, + showLoad: Boolean, + onSelect: (LocalDate) -> Unit, + onOpen: (LocalDate) -> Unit, + modifier: Modifier = Modifier, +) { + val scheme = MaterialTheme.colorScheme + // Computed over the whole month rather than per row, so a stretch that + // wraps from Sunday to Monday is one run and draws as one bar. + val accents = remember(days) { days.map { it.accent() } } + val runs = remember(accents) { accents.runPositions() } + val weeks = remember(days) { days.indices.toList().chunked(DaysPerRow) } + + // A whole month with nothing in it is a month somebody scrolls past, and + // sixty faintly-tinted cells do not say what they are. The label does. + // Only when *every* day of the month agrees: one September day at the + // bottom of an August grid means the year has started, and writing + // «Летние каникулы» across it would be wrong about the day that matters. + val wholeMonthOff = remember(days, accents) { + val inMonth = days.indices.filter { days[it].inPeriod } + inMonth.isNotEmpty() && inMonth.all { + accents[it] == DayAccent.OUT_OF_YEAR || accents[it] == DayAccent.BETWEEN_TERMS + } + } + val bannerText = when { + !wholeMonthOff -> null + days.any { it.inPeriod && it.day?.offReason == DayOffReason.OUT_OF_YEAR } -> + correctedString(R.string.calendar_year_over) + else -> correctedString(R.string.calendar_between_terms) + } + + Box(modifier = modifier.fillMaxWidth()) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = ScreenPadding), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + days.take(DaysPerRow).forEach { day -> + Text( + text = day.date.asShortWeekday(), + style = MaterialTheme.typography.labelSmall, + color = scheme.outline, + textAlign = TextAlign.Center, + modifier = Modifier.weight(1f), + ) + } + } + + weeks.forEach { week -> + // Zero spacing inside a run, so the cells of one stretch touch and + // read as a single bar; the 4.dp gap is drawn by the cell instead, + // on the sides where its run actually ends. + Row(horizontalArrangement = Arrangement.spacedBy(0.dp)) { + week.forEach { index -> + val day = days[index] + MonthCell( + day = day, + accent = accents[index], + run = runs[index], + selected = day.date == selected, + showLoad = showLoad, + onClick = { + if (day.date == selected) onOpen(day.date) else onSelect(day.date) + }, + modifier = Modifier.weight(1f), + ) + } + } + } + } + + if (bannerText != null) { + Box( + modifier = Modifier + .matchParentSize() + .padding(horizontal = ScreenPadding), + contentAlignment = Alignment.Center, + ) { + Text( + text = bannerText, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onTertiaryContainer, + textAlign = TextAlign.Center, + modifier = Modifier + .clip(LessonsShapeTokens.Row) + .background(MaterialTheme.colorScheme.tertiaryContainer) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } + } +} + +private const val DaysPerRow = 7 + +/** One cell of the month grid. */ +@Composable +private fun MonthCell( + day: WeekDayUi, + accent: DayAccent, + run: RunPosition, + selected: Boolean, + showLoad: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val scheme = MaterialTheme.colorScheme + val accentColors = accent.colors() + val container = when { + selected -> scheme.primary + day.isToday -> scheme.secondaryContainer + day.inPeriod -> accentColors.container + else -> Color.Transparent + } + val content = when { + selected -> scheme.onPrimary + day.isToday -> scheme.onSecondaryContainer + day.inPeriod -> accentColors.content + else -> scheme.outline + } + // A selected day is its own shape: it is one cell being pointed at, and + // squaring its corners to join a run would lose the one thing the + // selection is for. + val shape = if (selected || day.isToday) LessonsShapeTokens.Row else run.shape() + + // Filtered out: dimmed, never removed. A grid with holes in it stops + // lining up with its own weekday header. Today and the selection keep + // their full weight either way — the filter narrows what is interesting, + // it does not move where you are. + val dimmed = !day.matchesFilters && !selected && !day.isToday + + Column( + modifier = modifier + // The gap the Row used to space with, moved here so it can be left + // out between two cells of the same run. + .padding( + start = if (run.first || selected || day.isToday) 2.dp else 0.dp, + end = if (run.last || selected || day.isToday) 2.dp else 0.dp, + ) + .clip(shape) + .background(if (dimmed) container.copy(alpha = 0.25f) else container) + .clickable(onClick = onClick) + .padding(vertical = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + text = day.date.dayOfMonth.toString(), + style = MaterialTheme.typography.bodyMedium.emphasised(selected || day.isToday), + color = if (dimmed) content.copy(alpha = 0.38f) else content, + ) + LoadDots( + count = if (showLoad) day.day?.activeLessons?.size ?: 0 else 0, + color = when { + selected -> scheme.onPrimary + dimmed -> scheme.primary.copy(alpha = 0.3f) + else -> scheme.primary + }, + ) + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/DayPanel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/DayPanel.kt new file mode 100644 index 00000000..95e65e58 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/DayPanel.kt @@ -0,0 +1,190 @@ +package com.lumenpearson.lessons.ui.week + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.EmptyState +import com.lumenpearson.lessons.core.designsystem.component.LessonGroup +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.model.DayKind +import com.lumenpearson.lessons.core.model.Lesson +import com.lumenpearson.lessons.core.model.SchoolYear +import com.lumenpearson.lessons.core.model.DayOffReason +import com.lumenpearson.lessons.ui.common.asDayMonth +import com.lumenpearson.lessons.ui.common.asFullWeekday +import java.time.LocalDate + +/** The detail under the week strip or the month grid. */ +@Composable +internal fun DayPanel( + day: WeekDayUi?, + date: LocalDate, + /** Whether a fetch of this date's school year is in flight right now. */ + loadingYear: Boolean, + showTeacher: Boolean, + showEvents: Boolean, + showHomework: Boolean, + onLessonClick: (Lesson) -> Unit, + onOpenDay: () -> Unit, + modifier: Modifier = Modifier, +) { + val schoolDay = day?.day + val lessons = schoolDay?.activeLessons.orEmpty() + + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = ScreenPadding), + verticalArrangement = Arrangement.spacedBy(GroupSpacing), + ) { + SectionHeader( + title = "${date.asFullWeekday().replaceFirstChar { it.uppercase() }}, " + + date.asDayMonth(), + subtitle = schoolDay?.let { + pluralStringResource( + R.plurals.lessons_count, + it.activeLessons.size, + it.activeLessons.size, + ) + }, + actionLabel = schoolDay?.let { correctedString(R.string.schedule_day_details) }, + onActionClick = schoolDay?.let { { onOpenDay() } }, + ) + + DayChips(day = day, date = date) + + when { + // Three ways to be empty, and they were one until the cache learned + // to hold more than a year. «Нет данных» about a year nobody has + // asked for is a timetable that looks like it stops; «загружаю» is + // the same screen with the truth on it. + schoolDay == null && day?.isFetched == false -> EmptyState( + title = correctedString( + if (loadingYear) { + R.string.week_year_loading_title + } else { + R.string.week_year_missing_title + }, + ), + description = correctedString( + if (loadingYear) { + R.string.week_year_loading_description + } else { + R.string.week_year_missing_description + }, + yearLabel(SchoolYear.openingYearOf(date)), + ), + ) + + schoolDay == null -> EmptyState( + title = correctedString(R.string.week_no_data_title), + description = correctedString(R.string.week_no_data_description), + ) + + lessons.isEmpty() -> EmptyState( + title = correctedString(R.string.week_day_off_title), + description = schoolDay.offReason.asEmptyDescription(), + ) + + else -> LessonGroup( + lessons = lessons, + now = null, + showTeacher = showTeacher, + onLessonClick = onLessonClick, + ) + } + + DayExtras( + day = schoolDay, + showEvents = showEvents, + showHomework = showHomework, + ) + } +} + +/** Today / kind / note, as a row of pills. */ +@Composable +internal fun DayChips( + day: WeekDayUi?, + date: LocalDate, + modifier: Modifier = Modifier, +) { + val kind = day?.day?.kind?.takeIf { it != DayKind.NORMAL } + val note = day?.day?.note + val holiday = day?.day?.holiday + val isToday = day?.isToday == true + if (!isToday && kind == null && note == null && holiday == null) return + + Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (isToday) { + PillChip( + text = correctedString(R.string.day_today), + selected = true, + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + ) + } + if (holiday != null) { + // The server's own words. A date this build has never heard of + // still has a name, which is the whole reason the title travels + // beside the code rather than the code travelling alone. + PillChip( + text = holiday.title, + containerColor = if (holiday.stopsLessons) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.tertiaryContainer + }, + contentColor = if (holiday.stopsLessons) { + MaterialTheme.colorScheme.onErrorContainer + } else { + MaterialTheme.colorScheme.onTertiaryContainer + }, + ) + } + if (kind != null) PillChip(text = kind.asLabel()) + if (note != null) PillChip(text = note) + } +} + +/** + * Why this day is empty, in words somebody can act on. + * + * «Уроков нет» is true of four different days and useful on one. A blank + * Tuesday in November is the holidays, a public holiday, or a timetable with + * nothing on it, and those are three different things to do next. + */ +@Composable +internal fun DayOffReason?.asEmptyDescription(): String = correctedString( + when (this) { + DayOffReason.OUT_OF_YEAR -> R.string.week_day_off_year_over + DayOffReason.BETWEEN_TERMS -> R.string.week_day_off_between_terms + DayOffReason.PUBLIC_HOLIDAY -> R.string.week_day_off_public_holiday + null -> R.string.week_day_off_description + }, +) + +/** Localized name of a non-normal day kind. */ +@Composable +internal fun DayKind.asLabel(): String = correctedString( + when (this) { + DayKind.NORMAL -> R.string.day_kind_normal + DayKind.HOLIDAY -> R.string.day_kind_holiday + DayKind.SHORTENED -> R.string.day_kind_shortened + DayKind.REMOTE -> R.string.day_kind_remote + DayKind.SELF_STUDY -> R.string.day_kind_self_study + DayKind.DAY_OFF -> R.string.day_kind_day_off + }, +) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/FilterChips.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/FilterChips.kt new file mode 100644 index 00000000..2541e718 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/FilterChips.kt @@ -0,0 +1,65 @@ +package com.lumenpearson.lessons.ui.week + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.model.DayFilter + +/** + * The four facets, as chips over whatever the calendar is drawing. + * + * Horizontally scrollable rather than wrapped onto two rows: four Russian + * labels do not fit one phone width, and a row that grows taller when a filter + * is on moves the grid under the reader's thumb at the moment they press. + * + * «Сбросить» appears only when something is on. A permanent clear button on a + * calendar nobody has filtered is a button that does nothing, and the row is + * already competing with the grid for attention. + */ +@Composable +internal fun FilterChips( + active: Set, + onToggle: (DayFilter) -> Unit, + onClear: () -> Unit, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = ScreenPadding), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + DayFilter.entries.forEach { filter -> + PillChip( + text = filter.asLabel(), + selected = filter in active, + onClick = { onToggle(filter) }, + ) + } + if (active.isNotEmpty()) { + PillChip(text = correctedString(R.string.calendar_filter_clear), onClick = onClear) + } + } +} + +/** What each facet is called, out of resources so both languages have it. */ +@Composable +internal fun DayFilter.asLabel(): String = correctedString( + when (this) { + DayFilter.HAS_LESSONS -> R.string.calendar_filter_lessons + DayFilter.HAS_HOMEWORK -> R.string.calendar_filter_homework + DayFilter.HAS_EVENTS -> R.string.calendar_filter_events + DayFilter.MARKED -> R.string.calendar_filter_marked + }, +) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/ScheduleHeader.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/ScheduleHeader.kt new file mode 100644 index 00000000..1303c147 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/ScheduleHeader.kt @@ -0,0 +1,163 @@ +package com.lumenpearson.lessons.ui.week + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.ChevronLeft +import androidx.compose.material.icons.rounded.ChevronRight +import androidx.compose.material.icons.rounded.Today +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding + +/** What «назад» announces, for the unit this press actually moves. */ +private val PeriodStep.previousRes: Int + get() = when (this) { + PeriodStep.DAY -> R.string.day_previous + PeriodStep.WEEK -> R.string.week_previous + PeriodStep.MONTH -> R.string.month_previous + } + +/** What «вперёд» announces. @see previousRes */ +private val PeriodStep.nextRes: Int + get() = when (this) { + PeriodStep.DAY -> R.string.day_next + PeriodStep.WEEK -> R.string.week_next + PeriodStep.MONTH -> R.string.month_next + } + +/** What «вернуться к сегодня» announces. @see previousRes */ +private val PeriodStep.currentRes: Int + get() = when (this) { + PeriodStep.DAY -> R.string.day_current + PeriodStep.WEEK -> R.string.week_current + PeriodStep.MONTH -> R.string.month_current + } + +/** + * The page title and the three period controls. + * + * The controls used to be actions in a top app bar. They are here because there + * is no top app bar any more, and because the top-right corner of a 6.7 inch + * phone was a poor place for the one pair of buttons on this screen that + * anybody presses repeatedly. + */ +@Composable +internal fun ScheduleHeader( + periodLabel: String, + termLabel: String?, + yearLabel: String, + /** What one press of an arrow moves — and so what it announces. */ + step: PeriodStep, + showTodayAction: Boolean, + onToday: () -> Unit, + onPrevious: () -> Unit, + onNext: () -> Unit, + onPickYear: () -> Unit, + modifier: Modifier = Modifier, +) { + // Two rows, not one, and that is the whole fix. While the title shared a + // row with the chip and three icon buttons it was given what was left — + // about eight characters at 411 dp — so «Календарь» wrapped after + // «Календар» and the subtitle ran to three lines. Nothing about it looks + // wrong in the code: `weight(1f)` is the correct way to share a row, and + // the row was simply asked to hold more than it has. + // + // On its own row the title has the screen's width, which is more than any + // title here will ever need, and the controls below have the width they + // need rather than the width that is left. + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = ScreenPadding), + ) { + ScreenHeader( + title = correctedString(R.string.week_title), + // «Октябрь 2026 · 1 четверть». One line rather than two: the term + // qualifies the period rather than standing beside it, and a second + // line pushes the grid down on every phone for a word. It is asked + // for explicitly now — the header wraps a subtitle by default, + // because `DocsScreen` puts a whole sentence there. + subtitle = listOfNotNull(periodLabel, termLabel).joinToString(" · "), + singleLineSubtitle = true, + ) + Row( + modifier = Modifier + .fillMaxWidth() + // Level with the header's own text, which insets itself by 8. + .padding(start = 8.dp, end = 8.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + // The school year, and the way into the years either side of it. A + // chip rather than a third pair of arrows: the arrows step the + // *period*, which is a week here and a month there, and a second + // pair meaning «year» beside them is two controls that look the + // same and are not. + PillChip( + text = yearLabel, + onClick = onPickYear, + ) + Spacer(Modifier.weight(1f)) + // The slot is always here; only the button inside it comes and + // goes. «Вернуться к сегодня» is offered only when it would do + // something — a button for a period that already contains today is + // noise — but while the button itself was the thing that appeared, + // both arrows slid sideways by 48 dp every time the reader stepped + // into or out of this week. A control that moves under the thumb + // between two presses is worse than a gap. + Box( + modifier = Modifier.size(IconButtonSlot), + contentAlignment = Alignment.Center, + ) { + if (showTodayAction) { + IconButton(onClick = onToday) { + Icon( + imageVector = Icons.Rounded.Today, + contentDescription = correctedString(step.currentRes), + ) + } + } + } + // From [step], not from `R.string.week_*`. These three are the only + // part of the header a sighted reader never sees, which is how they + // went on saying «неделя» in four of the five modes long after the + // text above them learned to name the day or the month. + IconButton(onClick = onPrevious) { + Icon( + imageVector = Icons.Rounded.ChevronLeft, + contentDescription = correctedString(step.previousRes), + ) + } + IconButton(onClick = onNext) { + Icon( + imageVector = Icons.Rounded.ChevronRight, + contentDescription = correctedString(step.nextRes), + ) + } + } + } +} + +/** + * The side of the square an [IconButton] occupies, so a slot can be kept for + * one that is not there. + * + * Material's own minimum touch target, which is what `IconButton` sizes itself + * to; named here rather than written as `48.dp` at the one place that needs it, + * because the number is only correct as long as it is the same number. + */ +private val IconButtonSlot: Dp = 48.dp diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/WeekScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/WeekScreen.kt index 5b8593ad..3fcdbffa 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/WeekScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/week/WeekScreen.kt @@ -8,90 +8,47 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.ScrollState -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.LazyRow -import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.rounded.ChevronLeft -import androidx.compose.material.icons.rounded.ChevronRight -import androidx.compose.material.icons.rounded.Today -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R -import com.lumenpearson.lessons.core.designsystem.component.EmptyState -import com.lumenpearson.lessons.core.designsystem.component.LessonGroup -import com.lumenpearson.lessons.core.designsystem.component.PillChip -import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader -import com.lumenpearson.lessons.core.designsystem.component.SectionHeader import com.lumenpearson.lessons.core.designsystem.component.SegmentedPicker -import com.lumenpearson.lessons.core.designsystem.text.MarqueeText -import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing -import com.lumenpearson.lessons.core.designsystem.theme.LessonsShapeTokens import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace import com.lumenpearson.lessons.core.designsystem.theme.ReportScrollOffset import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur -import com.lumenpearson.lessons.core.designsystem.theme.emphasised import com.lumenpearson.lessons.core.designsystem.theme.rowContainer import com.lumenpearson.lessons.core.designsystem.theme.statusBarSpace -import com.lumenpearson.lessons.core.designsystem.theme.subjectTone -import com.lumenpearson.lessons.core.model.DayKind import com.lumenpearson.lessons.core.model.Lesson import com.lumenpearson.lessons.core.model.SchoolYear import com.lumenpearson.lessons.core.model.Term -import com.lumenpearson.lessons.core.model.DayFilter import com.lumenpearson.lessons.core.model.DayMode -import com.lumenpearson.lessons.core.model.DayOrder import com.lumenpearson.lessons.core.model.SchoolDay -import com.lumenpearson.lessons.core.model.DayOffReason import com.lumenpearson.lessons.core.model.TermKind import com.lumenpearson.lessons.ui.common.asDayMonth import com.lumenpearson.lessons.ui.common.asFullWeekday import com.lumenpearson.lessons.ui.common.asMonthYear -import com.lumenpearson.lessons.ui.common.asShortWeekday import com.lumenpearson.lessons.ui.day.DayRibbonView import com.lumenpearson.lessons.ui.day.RibbonSettingsSheet import java.time.LocalDate -import java.util.Locale /** * The calendar tab: the same timetable at three scales. @@ -421,30 +378,6 @@ internal fun RibbonPage( } } -/** What «назад» announces, for the unit this press actually moves. */ -private val PeriodStep.previousRes: Int - get() = when (this) { - PeriodStep.DAY -> R.string.day_previous - PeriodStep.WEEK -> R.string.week_previous - PeriodStep.MONTH -> R.string.month_previous - } - -/** What «вперёд» announces. @see previousRes */ -private val PeriodStep.nextRes: Int - get() = when (this) { - PeriodStep.DAY -> R.string.day_next - PeriodStep.WEEK -> R.string.week_next - PeriodStep.MONTH -> R.string.month_next - } - -/** What «вернуться к сегодня» announces. @see previousRes */ -private val PeriodStep.currentRes: Int - get() = when (this) { - PeriodStep.DAY -> R.string.day_current - PeriodStep.WEEK -> R.string.week_current - PeriodStep.MONTH -> R.string.month_current - } - /** Label of a day mode in the picker inside «День». */ private val DayMode.labelRes: Int get() = when (this) { @@ -519,811 +452,3 @@ internal fun Term.label(): String = when (kind) { TermKind.QUARTER -> correctedString(R.string.term_quarter, index) TermKind.SEMESTER -> correctedString(R.string.term_semester, index) } - -/** - * The page title and the three period controls. - * - * The controls used to be actions in a top app bar. They are here because there - * is no top app bar any more, and because the top-right corner of a 6.7 inch - * phone was a poor place for the one pair of buttons on this screen that - * anybody presses repeatedly. - */ -@Composable -internal fun ScheduleHeader( - periodLabel: String, - termLabel: String?, - yearLabel: String, - /** What one press of an arrow moves — and so what it announces. */ - step: PeriodStep, - showTodayAction: Boolean, - onToday: () -> Unit, - onPrevious: () -> Unit, - onNext: () -> Unit, - onPickYear: () -> Unit, - modifier: Modifier = Modifier, -) { - // Two rows, not one, and that is the whole fix. While the title shared a - // row with the chip and three icon buttons it was given what was left — - // about eight characters at 411 dp — so «Календарь» wrapped after - // «Календар» and the subtitle ran to three lines. Nothing about it looks - // wrong in the code: `weight(1f)` is the correct way to share a row, and - // the row was simply asked to hold more than it has. - // - // On its own row the title has the screen's width, which is more than any - // title here will ever need, and the controls below have the width they - // need rather than the width that is left. - Column( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = ScreenPadding), - ) { - ScreenHeader( - title = correctedString(R.string.week_title), - // «Октябрь 2026 · 1 четверть». One line rather than two: the term - // qualifies the period rather than standing beside it, and a second - // line pushes the grid down on every phone for a word. It is asked - // for explicitly now — the header wraps a subtitle by default, - // because `DocsScreen` puts a whole sentence there. - subtitle = listOfNotNull(periodLabel, termLabel).joinToString(" · "), - singleLineSubtitle = true, - ) - Row( - modifier = Modifier - .fillMaxWidth() - // Level with the header's own text, which insets itself by 8. - .padding(start = 8.dp, end = 8.dp, bottom = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - // The school year, and the way into the years either side of it. A - // chip rather than a third pair of arrows: the arrows step the - // *period*, which is a week here and a month there, and a second - // pair meaning «year» beside them is two controls that look the - // same and are not. - PillChip( - text = yearLabel, - onClick = onPickYear, - ) - Spacer(Modifier.weight(1f)) - // The slot is always here; only the button inside it comes and - // goes. «Вернуться к сегодня» is offered only when it would do - // something — a button for a period that already contains today is - // noise — but while the button itself was the thing that appeared, - // both arrows slid sideways by 48 dp every time the reader stepped - // into or out of this week. A control that moves under the thumb - // between two presses is worse than a gap. - Box( - modifier = Modifier.size(IconButtonSlot), - contentAlignment = Alignment.Center, - ) { - if (showTodayAction) { - IconButton(onClick = onToday) { - Icon( - imageVector = Icons.Rounded.Today, - contentDescription = correctedString(step.currentRes), - ) - } - } - } - // From [step], not from `R.string.week_*`. These three are the only - // part of the header a sighted reader never sees, which is how they - // went on saying «неделя» in four of the five modes long after the - // text above them learned to name the day or the month. - IconButton(onClick = onPrevious) { - Icon( - imageVector = Icons.Rounded.ChevronLeft, - contentDescription = correctedString(step.previousRes), - ) - } - IconButton(onClick = onNext) { - Icon( - imageVector = Icons.Rounded.ChevronRight, - contentDescription = correctedString(step.nextRes), - ) - } - } - } -} - -/** - * The side of the square an [IconButton] occupies, so a slot can be kept for - * one that is not there. - * - * Material's own minimum touch target, which is what `IconButton` sizes itself - * to; named here rather than written as `48.dp` at the one place that needs it, - * because the number is only correct as long as it is the same number. - */ -private val IconButtonSlot: Dp = 48.dp - -/** - * The week strip. - * - * Seven tiles need about 400 dp and a phone has 360, so the last day or two - * start off-screen; without the scroll-to below, the row never moved and the - * selected chip could not be seen at all. Five tiles — weekends hidden — fit, - * and the scroll-to costs nothing when there is nowhere to scroll. - */ -@Composable -private fun WeekdaySelector( - days: List, - selected: LocalDate, - showLoad: Boolean, - onSelect: (LocalDate) -> Unit, - modifier: Modifier = Modifier, -) { - val listState = rememberLazyListState() - val selectedIndex = days.indexOfFirst { it.date == selected } - LaunchedEffect(selectedIndex, days.size) { - if (selectedIndex >= 0) listState.animateScrollToItem(selectedIndex) - } - - LazyRow( - state = listState, - modifier = modifier.fillMaxWidth(), - contentPadding = PaddingValues(horizontal = ScreenPadding), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - itemsIndexed(items = days, key = { _, day -> day.date.toString() }) { _, day -> - WeekdayTile( - weekday = day.date.asShortWeekday(), - dayOfMonth = day.date.dayOfMonth.toString(), - lessonCount = if (showLoad) day.day?.activeLessons?.size ?: 0 else 0, - selected = day.date == selected, - isToday = day.isToday, - onClick = { onSelect(day.date) }, - ) - } - } -} - -/** - * One day of the strip: the weekday over the date, in a rounded tile. - * - * Two lines rather than one chip because "чт" alone is ambiguous the moment the - * user steps away from the current week. - */ -@Composable -private fun WeekdayTile( - weekday: String, - dayOfMonth: String, - lessonCount: Int, - selected: Boolean, - isToday: Boolean, - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - val scheme = MaterialTheme.colorScheme - val container = if (selected) scheme.primary else scheme.rowContainer - val content = if (selected) scheme.onPrimary else scheme.onSurfaceVariant - - Column( - modifier = modifier - .clip(LessonsShapeTokens.Row) - .background(container) - .clickable(onClick = onClick) - .padding(horizontal = 14.dp, vertical = 10.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - text = weekday, - style = MaterialTheme.typography.labelSmall, - color = content, - ) - Text( - text = dayOfMonth, - // Bold for the day in view and for today, which has no fill of its - // own in the strip and would otherwise carry no mark at all. - style = MaterialTheme.typography.titleMedium.emphasised(selected || isToday), - color = if (selected) scheme.onPrimary else scheme.onSurface, - ) - LoadDots( - count = lessonCount, - color = if (selected) scheme.onPrimary else scheme.primary, - ) - } -} - -/** - * How busy a day is, as up to three dots. - * - * A number would be read; dots are seen. Three is the cap because the difference - * that matters in a grid is none / a few / a full day, and a fourth dot only - * makes the cell taller. - */ -@Composable -private fun LoadDots( - count: Int, - color: Color, - modifier: Modifier = Modifier, -) { - val dots = count.coerceAtMost(MaxLoadDots) - Row( - modifier = modifier.height(DotSize), - horizontalArrangement = Arrangement.spacedBy(3.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - repeat(dots) { - Box( - modifier = Modifier - .size(DotSize) - .clip(androidx.compose.foundation.shape.CircleShape) - .background(color), - ) - } - } -} - -private const val MaxLoadDots = 3 -private val DotSize: Dp = 4.dp - -/** - * A month as a seven-column grid. - * - * The corners are filled with the neighbouring months' days rather than left - * blank: a grid that starts mid-row is harder to read than one that does not, - * and a blank cell is a cell nobody can tap. They are drawn faint, and tapping - * one steps the month rather than selecting a date the grid does not own. - * - * A tap selects; a second tap on the same day opens its sheet. One gesture for - * "show me this day below" and one for "show me everything", which is what the - * month view is for — the grid itself has room for a number and three dots. - */ -@Composable -private fun MonthGrid( - days: List, - selected: LocalDate, - showLoad: Boolean, - onSelect: (LocalDate) -> Unit, - onOpen: (LocalDate) -> Unit, - modifier: Modifier = Modifier, -) { - val scheme = MaterialTheme.colorScheme - // Computed over the whole month rather than per row, so a stretch that - // wraps from Sunday to Monday is one run and draws as one bar. - val accents = remember(days) { days.map { it.accent() } } - val runs = remember(accents) { accents.runPositions() } - val weeks = remember(days) { days.indices.toList().chunked(DaysPerRow) } - - // A whole month with nothing in it is a month somebody scrolls past, and - // sixty faintly-tinted cells do not say what they are. The label does. - // Only when *every* day of the month agrees: one September day at the - // bottom of an August grid means the year has started, and writing - // «Летние каникулы» across it would be wrong about the day that matters. - val wholeMonthOff = remember(days, accents) { - val inMonth = days.indices.filter { days[it].inPeriod } - inMonth.isNotEmpty() && inMonth.all { - accents[it] == DayAccent.OUT_OF_YEAR || accents[it] == DayAccent.BETWEEN_TERMS - } - } - val bannerText = when { - !wholeMonthOff -> null - days.any { it.inPeriod && it.day?.offReason == DayOffReason.OUT_OF_YEAR } -> - correctedString(R.string.calendar_year_over) - else -> correctedString(R.string.calendar_between_terms) - } - - Box(modifier = modifier.fillMaxWidth()) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = ScreenPadding), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { - days.take(DaysPerRow).forEach { day -> - Text( - text = day.date.asShortWeekday(), - style = MaterialTheme.typography.labelSmall, - color = scheme.outline, - textAlign = TextAlign.Center, - modifier = Modifier.weight(1f), - ) - } - } - - weeks.forEach { week -> - // Zero spacing inside a run, so the cells of one stretch touch and - // read as a single bar; the 4.dp gap is drawn by the cell instead, - // on the sides where its run actually ends. - Row(horizontalArrangement = Arrangement.spacedBy(0.dp)) { - week.forEach { index -> - val day = days[index] - MonthCell( - day = day, - accent = accents[index], - run = runs[index], - selected = day.date == selected, - showLoad = showLoad, - onClick = { - if (day.date == selected) onOpen(day.date) else onSelect(day.date) - }, - modifier = Modifier.weight(1f), - ) - } - } - } - } - - if (bannerText != null) { - Box( - modifier = Modifier - .matchParentSize() - .padding(horizontal = ScreenPadding), - contentAlignment = Alignment.Center, - ) { - Text( - text = bannerText, - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onTertiaryContainer, - textAlign = TextAlign.Center, - modifier = Modifier - .clip(LessonsShapeTokens.Row) - .background(MaterialTheme.colorScheme.tertiaryContainer) - .padding(horizontal = 16.dp, vertical = 8.dp), - ) - } - } - } -} - -/** - * A month as a list, and the only view an order can apply to. - * - * Filtered days are dropped here rather than dimmed, which is the opposite of - * the grid and right for the same reason: a list has no shape to preserve, so - * a day that does not match is a row worth not drawing. The grid keeps its - * holes filled because a month with gaps stops lining up with its own header. - * - * Empty is a real answer and says which kind it is — a month with nothing in - * it at all reads differently from one where the filter is hiding everything, - * and telling somebody «ничего не найдено» when they have narrowed to «с ДЗ» - * in July would be blaming the month for the chip. - * - * Four kinds, not two, and for a long time it drew one. The same distinction - * the month grid and the ribbon already make: an empty list here is a year - * nobody has asked for, a year on its way, a month the filters have emptied, - * or a month that is genuinely blank — and the one sentence it had blamed the - * chips for all four, including a fresh install with no filter set at all. - * `days` cannot tell them apart on its own, which is why the other three - * arrive beside it. - */ -@Composable -private fun AgendaList( - days: List, - today: LocalDate, - selected: LocalDate, - order: DayOrder, - /** The chips currently narrowing the month; empty is nobody's fault. */ - filters: Set, - /** Whether the month's school year is in the cache at all. */ - isFetched: Boolean, - /** Whether a fetch of it is in flight right now. */ - loadingYear: Boolean, - /** «2026/27», for the sentence that names the year being waited on. */ - yearName: String, - onOrder: (DayOrder) -> Unit, - onOpen: (LocalDate) -> Unit, - modifier: Modifier = Modifier, -) { - Column( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = ScreenPadding), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - DayOrder.entries.forEach { candidate -> - PillChip( - text = candidate.asLabel(), - selected = candidate == order, - onClick = { onOrder(candidate) }, - ) - } - } - - if (days.isEmpty()) { - EmptyState( - title = correctedString( - when { - !isFetched && loadingYear -> R.string.week_year_loading_title - !isFetched -> R.string.week_year_missing_title - filters.isEmpty() -> R.string.calendar_agenda_blank_title - else -> R.string.calendar_agenda_empty_title - }, - ), - description = if (!isFetched) { - correctedString( - if (loadingYear) { - R.string.week_year_loading_description - } else { - R.string.week_year_missing_description - }, - yearName, - ) - } else { - correctedString( - if (filters.isEmpty()) { - R.string.calendar_agenda_blank_description - } else { - R.string.calendar_agenda_empty_description - }, - ) - }, - ) - return@Column - } - - days.forEach { day -> - AgendaRow( - day = day, - isToday = day.date == today, - isSelected = day.date == selected, - onClick = { onOpen(day.date) }, - ) - } - } -} - -/** One day of the agenda: what it is, and how much of it there is. */ -@Composable -private fun AgendaRow( - day: SchoolDay, - isToday: Boolean, - isSelected: Boolean, - onClick: () -> Unit, -) { - val scheme = MaterialTheme.colorScheme - val accent = day.agendaAccent() - val accentColors = accent.colors() - val container = when { - isToday -> scheme.secondaryContainer - isSelected -> scheme.rowContainer - else -> accentColors.container - } - val content = when { - isToday -> scheme.onSecondaryContainer - isSelected -> scheme.onSurface - else -> accentColors.content - } - - Row( - modifier = Modifier - .fillMaxWidth() - .clip(LessonsShapeTokens.Row) - .background(container) - .clickable(onClick = onClick) - .padding(horizontal = 14.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = "${day.date.dayOfMonth} · ${day.date.asShortWeekday()}", - style = MaterialTheme.typography.titleSmall.emphasised(isToday), - color = content, - ) - val subtitle = day.holiday?.title - ?: day.kind.takeIf { it != DayKind.NORMAL }?.asLabel() - ?: day.offReason.takeIf { !day.hasLessons }?.asEmptyDescription() - if (subtitle != null) { - Text( - text = subtitle, - style = MaterialTheme.typography.bodySmall, - color = content.copy(alpha = 0.75f), - ) - } - } - Text( - text = pluralStringResource( - R.plurals.lessons_count, - day.activeLessons.size, - day.activeLessons.size, - ), - style = MaterialTheme.typography.labelMedium, - color = content.copy(alpha = 0.75f), - ) - } -} - -/** The accent an agenda row carries — the same vocabulary the grid uses. */ -private fun SchoolDay.agendaAccent(): DayAccent = WeekDayUi( - date = date, - day = this, - isToday = false, -).accent() - -/** What each order is called, out of resources so both languages have it. */ -@Composable -internal fun DayOrder.asLabel(): String = correctedString( - when (this) { - DayOrder.DATE_ASC -> R.string.calendar_order_date_asc - DayOrder.DATE_DESC -> R.string.calendar_order_date_desc - DayOrder.BUSIEST_FIRST -> R.string.calendar_order_busiest - }, -) - -/** - * The four facets, as chips over whatever the calendar is drawing. - * - * Horizontally scrollable rather than wrapped onto two rows: four Russian - * labels do not fit one phone width, and a row that grows taller when a filter - * is on moves the grid under the reader's thumb at the moment they press. - * - * «Сбросить» appears only when something is on. A permanent clear button on a - * calendar nobody has filtered is a button that does nothing, and the row is - * already competing with the grid for attention. - */ -@Composable -private fun FilterChips( - active: Set, - onToggle: (DayFilter) -> Unit, - onClear: () -> Unit, - modifier: Modifier = Modifier, -) { - Row( - modifier = modifier - .fillMaxWidth() - .horizontalScroll(rememberScrollState()) - .padding(horizontal = ScreenPadding), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - DayFilter.entries.forEach { filter -> - PillChip( - text = filter.asLabel(), - selected = filter in active, - onClick = { onToggle(filter) }, - ) - } - if (active.isNotEmpty()) { - PillChip(text = correctedString(R.string.calendar_filter_clear), onClick = onClear) - } - } -} - -/** What each facet is called, out of resources so both languages have it. */ -@Composable -internal fun DayFilter.asLabel(): String = correctedString( - when (this) { - DayFilter.HAS_LESSONS -> R.string.calendar_filter_lessons - DayFilter.HAS_HOMEWORK -> R.string.calendar_filter_homework - DayFilter.HAS_EVENTS -> R.string.calendar_filter_events - DayFilter.MARKED -> R.string.calendar_filter_marked - }, -) - -private const val DaysPerRow = 7 - -/** One cell of the month grid. */ -@Composable -private fun MonthCell( - day: WeekDayUi, - accent: DayAccent, - run: RunPosition, - selected: Boolean, - showLoad: Boolean, - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - val scheme = MaterialTheme.colorScheme - val accentColors = accent.colors() - val container = when { - selected -> scheme.primary - day.isToday -> scheme.secondaryContainer - day.inPeriod -> accentColors.container - else -> Color.Transparent - } - val content = when { - selected -> scheme.onPrimary - day.isToday -> scheme.onSecondaryContainer - day.inPeriod -> accentColors.content - else -> scheme.outline - } - // A selected day is its own shape: it is one cell being pointed at, and - // squaring its corners to join a run would lose the one thing the - // selection is for. - val shape = if (selected || day.isToday) LessonsShapeTokens.Row else run.shape() - - // Filtered out: dimmed, never removed. A grid with holes in it stops - // lining up with its own weekday header. Today and the selection keep - // their full weight either way — the filter narrows what is interesting, - // it does not move where you are. - val dimmed = !day.matchesFilters && !selected && !day.isToday - - Column( - modifier = modifier - // The gap the Row used to space with, moved here so it can be left - // out between two cells of the same run. - .padding( - start = if (run.first || selected || day.isToday) 2.dp else 0.dp, - end = if (run.last || selected || day.isToday) 2.dp else 0.dp, - ) - .clip(shape) - .background(if (dimmed) container.copy(alpha = 0.25f) else container) - .clickable(onClick = onClick) - .padding(vertical = 8.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - text = day.date.dayOfMonth.toString(), - style = MaterialTheme.typography.bodyMedium.emphasised(selected || day.isToday), - color = if (dimmed) content.copy(alpha = 0.38f) else content, - ) - LoadDots( - count = if (showLoad) day.day?.activeLessons?.size ?: 0 else 0, - color = when { - selected -> scheme.onPrimary - dimmed -> scheme.primary.copy(alpha = 0.3f) - else -> scheme.primary - }, - ) - } -} - -/** The detail under the week strip or the month grid. */ -@Composable -private fun DayPanel( - day: WeekDayUi?, - date: LocalDate, - /** Whether a fetch of this date's school year is in flight right now. */ - loadingYear: Boolean, - showTeacher: Boolean, - showEvents: Boolean, - showHomework: Boolean, - onLessonClick: (Lesson) -> Unit, - onOpenDay: () -> Unit, - modifier: Modifier = Modifier, -) { - val schoolDay = day?.day - val lessons = schoolDay?.activeLessons.orEmpty() - - Column( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = ScreenPadding), - verticalArrangement = Arrangement.spacedBy(GroupSpacing), - ) { - SectionHeader( - title = "${date.asFullWeekday().replaceFirstChar { it.uppercase() }}, " + - date.asDayMonth(), - subtitle = schoolDay?.let { - pluralStringResource( - R.plurals.lessons_count, - it.activeLessons.size, - it.activeLessons.size, - ) - }, - actionLabel = schoolDay?.let { correctedString(R.string.schedule_day_details) }, - onActionClick = schoolDay?.let { { onOpenDay() } }, - ) - - DayChips(day = day, date = date) - - when { - // Three ways to be empty, and they were one until the cache learned - // to hold more than a year. «Нет данных» about a year nobody has - // asked for is a timetable that looks like it stops; «загружаю» is - // the same screen with the truth on it. - schoolDay == null && day?.isFetched == false -> EmptyState( - title = correctedString( - if (loadingYear) { - R.string.week_year_loading_title - } else { - R.string.week_year_missing_title - }, - ), - description = correctedString( - if (loadingYear) { - R.string.week_year_loading_description - } else { - R.string.week_year_missing_description - }, - yearLabel(SchoolYear.openingYearOf(date)), - ), - ) - - schoolDay == null -> EmptyState( - title = correctedString(R.string.week_no_data_title), - description = correctedString(R.string.week_no_data_description), - ) - - lessons.isEmpty() -> EmptyState( - title = correctedString(R.string.week_day_off_title), - description = schoolDay.offReason.asEmptyDescription(), - ) - - else -> LessonGroup( - lessons = lessons, - now = null, - showTeacher = showTeacher, - onLessonClick = onLessonClick, - ) - } - - DayExtras( - day = schoolDay, - showEvents = showEvents, - showHomework = showHomework, - ) - } -} - -/** Today / kind / note, as a row of pills. */ -@Composable -private fun DayChips( - day: WeekDayUi?, - date: LocalDate, - modifier: Modifier = Modifier, -) { - val kind = day?.day?.kind?.takeIf { it != DayKind.NORMAL } - val note = day?.day?.note - val holiday = day?.day?.holiday - val isToday = day?.isToday == true - if (!isToday && kind == null && note == null && holiday == null) return - - Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - if (isToday) { - PillChip( - text = correctedString(R.string.day_today), - selected = true, - containerColor = MaterialTheme.colorScheme.primary, - contentColor = MaterialTheme.colorScheme.onPrimary, - ) - } - if (holiday != null) { - // The server's own words. A date this build has never heard of - // still has a name, which is the whole reason the title travels - // beside the code rather than the code travelling alone. - PillChip( - text = holiday.title, - containerColor = if (holiday.stopsLessons) { - MaterialTheme.colorScheme.errorContainer - } else { - MaterialTheme.colorScheme.tertiaryContainer - }, - contentColor = if (holiday.stopsLessons) { - MaterialTheme.colorScheme.onErrorContainer - } else { - MaterialTheme.colorScheme.onTertiaryContainer - }, - ) - } - if (kind != null) PillChip(text = kind.asLabel()) - if (note != null) PillChip(text = note) - } -} - -/** - * Why this day is empty, in words somebody can act on. - * - * «Уроков нет» is true of four different days and useful on one. A blank - * Tuesday in November is the holidays, a public holiday, or a timetable with - * nothing on it, and those are three different things to do next. - */ -@Composable -internal fun DayOffReason?.asEmptyDescription(): String = correctedString( - when (this) { - DayOffReason.OUT_OF_YEAR -> R.string.week_day_off_year_over - DayOffReason.BETWEEN_TERMS -> R.string.week_day_off_between_terms - DayOffReason.PUBLIC_HOLIDAY -> R.string.week_day_off_public_holiday - null -> R.string.week_day_off_description - }, -) - -/** Localized name of a non-normal day kind. */ -@Composable -internal fun DayKind.asLabel(): String = correctedString( - when (this) { - DayKind.NORMAL -> R.string.day_kind_normal - DayKind.HOLIDAY -> R.string.day_kind_holiday - DayKind.SHORTENED -> R.string.day_kind_shortened - DayKind.REMOTE -> R.string.day_kind_remote - DayKind.SELF_STUDY -> R.string.day_kind_self_study - DayKind.DAY_OFF -> R.string.day_kind_day_off - }, -) From a288aa807fb8e3c2e4bfea91313dcf8bb373d4e2 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 13:20:47 +0300 Subject: [PATCH 03/43] Take the compose database password from the environment, and refuse to start without one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docker-compose.yml set POSTGRES_PASSWORD, and the password inside both DATABASE_URLs, to the literal `lessons`. The repository is public, so that was the password of every deployment that ran the file as written. The db service now reads `${POSTGRES_PASSWORD:?...}` and both URLs splice in the same value, so `docker compose up` stops and names the variable instead of starting on a known password. docs/deploy.md, «Option 2», says where the value goes and how to make one. It also corrects the step before it: it said to fill in `server/.env`, which compose never reads for interpolation — the `.env` it reads is the one beside docker-compose.yml, at the repository root — so `up` stopped at «set BOT_TOKEN in .env» however carefully that file was filled in. Two more things are now written down: the password is spliced into a URL unescaped, so it has to be letters and digits (`token_hex` makes one), and a volume initialised while the file said `lessons` keeps that password until an ALTER ROLE changes it, which the page gives as one command. tests/test_compose.py holds it: the db password and the password slot of every DATABASE_URL must be the `:?` interpolation and nothing else. It failed on the old file. ci.yml's change filter now runs the server job for a commit that touches only docker-compose.yml, since that test is the one thing that reads it. Not covered: nothing here has Docker, so `docker compose up` with the new file is written, never run — including the ALTER ROLE step for an old volume. Closes #190 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 ++-- docker-compose.yml | 22 +++++++++++++--- docs/deploy.md | 28 ++++++++++++++++++++- server/tests/test_compose.py | 49 ++++++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 server/tests/test_compose.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6dcf6eb8..9ea97384 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,8 +103,9 @@ jobs: # test_env_example), `docs/diaries/regions.md` is the region # catalog's input and `docs/diaries.md` its table # (test_region_catalog), `docs/diaries/netschool.md` is quoted by - # test_netschool_mapper. - server/*|api/*|requirements.txt|docs/deploy.md|docs/build.md|docs/diaries.md|docs/diaries/*|.github/workflows/*) server=true ;; + # test_netschool_mapper. `docker-compose.yml` is read by + # test_compose, which is all that checks it: nothing here runs Docker. + server/*|api/*|requirements.txt|docker-compose.yml|docs/deploy.md|docs/build.md|docs/diaries.md|docs/diaries/*|.github/workflows/*) server=true ;; esac done <<< "$files" diff --git a/docker-compose.yml b/docker-compose.yml index 1d617bb7..1edbaaf0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,28 @@ # Minimal production-ish deployment: Postgres plus the combined API + bot process. # For a single class, dropping the `db` service and keeping the default SQLite # URL is perfectly adequate. +# +# Every `${...}` below is read from the shell or from `.env` beside this file — +# the repository root, not `server/` — which is where `docker compose` looks. +# docs/deploy.md, «Option 2», says what goes in it. services: db: image: postgres:16-alpine environment: POSTGRES_USER: lessons - POSTGRES_PASSWORD: lessons + # From the environment and never from here: this file is public, so a + # password written into it is the password of every deployment that ran it + # as written. `:?` refuses to start without one rather than falling back + # to anything. + # + # Letters and digits only. The same value is spliced into DATABASE_URL + # below unescaped, and an `@`, `:`, `/` or `%` in it is read as part of + # the URL's syntax rather than of the password. + # + # Postgres reads it once, when the volume is first initialised. A volume + # created while this line said `lessons` keeps that password until it is + # changed inside the database; docs/deploy.md has the one command. + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} POSTGRES_DB: lessons volumes: - pgdata:/var/lib/postgresql/data @@ -31,7 +47,7 @@ services: build: ./server command: ["alembic", "upgrade", "head"] environment: - DATABASE_URL: postgresql+asyncpg://lessons:lessons@db:5432/lessons + DATABASE_URL: postgresql+asyncpg://lessons:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@db:5432/lessons depends_on: db: condition: service_healthy @@ -40,7 +56,7 @@ services: server: build: ./server environment: - DATABASE_URL: postgresql+asyncpg://lessons:lessons@db:5432/lessons + DATABASE_URL: postgresql+asyncpg://lessons:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@db:5432/lessons BOT_TOKEN: ${BOT_TOKEN:?set BOT_TOKEN in .env} OWNER_IDS: ${OWNER_IDS:?set OWNER_IDS in .env} TIMEZONE: ${TIMEZONE:-Europe/Moscow} diff --git a/docs/deploy.md b/docs/deploy.md index 1efe9b77..615d62be 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -545,7 +545,8 @@ Nothing has to be rewritten — the code already works this way. ```bash git clone https://github.com/lumenpearson/lessons && cd lessons -cp server/.env.example server/.env # fill in BOT_TOKEN and OWNER_IDS +cp server/.env.example .env # beside docker-compose.yml; fill in BOT_TOKEN and OWNER_IDS +echo "POSTGRES_PASSWORD=$(python3 -c 'import secrets; print(secrets.token_hex(24))')" >> .env docker compose up -d --build ``` @@ -553,6 +554,31 @@ docker compose up -d --build through polling, so no external address and no webhook are needed at all — the server can sit behind NAT with no public IP. +**The `.env` is the one beside `docker-compose.yml`, not `server/.env`.** Compose fills every +`${...}` in the file from the shell or from `.env` in the directory the file is in, and hands +the container exactly what the file lists; the image copies no `.env` of its own. This step +used to say `server/.env`, which compose never reads, so `up` stopped at «set BOT_TOKEN in +.env» however carefully that file had been filled in. + +**The database password is yours, and letters and digits only.** `POSTGRES_PASSWORD` is +required — `docker compose up` refuses to start without it. The file used to carry `lessons` +in plain text, which in a public repository is the password of every deployment that ran it +as written (#190). The same value is spliced into `DATABASE_URL` unescaped, so an `@`, `:`, +`/` or `%` in it would be read as the URL's syntax rather than as the password; `token_hex` +produces none of them. + +**A volume created before that keeps its old password.** Postgres reads `POSTGRES_PASSWORD` +only when it initialises an empty volume, so a deployment that has been up since the file +said `lessons` still has `lessons`, and `migrate` fails to sign in with the new value. Change +it inside the database once — the `postgres` image trusts connections from inside its own +container, so this needs no password of its own: + +```bash +docker compose up -d db +docker compose exec db psql -U lessons -c "ALTER ROLE lessons PASSWORD ''" +docker compose up -d --build +``` + **The migration is a service of its own, and the server waits for it.** `migrate` runs `alembic upgrade head` once against the same image and the same database and must finish successfully (`condition: service_completed_successfully`) before `server` starts. On a diff --git a/server/tests/test_compose.py b/server/tests/test_compose.py new file mode 100644 index 00000000..dc3951ce --- /dev/null +++ b/server/tests/test_compose.py @@ -0,0 +1,49 @@ +"""`docker-compose.yml`, read against what the server needs from it. + +Nothing here has ever been run under Docker from this repository (there is no +Docker where it is developed), so the file is the only thing that can be +checked, and it is checked for the properties a wrong line would cost a +deployment silently rather than loudly. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[2] +COMPOSE = ROOT / "docker-compose.yml" + +#: The one way the database password may appear: interpolated from the +#: environment, refusing to start without it. +_PASSWORD = re.compile(r"^\$\{POSTGRES_PASSWORD:\?[^}]*\}$") + + +def _services() -> dict: + return yaml.safe_load(COMPOSE.read_text("utf-8"))["services"] + + +def test_the_database_password_comes_from_the_environment_and_nowhere_else(): + """#190. The file is public, so a password written into it is the password + of every deployment that ran it as written — and `lessons:lessons` is the + first thing anybody would try.""" + services = _services() + + assert _PASSWORD.match(services["db"]["environment"]["POSTGRES_PASSWORD"]) + + urls = { + name: service["environment"]["DATABASE_URL"] + for name, service in services.items() + if "DATABASE_URL" in service.get("environment", {}) + } + assert set(urls) == {"migrate", "server"}, urls + for name, url in urls.items(): + # Split by hand at the last `@`: the interpolation is not a password + # `urlsplit` can parse, and that is the point — it is not a literal. + userinfo, _, host = url.split("://", 1)[1].rpartition("@") + user, _, password = userinfo.partition(":") + assert user == services["db"]["environment"]["POSTGRES_USER"], name + assert _PASSWORD.match(password), f"{name} carries a literal database password" + assert host == "db:5432/lessons", name From 178b0925c5f2b826a93d97b94abbedaae2a7cb3c Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 13:21:54 +0300 Subject: [PATCH 04/43] Give the home shell, its pages, its scaffold and its motion files of their own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LessonsApp.kt had grown to 1223 lines, and the function the file is named for was the first hundred of them. The rest was the signed-in shell — the pager, the settings layers, back, the toolbar and the arranging mode, 660 lines in one composable — and four things that shell is built from. LessonsApp.kt now keeps what is above every screen: the root gate, the composition locals, the splash, and `isInsecure`. HomeShell.kt holds the shell, with the constants only it reads and the toolbar's action button; ShellPage.kt the pages it moves between; ShellScaffold.kt one page with its own toolbar riding on it; ShellMotion.kt how a page slides and how the pager moves when animations are off. Moved verbatim, comments included. HomeShell, ShellPage and its `destination`, ShellScaffold, pageTransition and goToPage go from private to internal because their callers are now in another file. Five imports the old file never used, and `key`, which only a named argument matched, were not carried over. `LayerTravelDivisor` came along as it was: nothing reads it, and its comment says the blur does, which is a question for whoever owns the blur rather than for a move. HomeShell itself is still one composable of 660 lines. Cutting it further would be rewriting it, not moving it, and this change is the move. docs/design.md named LessonsApp.kt as where Essentials' tab pager went; it is HomeShell.kt now. Refs #209 Co-Authored-By: Claude Opus 5.5 --- .../lessons/navigation/HomeShell.kt | 843 +++++++++++++ .../lessons/navigation/LessonsApp.kt | 1067 ----------------- .../lessons/navigation/ShellMotion.kt | 86 ++ .../lessons/navigation/ShellPage.kt | 54 + .../lessons/navigation/ShellScaffold.kt | 114 ++ docs/design.md | 2 +- 6 files changed, 1098 insertions(+), 1068 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellMotion.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellScaffold.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt new file mode 100644 index 00000000..87b2ceb3 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt @@ -0,0 +1,843 @@ +package com.lumenpearson.lessons.navigation + +import androidx.activity.compose.BackHandler +import androidx.activity.compose.PredictiveBackHandler +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.interaction.DragInteraction +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.pager.HorizontalPager +import androidx.compose.foundation.pager.rememberPagerState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.BugReport +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.saveable.rememberSaveableStateHolder +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.intl.Locale +import androidx.lifecycle.compose.LifecycleStartEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.di.Graph +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.designsystem.component.LessonsFloatingToolbar +import com.lumenpearson.lessons.core.designsystem.component.ToolbarAction +import com.lumenpearson.lessons.core.designsystem.component.ToolbarItem +import com.lumenpearson.lessons.core.designsystem.haptic.LessonsHaptics +import com.lumenpearson.lessons.core.designsystem.haptic.rememberHapticView +import com.lumenpearson.lessons.core.designsystem.modifier.LiquidRippleState +import com.lumenpearson.lessons.core.designsystem.modifier.LocalLiquidRipple +import com.lumenpearson.lessons.core.designsystem.modifier.liquidRipple +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion +import com.lumenpearson.lessons.core.designsystem.theme.LocalScrollOffset +import com.lumenpearson.lessons.core.designsystem.theme.ScrollOffsetHolder +import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur +import com.lumenpearson.lessons.core.model.HomeTab +import com.lumenpearson.lessons.ui.admin.isClassManager +import com.lumenpearson.lessons.ui.debug.DebugSheet +import com.lumenpearson.lessons.ui.diary.DiaryScreen +import com.lumenpearson.lessons.ui.diary.DiaryTab +import com.lumenpearson.lessons.ui.diary.DiaryViewModel +import com.lumenpearson.lessons.ui.diary.icon +import com.lumenpearson.lessons.ui.diary.labelRes +import com.lumenpearson.lessons.ui.docs.DocsScreen +import com.lumenpearson.lessons.ui.docs.DocsViewModel +import com.lumenpearson.lessons.ui.docs.docsToolbarItems +import com.lumenpearson.lessons.ui.docs.docsToolbarSelection +import com.lumenpearson.lessons.ui.homework.HomeworkScreen +import com.lumenpearson.lessons.ui.settings.SettingsRootScreen +import com.lumenpearson.lessons.ui.settings.SettingsSection +import com.lumenpearson.lessons.ui.settings.SettingsSectionScreen +import com.lumenpearson.lessons.ui.settings.UpdateHost +import com.lumenpearson.lessons.ui.settings.SettingsViewModel +import com.lumenpearson.lessons.ui.settings.role +import com.lumenpearson.lessons.ui.today.TodayScreen +import com.lumenpearson.lessons.ui.week.ScheduleView +import com.lumenpearson.lessons.ui.week.WeekScreen +import com.lumenpearson.lessons.ui.week.WeekViewModel +import java.time.LocalDate +import kotlin.math.abs +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch + +/** How far the whole pager shrinks while a predictive back gesture is in flight. */ +private const val BackScaleDepth = 0.06f + +/** Time the shell takes to settle back to rest after a cancelled back gesture. */ +private const val BackSettleMillis = 300 + +/** …and after a completed one, which travels further and so takes longer. */ +private const val BackReturnMillis = 400 + +/** The swipe rumble fires once per tenth of a page travelled. */ +private const val SwipeHapticBuckets = 10 + +/** Key the tabs' saved state is filed under while they are out of the tree. */ +private const val TabsStateKey = "home-tabs" + +/** + * The signed-in app: three tabs under one floating toolbar, with the settings + * tree layered over them. + * + * Everything that makes the shell feel like Essentials is here rather than in + * the screens: the swipe between tabs, the haptic that ticks through it, the + * predictive-back gesture that scales the page down and returns to the default + * tab, and the blur that lets content pass under the status bar. + * + * Settings is a layer, not a tab. Opening it slides a page in from the right + * over the pager, and opening one of its sections slides another over that, so + * the tabs underneath keep their scroll position and their loaded data — which + * is the thing a real navigation graph would have cost here. Back pops one layer + * at a time and only then reaches the predictive-back gesture below. + * + * The toolbar does not fold away on scroll. It used to, driven from here, and + * the idea cost more than it bought: on a page too short to scroll it folded + * with nothing left to unfold it, so the destinations vanished for good; and + * once folded it sat inside its own container's side padding as a lopsided + * halo, because that padding is sized for a row of items and not for one. + * Destinations that are always present and always reachable — by a screen reader + * too — beat an animation nobody asked for. + * + * The same shell draws both homes ([home]). On the diary home the tabs' pager is + * replaced by the diary itself and the toolbar carries its two halves instead + * of the class tabs; everything else — the settings layers, the guide, back, + * the update host — is shared, because a second shell would be a second copy of + * the rules `ShellBackTest` holds. The diary's halves are not swiped between + * and not rearranged: their order is the diary's, and there are two. + */ +@Composable +internal fun HomeShell( + home: ShellHome, + settings: AppSettings, + openDate: LocalDate?, + onDateOpened: () -> Unit, + modifier: Modifier = Modifier, +) { + // The reader's own order, repaired on the way out of storage — see + // `HomeTab.order`, which guarantees this is every tab exactly once however + // old the string behind it was. Every index below is an index into *this* + // list, and the whole of the arranging gesture is written in terms of tabs + // rather than positions for that reason. + val tabs = settings.tabOrder + val view = rememberHapticView() + val scope = rememberCoroutineScope() + val density = LocalDensity.current + // Read here rather than inside the transition spec below: `transitionSpec` + // is a plain lambda, not a composable one, so a composition local cannot be + // reached from inside it. + val motion = LocalMotion.current + + // Only read on the first composition — a pager cannot be re-seeded without + // yanking the page out from under the user, so changing the default tab + // takes effect the next time the app is opened. Essentials behaves the same. + // + // What is latched is the tab, and its index is looked up every time. + // Latching the index instead would survive a reorder as a number that has + // since come to mean another tab, and back would then return to a screen + // nobody chose — the same defect as the pager's, one level up. + val homeTab = remember { settings.defaultTab } + val homePage = tabs.indexOf(homeTab).coerceAtLeast(0) + val pagerState = rememberPagerState(initialPage = homePage) { tabs.size } + + // The order the bar is drawing while its tabs are being arranged, and null + // whenever they are not. One state rather than two, because «in the mode» + // and «the list the mode started from» are never separately true. + // + // It is latched so that both drags of one session describe permutations of + // the same list: the bar reports a permutation of the items it was *handed*, + // and a list that changed under it between two drags would leave the second + // one describing something neither side still had. + // + // It is not latched to keep the bar from applying a drag twice. The bar + // holds its permutation against the list it belongs to and drops it when + // that list changes, so a caller that hands the committed order straight + // back is drawn correctly — which is also what makes the frame this mode + // closes on correct, rather than one frame of the previous order. + var arranging by remember { mutableStateOf?>(null) } + val reordering = arranging != null + val barTabs = arranging ?: tabs + + // Hoisted rather than left to the settings screen: the toolbar is drawn here + // and its action button acts on this view model, so the shell needs it. Both + // call sites resolve to the same instance through the activity's store, so + // the screens below can keep their own default and nothing is passed down. + val settingsViewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory) + // Hoisted for the same reason: a day chip on the widget has to be able to + // put a date into the calendar before the calendar has been composed. Only + // on the class home — the diary home has no calendar, and building one + // would start a timetable load for a class this phone is not in. The + // branch is stable for the life of this composition: the shell is keyed + // on [home]. + val calendarViewModel: WeekViewModel? = + if (home == ShellHome.TIMETABLE) viewModel(factory = WeekViewModel.Factory) else null + // The diary's, on the diary home: the toolbar switches its tabs and back + // reads which one is open, so the shell holds it — the activity's store + // hands the settings page the same instance. + val diaryViewModel: DiaryViewModel? = + if (home == ShellHome.DIARY) viewModel(factory = DiaryViewModel.Factory) else null + val diaryTab = diaryViewModel?.uiState?.collectAsStateWithLifecycle()?.value?.tab + val settingsState by settingsViewModel.uiState.collectAsStateWithLifecycle() + val shellMode = if (home == ShellHome.DIARY) ShellMode.DIARY else ShellMode.CLASS + + // The one refresh of the diary that nobody pressed for: each time the diary + // home comes to the front, the week is read again if the saved copy is + // stale. Here and nowhere else — not in the application, a receiver or the + // worker — because a read is what keeps the server's copy of the session + // alive, and that has to mean somebody opened the app (G4). + if (diaryViewModel != null) { + LifecycleStartEffect(diaryViewModel) { + diaryViewModel.refreshOnStart { Graph.container.diaryImport.refreshIfStale() } + onStopOrDispose { } + } + } + + var settingsOpen by rememberSaveable { mutableStateOf(false) } + var showDebugSheet by rememberSaveable { mutableStateOf(false) } + + // The app's wave, provided by [LessonsApp]; a fresh one only for a preview + // that composes the shell bare. + val ripple = LocalLiquidRipple.current ?: remember { LiquidRippleState() } + // Where the shell sits on the screen, for turning a point a modal sheet + // measured in its own window into one of ours. + var shellOnScreen by remember { mutableStateOf(Offset.Zero) } + var openSectionName by rememberSaveable { mutableStateOf(null) } + val openSection = remember(openSectionName) { SettingsSection.fromName(openSectionName) } + + // Whether the guide is open. A flag rather than a path: its sections are + // peers on one pager now, so there is no history inside it to remember — + // back means "leave", and the pager keeps its own position across a + // rotation. + var docsOpen by rememberSaveable { mutableStateOf(false) } + + val docsViewModel: DocsViewModel = viewModel(factory = DocsViewModel.Factory) + val docsState by docsViewModel.state.collectAsStateWithLifecycle() + val docsPages = docsState.library?.guide?.pages.orEmpty() + + // The guide's own pager, hoisted for the reason the tabs' is: the toolbar + // is composed by the shell, and it both shows which section is current and + // scrolls to another. + val docsPagerState = rememberPagerState(pageCount = { docsPages.size }) + + // Which language the reader is actually looking at. Below Android 13 the + // app's chosen language is applied by wrapping the `Context`, so the + // composition is the only place that knows — a repository reading the + // phone's locale would hand a Russian reader the English guide. + val docsLanguage = Locale.current.language + + // Read as it opens, then checked against the repository. Keyed on the + // language too, so switching it while the guide is closed still loads the + // right one on the next visit. + LaunchedEffect(docsOpen, docsLanguage) { + if (docsOpen) docsViewModel.open(docsLanguage) + } + + // Where the shell is, as one value. Derived from the saved flags rather + // than replacing them, so what survives process death is unchanged. + val destination = remember(settingsOpen, openSection, docsOpen) { + when { + docsOpen -> ShellPage.Docs + openSection != null -> ShellPage.Section(openSection) + settingsOpen -> ShellPage.SettingsRoot + else -> ShellPage.Tabs + } + } + + // Keeps each tab's scroll position while the tabs are out of the tree. + // + // They leave it entirely once a settings page is in front, which is what + // stops them receiving touches — and that has to be removal rather than + // cover. A covering layer that consumed early enough to stop the pager was + // early enough to cancel taps on its own rows, and this shipped twice before + // a test existed for it. `OverlayLayerTest` now records that compose-bom + // 2026.09.00 changed that dispatch, which is the argument for removal rather + // than against it: the ordering is unspecified, it moved once under a + // dependency bump without a word, and a layer would go silently dead again. + // Removal leaves nothing to block. `AnimatedContent` removes the slot that is + // no longer current, so the property now falls out of the navigation rather + // than being maintained beside it. + // + // Without the holder, coming back would put every list at the top: the + // scroll position of a LazyColumn is `rememberSaveable`, and a + // `rememberSaveable` in a composable that leaves the tree is gone unless + // something holds it. + val tabStates = rememberSaveableStateHolder() + + // One holder per page plus one per settings layer. The pager keeps its + // neighbours composed, so a single shared holder would have an off-screen + // page reporting its own scroll over the visible one's. + // + // Per tab rather than per page index, because the bar can be rearranged: + // a holder that stayed with the index would hand the screen arriving there + // the scroll depth of the one that left, and the top fade would start + // halfway down a list that is at the top. + val pageOffsets = remember { HomeTab.entries.associateWith { ScrollOffsetHolder() } } + val diaryOffset = remember { ScrollOffsetHolder() } + + /** The holder belonging to whatever tab sits at [page] of the pager. */ + fun offsetOf(page: Int): ScrollOffsetHolder = + pageOffsets.getValue(tabs.getOrElse(page) { tabs.first() }) + + val settingsOffset = remember { ScrollOffsetHolder() } + val sectionOffset = remember { ScrollOffsetHolder() } + // One per section, for the reason the tabs have one per tab: the pager keeps + // its neighbours composed, and a shared holder would let an off-screen page + // report its scroll over the visible one's. + val docsOffset = remember { ScrollOffsetHolder() } + val docsOffsets = remember(docsPages.size) { + List(docsPages.size.coerceAtLeast(1)) { ScrollOffsetHolder() } + } + + // The tab the reader was looking at when the bar was last rearranged, held + // until the new order has actually come back out of storage. + // + // Which is the whole difficulty of this gesture: `pagerState.currentPage` is + // an index, and the reorder changes what that index means, so a reader who + // drags «Задания» to the front would silently be moved to another screen. + // The tab is captured before the write and the pager is put back on it + // after — and the write is a round trip through DataStore, so «after» is a + // frame or two later and cannot be done in the same breath. + var keepOnTab by remember { mutableStateOf(null) } + LaunchedEffect(tabs) { + val tab = keepOnTab ?: return@LaunchedEffect + val target = tabs.indexOf(tab) + // `scrollToPage`, never the animated one: the page did not go + // anywhere, the index under it did, and an animation here is a screen + // visibly sliding to a place it never left. + if (target >= 0 && target != pagerState.currentPage) pagerState.scrollToPage(target) + // Let go only once the pager is on it: the bar reads this tab as the + // selected one until then, and releasing it first left a frame in which + // the selection came from an index that still meant the old order. + keepOnTab = null + } + + // A widget tap lands here. Closing the settings layers first, because the + // request is "show me this day" and a page that slides in over the calendar + // would answer it with a screen the user did not ask for. + LaunchedEffect(openDate) { + val date = openDate ?: return@LaunchedEffect + docsOpen = false + openSectionName = null + settingsOpen = false + // A deep link is somebody arriving with a question, and a bar that is + // still being arranged is in the way of answering it. + arranging = null + // Only a widget tap from before the phone left its class can reach the + // diary home — the widget draws nothing to tap in the diary mode — and + // the nearest answer to «this day» there is the diary's week holding it. + diaryViewModel?.showWeekOf(date) + calendarViewModel?.let { calendar -> + calendar.select(date) + calendar.setView(ScheduleView.DAY) + pagerState.goToPage(motion, tabs.indexOf(HomeTab.WEEK).coerceAtLeast(0)) + } + onDateOpened() + } + + // A tap when the page actually changes, however it was changed. Keyed on the + // pager alone: re-keying on the swipe setting would restart the collector and + // swallow the next change as if it were the initial one. + LaunchedEffect(pagerState) { + var first = true + snapshotFlow { pagerState.currentPage }.collect { + if (first) first = false else LessonsHaptics.tap(view) + } + } + + // The rumble while a swipe is in flight, bucketed so it ticks ten times + // across a page instead of once per frame. Only while a finger is actually + // on the screen: `isScrollInProgress` is also true for animateScrollToPage, + // so gating on it turned one tap on a tab into a press, ten rumbles and a + // tap — a buzz, and at the stronger levels three overlapping waveforms. + var dragging by remember { mutableStateOf(false) } + LaunchedEffect(pagerState) { + pagerState.interactionSource.interactions.collect { interaction -> + dragging = when (interaction) { + is DragInteraction.Start -> true + is DragInteraction.Stop, is DragInteraction.Cancel -> false + else -> dragging + } + } + } + + var lastBucket by remember { mutableIntStateOf(0) } + LaunchedEffect(pagerState) { + snapshotFlow { pagerState.currentPageOffsetFraction }.collect { offset -> + if (!dragging) return@collect + val bucket = (abs(offset) * SwipeHapticBuckets).toInt() + if (bucket != lastBucket) { + if (abs(offset) > 0f) LessonsHaptics.swipe(view) + lastBucket = bucket + } + } + } + + fun closeSection() { + openSectionName = null + } + + fun closeSettings() { + openSectionName = null + settingsOpen = false + } + + /** + * Leaving the mode where the tabs are arranged. + * + * Called by everything that takes the reader off the tabs as well as by the + * back press: the mode is a property of a bar that is about to be replaced + * by another page's, and one left armed behind a settings page would be + * waiting, jiggling, when that page was closed. + */ + fun stopArranging() { + arranging = null + } + + /** + * A drag on the tab bar has finished. See [reorderTabs] for the arithmetic, + * which is separate because it is the half of this that can be wrong + * quietly. + * + * [moved] is relative to the list the bar was handed, which is [barTabs] and + * deliberately not the stored one — see where that is latched. + */ + fun commitTabOrder(moved: List) { + // Captured before the write, because after it the index means another + // tab; the effect above puts the pager back on this one. + keepOnTab = tabs.getOrNull(pagerState.currentPage) + settingsViewModel.setTabOrder(reorderTabs(barTabs, moved)) + } + + /** Opening the guide from the «О приложении» page. */ + fun openDocs() { + docsOpen = true + stopArranging() + } + + /** A tap on a section in the toolbar: a scroll, not a screen. */ + fun openDocsPage(index: Int) { + scope.launch { docsPagerState.goToPage(motion, index) } + } + + /** + * The one definition of "back" inside the documentation. + * + * The arrow beside the pill and the system gesture both run this, which is + * the point: two ways out that disagreed about where back goes is a bug a + * reader cannot work around. There is nothing to walk off any more — the + * sections are peers on one pager, and a reader on the fourth of them asked + * for the fourth rather than arrived at it through three others. + * + * Leaving goes home rather than back to the settings page it was opened + * from. The guide is somewhere you go to read, and handing a reader who has + * finished the settings tree they came through would make them press back + * twice more to reach the thing the documentation was about. + */ + fun docsBack() { + docsOpen = false + closeSettings() + } + + // One layer per press, innermost first, and exactly one handler enabled at + // a time: a back gesture in settings has to leave settings, not scroll the + // pager underneath it, and a back press while the tabs are being arranged + // has to leave that mode rather than do either. + // + // The guards are mutually exclusive rather than merely ordered, and they + // are now one function rather than four conditions that have to be read + // together to see that — the documentation is opened from inside a settings + // section, so while it is up two of the others are also true. Which of them + // acts is a rule, so [shellBack] states it once and `ShellBackTest` holds + // it; the handlers below only carry it out. + val back = shellBack( + arranging = reordering, + docsOpen = docsOpen, + sectionOpen = openSection != null, + settingsOpen = settingsOpen, + // The diary's home page is its timetable, as the class's is the + // default tab: back from the marks goes there before it leaves. + onHomePage = if (home == ShellHome.DIARY) { + diaryTab == null || diaryTab == DiaryTab.SCHEDULE + } else { + pagerState.currentPage == homePage + }, + ) + BackHandler(enabled = back == ShellBack.LEAVE_ARRANGING) { stopArranging() } + BackHandler(enabled = back == ShellBack.CLOSE_DOCS) { docsBack() } + BackHandler(enabled = back == ShellBack.CLOSE_SECTION) { closeSection() } + BackHandler(enabled = back == ShellBack.CLOSE_SETTINGS) { closeSettings() } + + val backProgress = remember { Animatable(0f) } + PredictiveBackHandler(enabled = back == ShellBack.HOME) { events -> + try { + events.collect { event -> backProgress.snapTo(event.progress) } + if (diaryViewModel != null) { + diaryViewModel.setTab(DiaryTab.SCHEDULE) + } else { + scope.launch { pagerState.goToPage(motion, homePage) } + } + scope.launch { backProgress.animateTo(0f, tween(BackReturnMillis)) } + } catch (_: CancellationException) { + scope.launch { backProgress.animateTo(0f, tween(BackSettleMillis)) } + } + } + + val statusBarHeightPx = with(density) { + WindowInsets.statusBars.asPaddingValues().calculateTopPadding().toPx() + } + if (showDebugSheet) { + DebugSheet( + enabled = settingsState.settings.debugMode, + onEnabledChange = settingsViewModel::setDebugMode, + onDismiss = { showDebugSheet = false }, + ) + } + UpdateHost( + state = settingsState, + viewModel = settingsViewModel, + ripple = ripple, + screenToRoot = { onScreen -> onScreen - shellOnScreen }, + ) + + Box( + modifier = modifier + .fillMaxSize() + .onGloballyPositioned { shellOnScreen = it.positionOnScreen() } + // On the whole shell, toolbar included, rather than on one page: the + // wave starts at the bug button, and a ripple that left the button it + // came from perfectly still would look like it came from somewhere + // else. Outside the AnimatedContent for the same reason — a ripple + // that only touched the page arriving would stop at its edge. + .liquidRipple(ripple, enabled = settings.rippleEffects), + ) { + AnimatedContent( + targetState = destination, + transitionSpec = { pageTransition(targetState.depth > initialState.depth, motion) }, + label = "shell_page", + ) { page -> + ShellScaffold( + edgeBlur = settings.edgeBlur, + statusBarHeightPx = statusBarHeightPx, + offset = when (page) { + ShellPage.Tabs -> if (home == ShellHome.DIARY) diaryOffset else offsetOf(pagerState.currentPage) + ShellPage.SettingsRoot -> settingsOffset + is ShellPage.Section -> sectionOffset + ShellPage.Docs -> docsOffsets.getOrElse(docsPagerState.currentPage) { docsOffset } + }, + // Everything here is read from `page`, never from the hoisted + // state, and that is the whole discipline of this arrangement: + // both slots are composed at once while the slide runs, so a + // title read from outside would flip the instant you navigated + // and the page would leave carrying the name of the one + // arriving. + toolbar = { barModifier -> + LessonsFloatingToolbar( + modifier = barModifier, + selectedIndex = when (page) { + // Which *tab* is in front, expressed as a position + // in the list this bar is drawing. The two lists + // are the same one outside the arranging mode, and + // inside it the bar's is a frame behind the stored + // one on purpose. + ShellPage.Tabs -> if (home == ShellHome.DIARY) { + diaryTab?.ordinal ?: 0 + } else { + // The tab being kept on, while there is one. A + // drop writes the new order, and the frame it + // arrives in still has the pager on the old + // *index* — the keyed pager moves it during its + // own measure, after this was read — so the + // index named the tab that had moved into it, + // and the selected circle hopped to that tab + // for a frame and back (#180). + (keepOnTab ?: tabs.getOrNull(pagerState.currentPage)) + ?.let(barTabs::indexOf) ?: -1 + } + + ShellPage.Docs -> docsToolbarSelection( + docsPagerState.currentPage, + docsPages.size, + ) + else -> -1 + }, + items = when (page) { + // Each item carries its tab rather than its + // position: where a tab is drawn and where its page + // is differ for the frames between a drag and the + // order coming back out of storage, and a tap in + // that window has to reach the screen the icon is + // of. + // The diary's own halves, in the diary's order. + ShellPage.Tabs -> if (diaryViewModel != null) { + DiaryTab.entries.map { tab -> + ToolbarItem( + icon = tab.icon, + label = correctedString(tab.labelRes()), + onClick = { diaryViewModel.setTab(tab) }, + ) + } + } else barTabs.map { tab -> + ToolbarItem( + icon = tab.icon, + label = correctedString(tab.labelRes), + onClick = { + val target = tabs.indexOf(tab).coerceAtLeast(0) + scope.launch { pagerState.goToPage(motion, target) } + }, + ) + } + + // The bar is the documentation's only navigation, + // so it carries every section rather than a way + // back to a list of them: there is no list. The + // sections come from the fetched guide, so one + // added to the documentation appears here without + // a new build. + ShellPage.Docs -> docsToolbarItems(docsPages, ::openDocsPage) + + else -> emptyList() + }, + // Only the destinations that are peers of each other + // overflow a phone; the three tabs never will. + scrollableItems = page == ShellPage.Docs, + // The tabs only. The documentation's bar is the same + // component, and its order is the document's rather + // than the reader's: a mode that opened there would let + // somebody rearrange a table of contents into one the + // text no longer matches. + reorderable = page == ShellPage.Tabs && home == ShellHome.TIMETABLE, + // Read against the page for the same reason everything + // else here is: both bars are composed at once while a + // slide runs, and the one leaving must not start + // jiggling on its way out. + reordering = reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE, + onReorderingChange = { on -> + arranging = if (on) tabs else null + }, + onReorder = ::commitTabOrder, + title = when (page) { + ShellPage.Tabs, ShellPage.Docs -> null + ShellPage.SettingsRoot -> correctedString(R.string.settings_title) + is ShellPage.Section -> correctedString(page.section.titleRes) + }, + onBackClick = when (page) { + // Null keeps the bar in its tabbed mode. On the + // documentation that is deliberate: the pill is the + // table of contents, and back is the button beside + // it — see [shellActionKind]. + ShellPage.Tabs, ShellPage.Docs -> null + ShellPage.SettingsRoot -> ::closeSettings + is ShellPage.Section -> ::closeSection + }, + action = shellAction( + destination = page.destination, + // The shortcut exists for the people who have the + // page it shortcuts to — never on the diary home, + // where there is no class to manage. + manager = home == ShellHome.TIMETABLE && + isClassManager(settingsState.deviceLink.role), + onOpenSettings = { + settingsOpen = true + stopArranging() + }, + onOpenDebug = { at -> + ripple.fire(at) + showDebugSheet = true + }, + onBack = ::docsBack, + ), + ) + }, + // Read against the page, like `reordering` above: the page + // sliding away must not keep a layer that swallows touches. + onTouchOutsideBar = if ( + reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE + ) { + ::stopArranging + } else { + null + }, + ) { + when (page) { + ShellPage.Tabs -> if (diaryViewModel != null) { + tabStates.SaveableStateProvider(TabsStateKey) { + CompositionLocalProvider(LocalScrollOffset provides diaryOffset) { + DiaryScreen( + asHome = true, + insecureServer = isInsecure(settings.baseUrl), + viewModel = diaryViewModel, + modifier = Modifier.graphicsLayer { + val scale = 1f - backProgress.value * BackScaleDepth + scaleX = scale + scaleY = scale + }, + ) + } + } + } else tabStates.SaveableStateProvider(TabsStateKey) { + HorizontalPager( + state = pagerState, + userScrollEnabled = settings.swipeTabs, + // Keyed by the tab, not by the position it is in. + // The default key is the index, and an index is + // exactly what a reorder changes: the saved scroll + // position filed under «page 1» would be restored + // into whichever screen had moved there. + key = { index -> tabs[index] }, + // Off-screen pages stay composed so a swipe back to a + // tab shows the list where it was left rather than + // re-running its loader. + beyondViewportPageCount = 1, + modifier = Modifier + .fillMaxSize() + // The largest scroll in the app, and the one the + // blur setting was missing: it named lists and + // left out the gesture people actually spend + // their day on. + .appScrollMotionBlur(pagerState) + .graphicsLayer { + val scale = 1f - backProgress.value * BackScaleDepth + scaleX = scale + scaleY = scale + }, + ) { tabIndex -> + CompositionLocalProvider( + LocalScrollOffset provides offsetOf(tabIndex), + ) { + when (tabs[tabIndex]) { + HomeTab.TODAY -> TodayScreen( + onOpenHomework = { + scope.launch { + pagerState.goToPage( + motion, + tabs.indexOf(HomeTab.HOMEWORK), + ) + } + }, + ) + + HomeTab.WEEK -> WeekScreen( + viewModel = checkNotNull(calendarViewModel) { + "the class home always has its calendar" + }, + ) + HomeTab.HOMEWORK -> HomeworkScreen() + } + } + } + } + + ShellPage.SettingsRoot -> CompositionLocalProvider( + LocalScrollOffset provides settingsOffset, + ) { + SettingsRootScreen( + mode = shellMode, + viewModel = settingsViewModel, + onOpenSection = { section -> openSectionName = section.name }, + ) + } + + is ShellPage.Section -> CompositionLocalProvider( + LocalScrollOffset provides sectionOffset, + ) { + // page.section, not the hoisted one: that is already null + // for the whole slide out, which is what the latch this + // replaces existed to paper over. + SettingsSectionScreen( + section = page.section, + mode = shellMode, + onOpenSection = { next -> openSectionName = next.name }, + onOpenDocs = ::openDocs, + viewModel = settingsViewModel, + ) + } + + ShellPage.Docs -> CompositionLocalProvider( + // The current section's holder, chosen the same way the + // tabs choose theirs; the screen itself provides one + // per page inside the pager. + LocalScrollOffset provides docsOffsets + .getOrElse(docsPagerState.currentPage) { docsOffset }, + ) { + DocsScreen( + state = docsState, + pagerState = docsPagerState, + onRefresh = { docsViewModel.refresh(docsLanguage) }, + ) + } + } + } + } + } +} + +/** + * The button beside the pill, chosen by where the shell is. + * + * On the tabs it is the way into settings, which is why settings stopped being a + * tab. Inside settings it is the bug — the crash reports and the switch that + * decides whether any are kept — which is where Essentials puts its own bug + * button and for the same reason: this app ships as an APK inside one school, + * with no crash service behind it, so the only place a crash can be read is the + * phone it happened on. + * + * It used to be a refresh button here. Refresh already has a row of its own in + * the sync section, two taps away, and spending the one permanent button in the + * app on a duplicate of a row is a poor trade. + * + * On the documentation it is the way back, because the pill beside it is full: + * it carries the sections, so the bar's standard mode — a back arrow and a + * title — is not available there. Which of the three it is, is decided by + * [shellActionKind]; this only dresses the answer. + */ +@Composable +private fun shellAction( + destination: ShellDestination, + manager: Boolean, + onOpenSettings: () -> Unit, + onOpenDebug: (at: Offset) -> Unit, + onBack: () -> Unit, +): ToolbarAction? = when (shellActionKind(destination, manager)) { + ShellActionKind.SETTINGS -> ToolbarAction( + icon = Icons.Rounded.Settings, + contentDescription = correctedString(R.string.nav_settings), + onClick = { onOpenSettings() }, + ) + + ShellActionKind.DEBUG -> ToolbarAction( + icon = Icons.Rounded.BugReport, + contentDescription = correctedString(R.string.debug_open), + onClick = onOpenDebug, + ) + + ShellActionKind.BACK -> ToolbarAction( + icon = Icons.AutoMirrored.Rounded.ArrowBack, + contentDescription = correctedString(R.string.docs_back), + onClick = { onBack() }, + ) + + ShellActionKind.NONE -> null +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt index a49a6b0a..a9a38c3b 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt @@ -1,128 +1,27 @@ package com.lumenpearson.lessons.navigation -import androidx.activity.compose.BackHandler -import androidx.activity.compose.PredictiveBackHandler -import androidx.compose.animation.AnimatedContent -import androidx.compose.animation.ContentTransform -import androidx.compose.animation.EnterTransition -import androidx.compose.animation.ExitTransition -import androidx.compose.animation.SizeTransform -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.Spring -import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.spring -import androidx.compose.animation.core.tween -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.animation.slideInHorizontally -import androidx.compose.animation.slideOutHorizontally -import androidx.compose.foundation.background -import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.statusBars -import androidx.compose.foundation.pager.HorizontalPager -import androidx.compose.foundation.pager.PagerState -import androidx.compose.foundation.pager.rememberPagerState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack -import androidx.compose.material.icons.rounded.BugReport -import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.Immutable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.derivedStateOf -import androidx.compose.runtime.getValue import androidx.compose.runtime.key -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.saveable.rememberSaveableStateHolder -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.layout.positionOnScreen -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.dp -import androidx.compose.ui.zIndex -import androidx.compose.ui.text.intl.Locale -import androidx.lifecycle.compose.LifecycleStartEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.lumenpearson.lessons.R -import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.repository.AppSettings -import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.data.repository.ShellState -import com.lumenpearson.lessons.core.designsystem.component.ArrangingDismissLayer -import com.lumenpearson.lessons.core.designsystem.component.LessonsFloatingToolbar import com.lumenpearson.lessons.core.designsystem.component.LessonsLoadingIndicator -import com.lumenpearson.lessons.core.designsystem.component.ToolbarAction -import com.lumenpearson.lessons.core.designsystem.component.ToolbarItem -import com.lumenpearson.lessons.core.designsystem.haptic.LessonsHaptics -import com.lumenpearson.lessons.core.designsystem.haptic.rememberHapticView -import com.lumenpearson.lessons.core.designsystem.modifier.BottomBlurHeight -import com.lumenpearson.lessons.core.designsystem.modifier.StatusBarBlurExtent -import com.lumenpearson.lessons.core.designsystem.modifier.StatusBarBlurRadius -import com.lumenpearson.lessons.core.designsystem.modifier.TopBlurRampPx import com.lumenpearson.lessons.core.designsystem.modifier.LiquidRippleState import com.lumenpearson.lessons.core.designsystem.modifier.LocalLiquidRipple -import com.lumenpearson.lessons.core.designsystem.modifier.liquidRipple -import com.lumenpearson.lessons.core.designsystem.modifier.progressiveBlur -import com.lumenpearson.lessons.core.designsystem.text.correctedString -import com.lumenpearson.lessons.core.designsystem.theme.BottomBarGap -import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion import com.lumenpearson.lessons.core.designsystem.theme.LocalScrollBlur -import com.lumenpearson.lessons.core.designsystem.theme.LocalScrollOffset import com.lumenpearson.lessons.core.designsystem.theme.MotionSettings import com.lumenpearson.lessons.core.designsystem.theme.ScrollBlurSettings -import com.lumenpearson.lessons.core.designsystem.theme.ScrollOffsetHolder -import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur -import com.lumenpearson.lessons.core.designsystem.theme.appSlideMotionBlur -import com.lumenpearson.lessons.core.model.HomeTab -import com.lumenpearson.lessons.ui.admin.isClassManager -import com.lumenpearson.lessons.ui.debug.DebugSheet -import com.lumenpearson.lessons.ui.diary.DiaryScreen -import com.lumenpearson.lessons.ui.diary.DiaryTab -import com.lumenpearson.lessons.ui.diary.DiaryViewModel -import com.lumenpearson.lessons.ui.diary.icon -import com.lumenpearson.lessons.ui.diary.labelRes -import com.lumenpearson.lessons.ui.docs.DocsScreen -import com.lumenpearson.lessons.ui.docs.DocsViewModel -import com.lumenpearson.lessons.ui.docs.docsToolbarItems -import com.lumenpearson.lessons.ui.docs.docsToolbarSelection -import com.lumenpearson.lessons.ui.homework.HomeworkScreen import com.lumenpearson.lessons.ui.onboarding.OnboardingScreen -import com.lumenpearson.lessons.ui.settings.SettingsRootScreen -import com.lumenpearson.lessons.ui.settings.SettingsSection -import com.lumenpearson.lessons.ui.settings.SettingsSectionScreen -import com.lumenpearson.lessons.ui.settings.UpdateHost -import com.lumenpearson.lessons.ui.settings.SettingsViewModel -import com.lumenpearson.lessons.ui.settings.role -import com.lumenpearson.lessons.ui.today.TodayScreen -import com.lumenpearson.lessons.ui.week.ScheduleView -import com.lumenpearson.lessons.ui.week.WeekScreen -import com.lumenpearson.lessons.ui.week.WeekViewModel import java.time.LocalDate -import kotlin.math.abs -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch /** * The whole app below the theme. @@ -233,972 +132,6 @@ fun LessonsApp( } } -/** How far the whole pager shrinks while a predictive back gesture is in flight. */ -private const val BackScaleDepth = 0.06f - -/** Time the shell takes to settle back to rest after a cancelled back gesture. */ -private const val BackSettleMillis = 300 - -/** …and after a completed one, which travels further and so takes longer. */ -private const val BackReturnMillis = 400 - -/** The swipe rumble fires once per tenth of a page travelled. */ -private const val SwipeHapticBuckets = 10 - -/** How long a settings page takes to slide in over the tabs. */ -private const val PageTransitionMillis = 320 - -/** Key the tabs' saved state is filed under while they are out of the tree. */ -private const val TabsStateKey = "home-tabs" - -/** - * The signed-in app: three tabs under one floating toolbar, with the settings - * tree layered over them. - * - * Everything that makes the shell feel like Essentials is here rather than in - * the screens: the swipe between tabs, the haptic that ticks through it, the - * predictive-back gesture that scales the page down and returns to the default - * tab, and the blur that lets content pass under the status bar. - * - * Settings is a layer, not a tab. Opening it slides a page in from the right - * over the pager, and opening one of its sections slides another over that, so - * the tabs underneath keep their scroll position and their loaded data — which - * is the thing a real navigation graph would have cost here. Back pops one layer - * at a time and only then reaches the predictive-back gesture below. - * - * The toolbar does not fold away on scroll. It used to, driven from here, and - * the idea cost more than it bought: on a page too short to scroll it folded - * with nothing left to unfold it, so the destinations vanished for good; and - * once folded it sat inside its own container's side padding as a lopsided - * halo, because that padding is sized for a row of items and not for one. - * Destinations that are always present and always reachable — by a screen reader - * too — beat an animation nobody asked for. - * - * The same shell draws both homes ([home]). On the diary home the tabs' pager is - * replaced by the diary itself and the toolbar carries its two halves instead - * of the class tabs; everything else — the settings layers, the guide, back, - * the update host — is shared, because a second shell would be a second copy of - * the rules `ShellBackTest` holds. The diary's halves are not swiped between - * and not rearranged: their order is the diary's, and there are two. - */ -@Composable -private fun HomeShell( - home: ShellHome, - settings: AppSettings, - openDate: LocalDate?, - onDateOpened: () -> Unit, - modifier: Modifier = Modifier, -) { - // The reader's own order, repaired on the way out of storage — see - // `HomeTab.order`, which guarantees this is every tab exactly once however - // old the string behind it was. Every index below is an index into *this* - // list, and the whole of the arranging gesture is written in terms of tabs - // rather than positions for that reason. - val tabs = settings.tabOrder - val view = rememberHapticView() - val scope = rememberCoroutineScope() - val density = LocalDensity.current - // Read here rather than inside the transition spec below: `transitionSpec` - // is a plain lambda, not a composable one, so a composition local cannot be - // reached from inside it. - val motion = LocalMotion.current - - // Only read on the first composition — a pager cannot be re-seeded without - // yanking the page out from under the user, so changing the default tab - // takes effect the next time the app is opened. Essentials behaves the same. - // - // What is latched is the tab, and its index is looked up every time. - // Latching the index instead would survive a reorder as a number that has - // since come to mean another tab, and back would then return to a screen - // nobody chose — the same defect as the pager's, one level up. - val homeTab = remember { settings.defaultTab } - val homePage = tabs.indexOf(homeTab).coerceAtLeast(0) - val pagerState = rememberPagerState(initialPage = homePage) { tabs.size } - - // The order the bar is drawing while its tabs are being arranged, and null - // whenever they are not. One state rather than two, because «in the mode» - // and «the list the mode started from» are never separately true. - // - // It is latched so that both drags of one session describe permutations of - // the same list: the bar reports a permutation of the items it was *handed*, - // and a list that changed under it between two drags would leave the second - // one describing something neither side still had. - // - // It is not latched to keep the bar from applying a drag twice. The bar - // holds its permutation against the list it belongs to and drops it when - // that list changes, so a caller that hands the committed order straight - // back is drawn correctly — which is also what makes the frame this mode - // closes on correct, rather than one frame of the previous order. - var arranging by remember { mutableStateOf?>(null) } - val reordering = arranging != null - val barTabs = arranging ?: tabs - - // Hoisted rather than left to the settings screen: the toolbar is drawn here - // and its action button acts on this view model, so the shell needs it. Both - // call sites resolve to the same instance through the activity's store, so - // the screens below can keep their own default and nothing is passed down. - val settingsViewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory) - // Hoisted for the same reason: a day chip on the widget has to be able to - // put a date into the calendar before the calendar has been composed. Only - // on the class home — the diary home has no calendar, and building one - // would start a timetable load for a class this phone is not in. The - // branch is stable for the life of this composition: the shell is keyed - // on [home]. - val calendarViewModel: WeekViewModel? = - if (home == ShellHome.TIMETABLE) viewModel(factory = WeekViewModel.Factory) else null - // The diary's, on the diary home: the toolbar switches its tabs and back - // reads which one is open, so the shell holds it — the activity's store - // hands the settings page the same instance. - val diaryViewModel: DiaryViewModel? = - if (home == ShellHome.DIARY) viewModel(factory = DiaryViewModel.Factory) else null - val diaryTab = diaryViewModel?.uiState?.collectAsStateWithLifecycle()?.value?.tab - val settingsState by settingsViewModel.uiState.collectAsStateWithLifecycle() - val shellMode = if (home == ShellHome.DIARY) ShellMode.DIARY else ShellMode.CLASS - - // The one refresh of the diary that nobody pressed for: each time the diary - // home comes to the front, the week is read again if the saved copy is - // stale. Here and nowhere else — not in the application, a receiver or the - // worker — because a read is what keeps the server's copy of the session - // alive, and that has to mean somebody opened the app (G4). - if (diaryViewModel != null) { - LifecycleStartEffect(diaryViewModel) { - diaryViewModel.refreshOnStart { Graph.container.diaryImport.refreshIfStale() } - onStopOrDispose { } - } - } - - var settingsOpen by rememberSaveable { mutableStateOf(false) } - var showDebugSheet by rememberSaveable { mutableStateOf(false) } - - // The app's wave, provided by [LessonsApp]; a fresh one only for a preview - // that composes the shell bare. - val ripple = LocalLiquidRipple.current ?: remember { LiquidRippleState() } - // Where the shell sits on the screen, for turning a point a modal sheet - // measured in its own window into one of ours. - var shellOnScreen by remember { mutableStateOf(Offset.Zero) } - var openSectionName by rememberSaveable { mutableStateOf(null) } - val openSection = remember(openSectionName) { SettingsSection.fromName(openSectionName) } - - // Whether the guide is open. A flag rather than a path: its sections are - // peers on one pager now, so there is no history inside it to remember — - // back means "leave", and the pager keeps its own position across a - // rotation. - var docsOpen by rememberSaveable { mutableStateOf(false) } - - val docsViewModel: DocsViewModel = viewModel(factory = DocsViewModel.Factory) - val docsState by docsViewModel.state.collectAsStateWithLifecycle() - val docsPages = docsState.library?.guide?.pages.orEmpty() - - // The guide's own pager, hoisted for the reason the tabs' is: the toolbar - // is composed by the shell, and it both shows which section is current and - // scrolls to another. - val docsPagerState = rememberPagerState(pageCount = { docsPages.size }) - - // Which language the reader is actually looking at. Below Android 13 the - // app's chosen language is applied by wrapping the `Context`, so the - // composition is the only place that knows — a repository reading the - // phone's locale would hand a Russian reader the English guide. - val docsLanguage = Locale.current.language - - // Read as it opens, then checked against the repository. Keyed on the - // language too, so switching it while the guide is closed still loads the - // right one on the next visit. - LaunchedEffect(docsOpen, docsLanguage) { - if (docsOpen) docsViewModel.open(docsLanguage) - } - - // Where the shell is, as one value. Derived from the saved flags rather - // than replacing them, so what survives process death is unchanged. - val destination = remember(settingsOpen, openSection, docsOpen) { - when { - docsOpen -> ShellPage.Docs - openSection != null -> ShellPage.Section(openSection) - settingsOpen -> ShellPage.SettingsRoot - else -> ShellPage.Tabs - } - } - - // Keeps each tab's scroll position while the tabs are out of the tree. - // - // They leave it entirely once a settings page is in front, which is what - // stops them receiving touches — and that has to be removal rather than - // cover. A covering layer that consumed early enough to stop the pager was - // early enough to cancel taps on its own rows, and this shipped twice before - // a test existed for it. `OverlayLayerTest` now records that compose-bom - // 2026.09.00 changed that dispatch, which is the argument for removal rather - // than against it: the ordering is unspecified, it moved once under a - // dependency bump without a word, and a layer would go silently dead again. - // Removal leaves nothing to block. `AnimatedContent` removes the slot that is - // no longer current, so the property now falls out of the navigation rather - // than being maintained beside it. - // - // Without the holder, coming back would put every list at the top: the - // scroll position of a LazyColumn is `rememberSaveable`, and a - // `rememberSaveable` in a composable that leaves the tree is gone unless - // something holds it. - val tabStates = rememberSaveableStateHolder() - - // One holder per page plus one per settings layer. The pager keeps its - // neighbours composed, so a single shared holder would have an off-screen - // page reporting its own scroll over the visible one's. - // - // Per tab rather than per page index, because the bar can be rearranged: - // a holder that stayed with the index would hand the screen arriving there - // the scroll depth of the one that left, and the top fade would start - // halfway down a list that is at the top. - val pageOffsets = remember { HomeTab.entries.associateWith { ScrollOffsetHolder() } } - val diaryOffset = remember { ScrollOffsetHolder() } - - /** The holder belonging to whatever tab sits at [page] of the pager. */ - fun offsetOf(page: Int): ScrollOffsetHolder = - pageOffsets.getValue(tabs.getOrElse(page) { tabs.first() }) - - val settingsOffset = remember { ScrollOffsetHolder() } - val sectionOffset = remember { ScrollOffsetHolder() } - // One per section, for the reason the tabs have one per tab: the pager keeps - // its neighbours composed, and a shared holder would let an off-screen page - // report its scroll over the visible one's. - val docsOffset = remember { ScrollOffsetHolder() } - val docsOffsets = remember(docsPages.size) { - List(docsPages.size.coerceAtLeast(1)) { ScrollOffsetHolder() } - } - - // The tab the reader was looking at when the bar was last rearranged, held - // until the new order has actually come back out of storage. - // - // Which is the whole difficulty of this gesture: `pagerState.currentPage` is - // an index, and the reorder changes what that index means, so a reader who - // drags «Задания» to the front would silently be moved to another screen. - // The tab is captured before the write and the pager is put back on it - // after — and the write is a round trip through DataStore, so «after» is a - // frame or two later and cannot be done in the same breath. - var keepOnTab by remember { mutableStateOf(null) } - LaunchedEffect(tabs) { - val tab = keepOnTab ?: return@LaunchedEffect - val target = tabs.indexOf(tab) - // `scrollToPage`, never the animated one: the page did not go - // anywhere, the index under it did, and an animation here is a screen - // visibly sliding to a place it never left. - if (target >= 0 && target != pagerState.currentPage) pagerState.scrollToPage(target) - // Let go only once the pager is on it: the bar reads this tab as the - // selected one until then, and releasing it first left a frame in which - // the selection came from an index that still meant the old order. - keepOnTab = null - } - - // A widget tap lands here. Closing the settings layers first, because the - // request is "show me this day" and a page that slides in over the calendar - // would answer it with a screen the user did not ask for. - LaunchedEffect(openDate) { - val date = openDate ?: return@LaunchedEffect - docsOpen = false - openSectionName = null - settingsOpen = false - // A deep link is somebody arriving with a question, and a bar that is - // still being arranged is in the way of answering it. - arranging = null - // Only a widget tap from before the phone left its class can reach the - // diary home — the widget draws nothing to tap in the diary mode — and - // the nearest answer to «this day» there is the diary's week holding it. - diaryViewModel?.showWeekOf(date) - calendarViewModel?.let { calendar -> - calendar.select(date) - calendar.setView(ScheduleView.DAY) - pagerState.goToPage(motion, tabs.indexOf(HomeTab.WEEK).coerceAtLeast(0)) - } - onDateOpened() - } - - // A tap when the page actually changes, however it was changed. Keyed on the - // pager alone: re-keying on the swipe setting would restart the collector and - // swallow the next change as if it were the initial one. - LaunchedEffect(pagerState) { - var first = true - snapshotFlow { pagerState.currentPage }.collect { - if (first) first = false else LessonsHaptics.tap(view) - } - } - - // The rumble while a swipe is in flight, bucketed so it ticks ten times - // across a page instead of once per frame. Only while a finger is actually - // on the screen: `isScrollInProgress` is also true for animateScrollToPage, - // so gating on it turned one tap on a tab into a press, ten rumbles and a - // tap — a buzz, and at the stronger levels three overlapping waveforms. - var dragging by remember { mutableStateOf(false) } - LaunchedEffect(pagerState) { - pagerState.interactionSource.interactions.collect { interaction -> - dragging = when (interaction) { - is DragInteraction.Start -> true - is DragInteraction.Stop, is DragInteraction.Cancel -> false - else -> dragging - } - } - } - - var lastBucket by remember { mutableIntStateOf(0) } - LaunchedEffect(pagerState) { - snapshotFlow { pagerState.currentPageOffsetFraction }.collect { offset -> - if (!dragging) return@collect - val bucket = (abs(offset) * SwipeHapticBuckets).toInt() - if (bucket != lastBucket) { - if (abs(offset) > 0f) LessonsHaptics.swipe(view) - lastBucket = bucket - } - } - } - - fun closeSection() { - openSectionName = null - } - - fun closeSettings() { - openSectionName = null - settingsOpen = false - } - - /** - * Leaving the mode where the tabs are arranged. - * - * Called by everything that takes the reader off the tabs as well as by the - * back press: the mode is a property of a bar that is about to be replaced - * by another page's, and one left armed behind a settings page would be - * waiting, jiggling, when that page was closed. - */ - fun stopArranging() { - arranging = null - } - - /** - * A drag on the tab bar has finished. See [reorderTabs] for the arithmetic, - * which is separate because it is the half of this that can be wrong - * quietly. - * - * [moved] is relative to the list the bar was handed, which is [barTabs] and - * deliberately not the stored one — see where that is latched. - */ - fun commitTabOrder(moved: List) { - // Captured before the write, because after it the index means another - // tab; the effect above puts the pager back on this one. - keepOnTab = tabs.getOrNull(pagerState.currentPage) - settingsViewModel.setTabOrder(reorderTabs(barTabs, moved)) - } - - /** Opening the guide from the «О приложении» page. */ - fun openDocs() { - docsOpen = true - stopArranging() - } - - /** A tap on a section in the toolbar: a scroll, not a screen. */ - fun openDocsPage(index: Int) { - scope.launch { docsPagerState.goToPage(motion, index) } - } - - /** - * The one definition of "back" inside the documentation. - * - * The arrow beside the pill and the system gesture both run this, which is - * the point: two ways out that disagreed about where back goes is a bug a - * reader cannot work around. There is nothing to walk off any more — the - * sections are peers on one pager, and a reader on the fourth of them asked - * for the fourth rather than arrived at it through three others. - * - * Leaving goes home rather than back to the settings page it was opened - * from. The guide is somewhere you go to read, and handing a reader who has - * finished the settings tree they came through would make them press back - * twice more to reach the thing the documentation was about. - */ - fun docsBack() { - docsOpen = false - closeSettings() - } - - // One layer per press, innermost first, and exactly one handler enabled at - // a time: a back gesture in settings has to leave settings, not scroll the - // pager underneath it, and a back press while the tabs are being arranged - // has to leave that mode rather than do either. - // - // The guards are mutually exclusive rather than merely ordered, and they - // are now one function rather than four conditions that have to be read - // together to see that — the documentation is opened from inside a settings - // section, so while it is up two of the others are also true. Which of them - // acts is a rule, so [shellBack] states it once and `ShellBackTest` holds - // it; the handlers below only carry it out. - val back = shellBack( - arranging = reordering, - docsOpen = docsOpen, - sectionOpen = openSection != null, - settingsOpen = settingsOpen, - // The diary's home page is its timetable, as the class's is the - // default tab: back from the marks goes there before it leaves. - onHomePage = if (home == ShellHome.DIARY) { - diaryTab == null || diaryTab == DiaryTab.SCHEDULE - } else { - pagerState.currentPage == homePage - }, - ) - BackHandler(enabled = back == ShellBack.LEAVE_ARRANGING) { stopArranging() } - BackHandler(enabled = back == ShellBack.CLOSE_DOCS) { docsBack() } - BackHandler(enabled = back == ShellBack.CLOSE_SECTION) { closeSection() } - BackHandler(enabled = back == ShellBack.CLOSE_SETTINGS) { closeSettings() } - - val backProgress = remember { Animatable(0f) } - PredictiveBackHandler(enabled = back == ShellBack.HOME) { events -> - try { - events.collect { event -> backProgress.snapTo(event.progress) } - if (diaryViewModel != null) { - diaryViewModel.setTab(DiaryTab.SCHEDULE) - } else { - scope.launch { pagerState.goToPage(motion, homePage) } - } - scope.launch { backProgress.animateTo(0f, tween(BackReturnMillis)) } - } catch (_: CancellationException) { - scope.launch { backProgress.animateTo(0f, tween(BackSettleMillis)) } - } - } - - val statusBarHeightPx = with(density) { - WindowInsets.statusBars.asPaddingValues().calculateTopPadding().toPx() - } - if (showDebugSheet) { - DebugSheet( - enabled = settingsState.settings.debugMode, - onEnabledChange = settingsViewModel::setDebugMode, - onDismiss = { showDebugSheet = false }, - ) - } - UpdateHost( - state = settingsState, - viewModel = settingsViewModel, - ripple = ripple, - screenToRoot = { onScreen -> onScreen - shellOnScreen }, - ) - - Box( - modifier = modifier - .fillMaxSize() - .onGloballyPositioned { shellOnScreen = it.positionOnScreen() } - // On the whole shell, toolbar included, rather than on one page: the - // wave starts at the bug button, and a ripple that left the button it - // came from perfectly still would look like it came from somewhere - // else. Outside the AnimatedContent for the same reason — a ripple - // that only touched the page arriving would stop at its edge. - .liquidRipple(ripple, enabled = settings.rippleEffects), - ) { - AnimatedContent( - targetState = destination, - transitionSpec = { pageTransition(targetState.depth > initialState.depth, motion) }, - label = "shell_page", - ) { page -> - ShellScaffold( - edgeBlur = settings.edgeBlur, - statusBarHeightPx = statusBarHeightPx, - offset = when (page) { - ShellPage.Tabs -> if (home == ShellHome.DIARY) diaryOffset else offsetOf(pagerState.currentPage) - ShellPage.SettingsRoot -> settingsOffset - is ShellPage.Section -> sectionOffset - ShellPage.Docs -> docsOffsets.getOrElse(docsPagerState.currentPage) { docsOffset } - }, - // Everything here is read from `page`, never from the hoisted - // state, and that is the whole discipline of this arrangement: - // both slots are composed at once while the slide runs, so a - // title read from outside would flip the instant you navigated - // and the page would leave carrying the name of the one - // arriving. - toolbar = { barModifier -> - LessonsFloatingToolbar( - modifier = barModifier, - selectedIndex = when (page) { - // Which *tab* is in front, expressed as a position - // in the list this bar is drawing. The two lists - // are the same one outside the arranging mode, and - // inside it the bar's is a frame behind the stored - // one on purpose. - ShellPage.Tabs -> if (home == ShellHome.DIARY) { - diaryTab?.ordinal ?: 0 - } else { - // The tab being kept on, while there is one. A - // drop writes the new order, and the frame it - // arrives in still has the pager on the old - // *index* — the keyed pager moves it during its - // own measure, after this was read — so the - // index named the tab that had moved into it, - // and the selected circle hopped to that tab - // for a frame and back (#180). - (keepOnTab ?: tabs.getOrNull(pagerState.currentPage)) - ?.let(barTabs::indexOf) ?: -1 - } - - ShellPage.Docs -> docsToolbarSelection( - docsPagerState.currentPage, - docsPages.size, - ) - else -> -1 - }, - items = when (page) { - // Each item carries its tab rather than its - // position: where a tab is drawn and where its page - // is differ for the frames between a drag and the - // order coming back out of storage, and a tap in - // that window has to reach the screen the icon is - // of. - // The diary's own halves, in the diary's order. - ShellPage.Tabs -> if (diaryViewModel != null) { - DiaryTab.entries.map { tab -> - ToolbarItem( - icon = tab.icon, - label = correctedString(tab.labelRes()), - onClick = { diaryViewModel.setTab(tab) }, - ) - } - } else barTabs.map { tab -> - ToolbarItem( - icon = tab.icon, - label = correctedString(tab.labelRes), - onClick = { - val target = tabs.indexOf(tab).coerceAtLeast(0) - scope.launch { pagerState.goToPage(motion, target) } - }, - ) - } - - // The bar is the documentation's only navigation, - // so it carries every section rather than a way - // back to a list of them: there is no list. The - // sections come from the fetched guide, so one - // added to the documentation appears here without - // a new build. - ShellPage.Docs -> docsToolbarItems(docsPages, ::openDocsPage) - - else -> emptyList() - }, - // Only the destinations that are peers of each other - // overflow a phone; the three tabs never will. - scrollableItems = page == ShellPage.Docs, - // The tabs only. The documentation's bar is the same - // component, and its order is the document's rather - // than the reader's: a mode that opened there would let - // somebody rearrange a table of contents into one the - // text no longer matches. - reorderable = page == ShellPage.Tabs && home == ShellHome.TIMETABLE, - // Read against the page for the same reason everything - // else here is: both bars are composed at once while a - // slide runs, and the one leaving must not start - // jiggling on its way out. - reordering = reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE, - onReorderingChange = { on -> - arranging = if (on) tabs else null - }, - onReorder = ::commitTabOrder, - title = when (page) { - ShellPage.Tabs, ShellPage.Docs -> null - ShellPage.SettingsRoot -> correctedString(R.string.settings_title) - is ShellPage.Section -> correctedString(page.section.titleRes) - }, - onBackClick = when (page) { - // Null keeps the bar in its tabbed mode. On the - // documentation that is deliberate: the pill is the - // table of contents, and back is the button beside - // it — see [shellActionKind]. - ShellPage.Tabs, ShellPage.Docs -> null - ShellPage.SettingsRoot -> ::closeSettings - is ShellPage.Section -> ::closeSection - }, - action = shellAction( - destination = page.destination, - // The shortcut exists for the people who have the - // page it shortcuts to — never on the diary home, - // where there is no class to manage. - manager = home == ShellHome.TIMETABLE && - isClassManager(settingsState.deviceLink.role), - onOpenSettings = { - settingsOpen = true - stopArranging() - }, - onOpenDebug = { at -> - ripple.fire(at) - showDebugSheet = true - }, - onBack = ::docsBack, - ), - ) - }, - // Read against the page, like `reordering` above: the page - // sliding away must not keep a layer that swallows touches. - onTouchOutsideBar = if ( - reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE - ) { - ::stopArranging - } else { - null - }, - ) { - when (page) { - ShellPage.Tabs -> if (diaryViewModel != null) { - tabStates.SaveableStateProvider(TabsStateKey) { - CompositionLocalProvider(LocalScrollOffset provides diaryOffset) { - DiaryScreen( - asHome = true, - insecureServer = isInsecure(settings.baseUrl), - viewModel = diaryViewModel, - modifier = Modifier.graphicsLayer { - val scale = 1f - backProgress.value * BackScaleDepth - scaleX = scale - scaleY = scale - }, - ) - } - } - } else tabStates.SaveableStateProvider(TabsStateKey) { - HorizontalPager( - state = pagerState, - userScrollEnabled = settings.swipeTabs, - // Keyed by the tab, not by the position it is in. - // The default key is the index, and an index is - // exactly what a reorder changes: the saved scroll - // position filed under «page 1» would be restored - // into whichever screen had moved there. - key = { index -> tabs[index] }, - // Off-screen pages stay composed so a swipe back to a - // tab shows the list where it was left rather than - // re-running its loader. - beyondViewportPageCount = 1, - modifier = Modifier - .fillMaxSize() - // The largest scroll in the app, and the one the - // blur setting was missing: it named lists and - // left out the gesture people actually spend - // their day on. - .appScrollMotionBlur(pagerState) - .graphicsLayer { - val scale = 1f - backProgress.value * BackScaleDepth - scaleX = scale - scaleY = scale - }, - ) { tabIndex -> - CompositionLocalProvider( - LocalScrollOffset provides offsetOf(tabIndex), - ) { - when (tabs[tabIndex]) { - HomeTab.TODAY -> TodayScreen( - onOpenHomework = { - scope.launch { - pagerState.goToPage( - motion, - tabs.indexOf(HomeTab.HOMEWORK), - ) - } - }, - ) - - HomeTab.WEEK -> WeekScreen( - viewModel = checkNotNull(calendarViewModel) { - "the class home always has its calendar" - }, - ) - HomeTab.HOMEWORK -> HomeworkScreen() - } - } - } - } - - ShellPage.SettingsRoot -> CompositionLocalProvider( - LocalScrollOffset provides settingsOffset, - ) { - SettingsRootScreen( - mode = shellMode, - viewModel = settingsViewModel, - onOpenSection = { section -> openSectionName = section.name }, - ) - } - - is ShellPage.Section -> CompositionLocalProvider( - LocalScrollOffset provides sectionOffset, - ) { - // page.section, not the hoisted one: that is already null - // for the whole slide out, which is what the latch this - // replaces existed to paper over. - SettingsSectionScreen( - section = page.section, - mode = shellMode, - onOpenSection = { next -> openSectionName = next.name }, - onOpenDocs = ::openDocs, - viewModel = settingsViewModel, - ) - } - - ShellPage.Docs -> CompositionLocalProvider( - // The current section's holder, chosen the same way the - // tabs choose theirs; the screen itself provides one - // per page inside the pager. - LocalScrollOffset provides docsOffsets - .getOrElse(docsPagerState.currentPage) { docsOffset }, - ) { - DocsScreen( - state = docsState, - pagerState = docsPagerState, - onRefresh = { docsViewModel.refresh(docsLanguage) }, - ) - } - } - } - } - } -} - -/** - * Where the shell is, and how deep. - * - * The depth is declared rather than taken from an enum's ordinal, because an - * ordinal is a declaration order and reordering the list would silently reverse - * a transition. - */ -@Immutable -private sealed interface ShellPage { - - val depth: Int - - data object Tabs : ShellPage { - override val depth: Int = 0 - } - - data object SettingsRoot : ShellPage { - override val depth: Int = 1 - } - - data class Section(val section: SettingsSection) : ShellPage { - override val depth: Int = 2 - } - - /** - * The guide, all of it. - * - * One destination rather than one per section, which is the change: the - * sections are peers on a pager and moving between them is a swipe, so the - * shell's `AnimatedContent` has nothing to do between them. It used to push - * a screen per section, with a depth per section to make the slide follow - * the finger; a pager does that itself, in the same gesture the home tabs - * use, and without a history to walk back out of. - * - * Deeper than a settings section, so opening the guide still slides forward - * and leaving it slides back. - */ - data object Docs : ShellPage { - override val depth: Int = 3 - } -} - -/** As much of the page as the toolbar's action button needs to know. */ -private val ShellPage.destination: ShellDestination - get() = when (this) { - ShellPage.Tabs -> ShellDestination.TABS - ShellPage.SettingsRoot, is ShellPage.Section -> ShellDestination.SETTINGS - ShellPage.Docs -> ShellDestination.DOCS - } - -/** - * One page of the shell, with its own toolbar riding on it. - * - * The toolbar used to be drawn once, above everything, and stayed still while - * the page moved under it — so opening settings slid a page in beneath a bar - * that was already showing that page's title. Here it belongs to the page, so - * the two travel together and each screen's bar arrives with it. - * - * The cost of that is one measurement per page instead of one for the app, and - * that is deliberate too: during a slide there are two toolbars, and a single - * shared height would be written twice per frame by two different bars. - * - * @param onTouchOutsideBar while the tabs are being arranged, what a touch - * anywhere but the bar does; see [ArrangingDismissLayer]. Null the rest of the - * time, when there is no layer and the page takes its own touches. - */ -@Composable -private fun ShellScaffold( - edgeBlur: Boolean, - statusBarHeightPx: Float, - offset: ScrollOffsetHolder, - toolbar: @Composable (Modifier) -> Unit, - onTouchOutsideBar: (() -> Unit)? = null, - content: @Composable () -> Unit, -) { - val density = LocalDensity.current - val seedBarHeight = LocalBottomBarSpace.current - var barHeight by remember { mutableStateOf(seedBarHeight) } - val barHeightPx = with(density) { barHeight.toPx() } - - // Essentials' distance, not the toolbar's height. The bar measures around - // 60 dp here, so a fade tied to it only began where the toolbar already - // covered the list — the rows arrived sharp and were cut off rather than - // dissolving into it. `coerceAtLeast` is the one thing not copied: it keeps - // the guarantee the measured height gave, that the fade is never shorter - // than the bar it has to reach behind, on a device whose gesture inset - // makes the toolbar taller than Essentials' 130 dp. - val bottomBlurPx = with(density) { BottomBlurHeight.toPx() }.coerceAtLeast(barHeightPx) - - // This page's own scroll drives this page's own fade. The shell used to pick - // whichever screen was in front and hand one number to everybody, which the - // page sliding away then wore for the length of the slide. - // derivedStateOf, because the raw offset changes every scrolled pixel and - // the fraction it produces does not: past the ramp it is 1f and stays - // there. Read directly, this composable — the whole page, toolbar included - // — was invalidated on every frame of every scroll for a number that had - // stopped moving. The derived read only invalidates when the clamped value - // actually changes, which is a handful of frames per swipe instead of all - // of them. - val target by remember(offset) { - derivedStateOf { (offset.value / TopBlurRampPx).coerceIn(0f, 1f) } - } - val topFraction by animateFloatAsState(targetValue = target, label = "top_blur_fraction") - - Box(modifier = Modifier.fillMaxSize()) { - CompositionLocalProvider(LocalBottomBarSpace provides barHeight + BottomBarGap) { - // The blur goes on the content, never on the parent that also holds - // the toolbar: a bottom fade applied there would dissolve the - // toolbar along with the list running underneath it. - Box( - modifier = Modifier - .fillMaxSize() - .progressiveBlur( - blurRadius = if (edgeBlur) StatusBarBlurRadius else 0f, - topHeight = statusBarHeightPx * StatusBarBlurExtent, - bottomHeight = bottomBlurPx, - topFraction = topFraction, - showGradientOverlay = edgeBlur, - ), - ) { - content() - } - } - - // Between the page and the bar, so it takes every touch but the bar's. - if (onTouchOutsideBar != null) ArrangingDismissLayer(onDismiss = onTouchOutsideBar) - - toolbar( - Modifier - .align(Alignment.BottomCenter) - .zIndex(1f) - .onSizeChanged { size -> - barHeight = with(density) { size.height.toDp() } - }, - ) - } -} - -/** - * Forward pushes the old page off to the left; back slides it away to the right. - * - * One spec for the movement and the fade, rather than a tween on one and a - * spring on the other: given different curves the arriving page reaches full - * opacity while it is still visibly moving, and the leaving one disappears - * before it is off the screen. - * - * `SizeTransform(clip = false)` because settings pages are wildly different - * heights, and the default animates the slot's size *and* clips to it — which - * crops whichever page is taller for the length of the slide. - */ -private fun pageTransition(forward: Boolean, motion: MotionSettings): ContentTransform { - // Instant, not quick. Scaling the durations towards zero would still slide - // the page — a two-frame slide is a flicker, which is worse than no - // animation for exactly the people who switch animations off. - if (!motion.enabled) { - return ContentTransform( - targetContentEnter = EnterTransition.None, - initialContentExit = ExitTransition.None, - sizeTransform = SizeTransform(clip = false), - ) - } - - val fade = tween(motion.durationMillis(PageTransitionMillis)) - val enter = slideInHorizontally(animationSpec = pageSlideSpring(motion)) { width -> - if (forward) width else -width - } + fadeIn(animationSpec = fade) - - val exit = slideOutHorizontally(animationSpec = pageSlideSpring(motion)) { width -> - if (forward) -width else width - } + fadeOut(animationSpec = fade) - - return ContentTransform( - targetContentEnter = enter, - initialContentExit = exit, - sizeTransform = SizeTransform(clip = false), - ) -} - -/** A stiffer spring is a faster one; see [MotionSettings.stiffness]. */ -private fun pageSlideSpring(motion: MotionSettings) = spring( - dampingRatio = Spring.DampingRatioNoBouncy, - stiffness = motion.stiffness(Spring.StiffnessMediumLow), -) - -/** - * The button beside the pill, chosen by where the shell is. - * - * On the tabs it is the way into settings, which is why settings stopped being a - * tab. Inside settings it is the bug — the crash reports and the switch that - * decides whether any are kept — which is where Essentials puts its own bug - * button and for the same reason: this app ships as an APK inside one school, - * with no crash service behind it, so the only place a crash can be read is the - * phone it happened on. - * - * It used to be a refresh button here. Refresh already has a row of its own in - * the sync section, two taps away, and spending the one permanent button in the - * app on a duplicate of a row is a poor trade. - * - * On the documentation it is the way back, because the pill beside it is full: - * it carries the sections, so the bar's standard mode — a back arrow and a - * title — is not available there. Which of the three it is, is decided by - * [shellActionKind]; this only dresses the answer. - */ -@Composable -private fun shellAction( - destination: ShellDestination, - manager: Boolean, - onOpenSettings: () -> Unit, - onOpenDebug: (at: Offset) -> Unit, - onBack: () -> Unit, -): ToolbarAction? = when (shellActionKind(destination, manager)) { - ShellActionKind.SETTINGS -> ToolbarAction( - icon = Icons.Rounded.Settings, - contentDescription = correctedString(R.string.nav_settings), - onClick = { onOpenSettings() }, - ) - - ShellActionKind.DEBUG -> ToolbarAction( - icon = Icons.Rounded.BugReport, - contentDescription = correctedString(R.string.debug_open), - onClick = onOpenDebug, - ) - - ShellActionKind.BACK -> ToolbarAction( - icon = Icons.AutoMirrored.Rounded.ArrowBack, - contentDescription = correctedString(R.string.docs_back), - onClick = { onBack() }, - ) - - ShellActionKind.NONE -> null -} - -/** - * Moves the pager to [page] — instantly when the user has switched animations - * off, and with the usual glide otherwise. - * - * A tab tap is the movement people make most, so leaving it animated while the - * settings pages had become instant would have made the switch look broken from - * the very screen it lives on. - */ -private suspend fun PagerState.goToPage(motion: MotionSettings, page: Int) { - if (motion.enabled) animateScrollToPage(page) else scrollToPage(page) -} - -/** - * A settings page slides in across a third of the screen, not the whole of it. - * - * Named because the blur needs the same number: the shader is fed how far the - * layer really travels, and a second copy of "3" would silently stop matching - * the first the day the animation is retuned. - */ -private const val LayerTravelDivisor = 3 - /** * Whether [address] is plain `http://` — what the diary's sign-in warns about. * A blank address is not «insecure», it is «not configured»: nothing can be diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellMotion.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellMotion.kt new file mode 100644 index 00000000..3e71380c --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellMotion.kt @@ -0,0 +1,86 @@ +package com.lumenpearson.lessons.navigation + +import androidx.compose.animation.ContentTransform +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.foundation.pager.PagerState +import androidx.compose.ui.unit.IntOffset +import com.lumenpearson.lessons.core.designsystem.theme.MotionSettings + +/** How long a settings page takes to slide in over the tabs. */ +private const val PageTransitionMillis = 320 + +/** + * Forward pushes the old page off to the left; back slides it away to the right. + * + * One spec for the movement and the fade, rather than a tween on one and a + * spring on the other: given different curves the arriving page reaches full + * opacity while it is still visibly moving, and the leaving one disappears + * before it is off the screen. + * + * `SizeTransform(clip = false)` because settings pages are wildly different + * heights, and the default animates the slot's size *and* clips to it — which + * crops whichever page is taller for the length of the slide. + */ +internal fun pageTransition(forward: Boolean, motion: MotionSettings): ContentTransform { + // Instant, not quick. Scaling the durations towards zero would still slide + // the page — a two-frame slide is a flicker, which is worse than no + // animation for exactly the people who switch animations off. + if (!motion.enabled) { + return ContentTransform( + targetContentEnter = EnterTransition.None, + initialContentExit = ExitTransition.None, + sizeTransform = SizeTransform(clip = false), + ) + } + + val fade = tween(motion.durationMillis(PageTransitionMillis)) + val enter = slideInHorizontally(animationSpec = pageSlideSpring(motion)) { width -> + if (forward) width else -width + } + fadeIn(animationSpec = fade) + + val exit = slideOutHorizontally(animationSpec = pageSlideSpring(motion)) { width -> + if (forward) -width else width + } + fadeOut(animationSpec = fade) + + return ContentTransform( + targetContentEnter = enter, + initialContentExit = exit, + sizeTransform = SizeTransform(clip = false), + ) +} + +/** A stiffer spring is a faster one; see [MotionSettings.stiffness]. */ +private fun pageSlideSpring(motion: MotionSettings) = spring( + dampingRatio = Spring.DampingRatioNoBouncy, + stiffness = motion.stiffness(Spring.StiffnessMediumLow), +) + +/** + * Moves the pager to [page] — instantly when the user has switched animations + * off, and with the usual glide otherwise. + * + * A tab tap is the movement people make most, so leaving it animated while the + * settings pages had become instant would have made the switch look broken from + * the very screen it lives on. + */ +internal suspend fun PagerState.goToPage(motion: MotionSettings, page: Int) { + if (motion.enabled) animateScrollToPage(page) else scrollToPage(page) +} + +/** + * A settings page slides in across a third of the screen, not the whole of it. + * + * Named because the blur needs the same number: the shader is fed how far the + * layer really travels, and a second copy of "3" would silently stop matching + * the first the day the animation is retuned. + */ +private const val LayerTravelDivisor = 3 diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellPage.kt new file mode 100644 index 00000000..c3b3c3ef --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellPage.kt @@ -0,0 +1,54 @@ +package com.lumenpearson.lessons.navigation + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.ui.settings.SettingsSection + +/** + * Where the shell is, and how deep. + * + * The depth is declared rather than taken from an enum's ordinal, because an + * ordinal is a declaration order and reordering the list would silently reverse + * a transition. + */ +@Immutable +internal sealed interface ShellPage { + + val depth: Int + + data object Tabs : ShellPage { + override val depth: Int = 0 + } + + data object SettingsRoot : ShellPage { + override val depth: Int = 1 + } + + data class Section(val section: SettingsSection) : ShellPage { + override val depth: Int = 2 + } + + /** + * The guide, all of it. + * + * One destination rather than one per section, which is the change: the + * sections are peers on a pager and moving between them is a swipe, so the + * shell's `AnimatedContent` has nothing to do between them. It used to push + * a screen per section, with a depth per section to make the slide follow + * the finger; a pager does that itself, in the same gesture the home tabs + * use, and without a history to walk back out of. + * + * Deeper than a settings section, so opening the guide still slides forward + * and leaving it slides back. + */ + data object Docs : ShellPage { + override val depth: Int = 3 + } +} + +/** As much of the page as the toolbar's action button needs to know. */ +internal val ShellPage.destination: ShellDestination + get() = when (this) { + ShellPage.Tabs -> ShellDestination.TABS + ShellPage.SettingsRoot, is ShellPage.Section -> ShellDestination.SETTINGS + ShellPage.Docs -> ShellDestination.DOCS + } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellScaffold.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellScaffold.kt new file mode 100644 index 00000000..3b78df9e --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellScaffold.kt @@ -0,0 +1,114 @@ +package com.lumenpearson.lessons.navigation + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.zIndex +import com.lumenpearson.lessons.core.designsystem.component.ArrangingDismissLayer +import com.lumenpearson.lessons.core.designsystem.modifier.BottomBlurHeight +import com.lumenpearson.lessons.core.designsystem.modifier.StatusBarBlurExtent +import com.lumenpearson.lessons.core.designsystem.modifier.StatusBarBlurRadius +import com.lumenpearson.lessons.core.designsystem.modifier.TopBlurRampPx +import com.lumenpearson.lessons.core.designsystem.modifier.progressiveBlur +import com.lumenpearson.lessons.core.designsystem.theme.BottomBarGap +import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace +import com.lumenpearson.lessons.core.designsystem.theme.ScrollOffsetHolder + +/** + * One page of the shell, with its own toolbar riding on it. + * + * The toolbar used to be drawn once, above everything, and stayed still while + * the page moved under it — so opening settings slid a page in beneath a bar + * that was already showing that page's title. Here it belongs to the page, so + * the two travel together and each screen's bar arrives with it. + * + * The cost of that is one measurement per page instead of one for the app, and + * that is deliberate too: during a slide there are two toolbars, and a single + * shared height would be written twice per frame by two different bars. + * + * @param onTouchOutsideBar while the tabs are being arranged, what a touch + * anywhere but the bar does; see [ArrangingDismissLayer]. Null the rest of the + * time, when there is no layer and the page takes its own touches. + */ +@Composable +internal fun ShellScaffold( + edgeBlur: Boolean, + statusBarHeightPx: Float, + offset: ScrollOffsetHolder, + toolbar: @Composable (Modifier) -> Unit, + onTouchOutsideBar: (() -> Unit)? = null, + content: @Composable () -> Unit, +) { + val density = LocalDensity.current + val seedBarHeight = LocalBottomBarSpace.current + var barHeight by remember { mutableStateOf(seedBarHeight) } + val barHeightPx = with(density) { barHeight.toPx() } + + // Essentials' distance, not the toolbar's height. The bar measures around + // 60 dp here, so a fade tied to it only began where the toolbar already + // covered the list — the rows arrived sharp and were cut off rather than + // dissolving into it. `coerceAtLeast` is the one thing not copied: it keeps + // the guarantee the measured height gave, that the fade is never shorter + // than the bar it has to reach behind, on a device whose gesture inset + // makes the toolbar taller than Essentials' 130 dp. + val bottomBlurPx = with(density) { BottomBlurHeight.toPx() }.coerceAtLeast(barHeightPx) + + // This page's own scroll drives this page's own fade. The shell used to pick + // whichever screen was in front and hand one number to everybody, which the + // page sliding away then wore for the length of the slide. + // derivedStateOf, because the raw offset changes every scrolled pixel and + // the fraction it produces does not: past the ramp it is 1f and stays + // there. Read directly, this composable — the whole page, toolbar included + // — was invalidated on every frame of every scroll for a number that had + // stopped moving. The derived read only invalidates when the clamped value + // actually changes, which is a handful of frames per swipe instead of all + // of them. + val target by remember(offset) { + derivedStateOf { (offset.value / TopBlurRampPx).coerceIn(0f, 1f) } + } + val topFraction by animateFloatAsState(targetValue = target, label = "top_blur_fraction") + + Box(modifier = Modifier.fillMaxSize()) { + CompositionLocalProvider(LocalBottomBarSpace provides barHeight + BottomBarGap) { + // The blur goes on the content, never on the parent that also holds + // the toolbar: a bottom fade applied there would dissolve the + // toolbar along with the list running underneath it. + Box( + modifier = Modifier + .fillMaxSize() + .progressiveBlur( + blurRadius = if (edgeBlur) StatusBarBlurRadius else 0f, + topHeight = statusBarHeightPx * StatusBarBlurExtent, + bottomHeight = bottomBlurPx, + topFraction = topFraction, + showGradientOverlay = edgeBlur, + ), + ) { + content() + } + } + + // Between the page and the bar, so it takes every touch but the bar's. + if (onTouchOutsideBar != null) ArrangingDismissLayer(onDismiss = onTouchOutsideBar) + + toolbar( + Modifier + .align(Alignment.BottomCenter) + .zIndex(1f) + .onSizeChanged { size -> + barHeight = with(density) { size.height.toDp() } + }, + ) + } +} diff --git a/docs/design.md b/docs/design.md index c46b37df..dac37e0a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -109,7 +109,7 @@ does not apply. | `ui/modifiers/ProgressiveBlurModifier.kt` | `modifier/ProgressiveBlur.kt` | | `ui/components/modifiers/ShimmerModifier.kt` | `modifier/Shimmer.kt` | | `utils/ui/HapticUtil.kt` | `haptic/LessonsHaptics.kt` | -| `MainActivity` (the tab pager) | `navigation/LessonsApp.kt` | +| `MainActivity` (the tab pager) | `navigation/HomeShell.kt`, under `navigation/LessonsApp.kt` | | `ui/activities/SettingsActivity.kt` | `ui/settings/SettingsScreen.kt` | | `ui/composables/WelcomeScreen.kt` | `ui/onboarding/` — the introduction of the first run | From 6b3ac5a98f98cf57968659547fb1188e38931d30 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 13:23:11 +0300 Subject: [PATCH 05/43] Keep HANDOVER.md to where the work stands, and its history in docs/history.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HANDOVER.md had grown to 337 KB because every batch section stayed in it after the next one arrived, so the one document a new session starts from was four fifths record. It now carries the opening, «Where the work happens from here», the last two batches, the milestone table, and sections 5 to 8, which kept their numbers because the documents, the skills and the history refer to them by number. The «How to continue» cheat-sheet moved to the end of section 8. docs/history.md holds the rest, newest first: every older batch section, sections 1 to 4, and what sections 5, 6 and 7 no longer need — two section 5 bullets that stopped being true, fourteen section 6 subsections that retold rules CLAUDE.md carries or narrated batches that are done, and the section 7 items that were asked for and done. Two decisions from those subsections stay in section 6, as «Two things left in Russian on purpose». The move is verbatim: all 4077 non-blank lines of the old file are in one of the two, counted as a multiset. References that now point across the two files are fixed in the next commit. The history quotes every schema head there has been, and test_every_document_that_names_the_head_names_this_one reads every .md under docs/, so the file is left out of it the way HANDOVER.md always was; the test failed on the moved text without that. docs/README.md indexes the new file, CLAUDE.md counts ten documents, and the handover skill, the handover-keeper and the docs-keeper say how the chain now works: the new batch on top, and the one that falls off the last two to the top of docs/history.md. Co-Authored-By: Claude Opus 5.5 --- .claude/agents/docs-keeper.md | 4 +- .claude/agents/handover-keeper.md | 4 + .claude/skills/handover/SKILL.md | 32 +- CLAUDE.md | 11 +- HANDOVER.md | 3605 +------------------------- docs/README.md | 12 +- docs/history.md | 3611 +++++++++++++++++++++++++++ server/tests/test_schema_version.py | 11 +- 8 files changed, 3709 insertions(+), 3581 deletions(-) create mode 100644 docs/history.md diff --git a/.claude/agents/docs-keeper.md b/.claude/agents/docs-keeper.md index 762e9777..8f215faf 100644 --- a/.claude/agents/docs-keeper.md +++ b/.claude/agents/docs-keeper.md @@ -40,4 +40,6 @@ is a legitimate status; a claim that something was verified when it was not is n ## Not yours `HANDOVER.md` is working state, not part of the reference set — that belongs to the -`handover-keeper` agent. +`handover-keeper` agent. So does `docs/history.md`, although it sits in `docs/`: it is the +record of the batches `HANDOVER.md` has handed on, true of the commits it names, and is +never corrected to today's code. diff --git a/.claude/agents/handover-keeper.md b/.claude/agents/handover-keeper.md index aa2f1237..553d8064 100644 --- a/.claude/agents/handover-keeper.md +++ b/.claude/agents/handover-keeper.md @@ -28,3 +28,7 @@ project — and say four things: Name the branches, the PR numbers, the test counts and the schema head. Numbers are what a new session can check cheaply. + +Keep two batch sections and no more. The new one goes on top; the one that falls off the +last two moves, verbatim, to the top of `docs/history.md`, which is where every older batch +already is, newest first. The `handover` skill has the order and the references to fix. diff --git a/.claude/skills/handover/SKILL.md b/.claude/skills/handover/SKILL.md index bcb6d18d..cbb6a1d2 100644 --- a/.claude/skills/handover/SKILL.md +++ b/.claude/skills/handover/SKILL.md @@ -72,17 +72,29 @@ remembering them: - **The opening paragraph** — which pull requests merged, the SHA `main` is at, what is open (and «nothing is open» is an answer), whether `dev` is level, the schema head, and whether `EXPECTED_REVISION` moved. -- **The chain of batch sections.** The new one goes on top; the one that was «What the last - session added» becomes «What the session before it added», and so on down. Two sections - both claiming to be the last is the commonest mess here. -- **The milestone table**, whose last row grows with every pull request the milestone takes. -- **The test counts, which live in three places** — this file's cheat-sheet, the README's - «Honest status» table and `docs/architecture.md`. Take them from a real run, not from the - last document that mentioned them: `docs/architecture.md` once carried a corrected total - over a per-module breakdown that still summed to the old one, and the total hid it. +- **The chain of batch sections, which is two long.** The new one goes on top as «What the + last session added»; the one that was last becomes «What the session before it added»; + and the one that was before it leaves this file — verbatim, retitled «What the batch + before added: …» — for the top of `docs/history.md`, directly under that file's + introduction, so the history stays newest first. Two sections both claiming to be the + last is the commonest mess here. The file grew to 331 KB before this rule existed (#211), + because every batch stayed. +- **References across the two files.** A sentence that moves to `docs/history.md` and says + «section 5» or «above» now points into another file: name `HANDOVER.md` in it. Sections + 5 to 8 keep their numbers for exactly that reason. When a paragraph of section 5 or 7 + stops being true — somebody verified it, or the owner did it — it moves to the matching + «Moved out of section …» part at the end of `docs/history.md` rather than being deleted. +- **The milestone table**, under «The milestones», whose last row grows with every pull + request the milestone takes. +- **The test counts, which live in three places** — this file's cheat-sheet («How to + continue», at the end of section 8), the README's «Honest status» table and + `docs/architecture.md`. Take them from a real run, not from the last document that + mentioned them: `docs/architecture.md` once carried a corrected total over a per-module + breakdown that still summed to the old one, and the total hid it. - **Section 5, what nobody has verified**, which grows with every path that shipped without a test able to reach it. - **Section 7, what is left to the owner**, which shrinks when they do one of them. -A number written against a named commit is a record, not a claim, and is not rewritten: this -file reports the gates «at `d330d68`», and at that commit the count really was what it says. +A number written against a named commit is a record, not a claim, and is not rewritten: a +batch section reports the gates «at `d330d68`», and at that commit the count really was what +it says. That is also why `docs/history.md` is never brought up to date. diff --git a/CLAUDE.md b/CLAUDE.md index c2ddd6b5..2de2b516 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,8 @@ Three deliverables in one repository: android/ Kotlin / Compose / Glance, five Gradle modules server/ FastAPI + aiogram in one process, one database, Alembic migrations api/ thin Vercel entry point that re-exports server/app/main.py -docs/ nine documents plus an index (docs/README.md), all current, all English; +docs/ ten documents plus an index (docs/README.md), all English; nine are current, + and history.md is the record of every batch HANDOVER.md has handed on; docs/diaries/ holds the per-platform reference pages of diaries.md; docs/app/ (the in-app guide) and docs/legal/ (the terms and the privacy policy) are product text the APK bundles, Russian source and English twin @@ -634,7 +635,8 @@ points Hilt does not inject cleanly. - **`HANDOVER.md` at the root says where the work stands** — the branches, what the last session finished, what it deliberately left alone and what nothing has verified. It is working state, not part of `docs/`, so it is stale the moment it stops being updated: - re-check the PR and CI before trusting it. + re-check the PR and CI before trusting it. It carries the last two batches; every batch + before them is in `docs/history.md`, newest first, verbatim. - **A pull request of this session's own work is merged without asking.** The owner asked for that on 20 September 2026; it is their standing instruction, recorded in the `github-pr` skill with the five things to check first — CI green on the exact head, `mergeable_state` @@ -653,8 +655,9 @@ points Hilt does not inject cleanly. batch before. If the batch's own pull request has already merged, the update is its own commit and its own pull request — with a milestone, like every other. What drifts every time, and is not a judgement call, is listed in the `handover` skill: the opening - paragraph, the chain of batch sections, the milestone table, the test counts in their - three places, and sections 5 and 7. + paragraph, the chain of batch sections — the new one on top, and the one that falls off + the last two moved to the top of `docs/history.md` — the milestone table, the test counts + in their three places, and sections 5 and 7. - **`.claude/` holds the agent configuration, and it describes the shape rather than repeating this file.** `.claude/agents/` has one agent per area that has produced a defect here, carrying the fact that would have prevented it; `.claude/skills/` has the procedures diff --git a/HANDOVER.md b/HANDOVER.md index 716923b0..9fb947be 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -3,6 +3,8 @@ A working document, not part of the reference set in `docs/`. It describes **the state at the moment of handover**, so that a new session — human or agent — continues from the same place without reopening or redoing anything. +What every batch before the last two added is in [docs/history.md](docs/history.md), +newest first. Last updated: **27 September 2026**. **PRs #63 through #85, #128, #129, #133, #134, #140, #166, #186 and #187 are merged**; `main` is at `2a408d8`, the merge of #187, and `dev` is @@ -309,2405 +311,7 @@ has not been asked. #176's defect never reproduced on demand. #175's single sent looked at on a screen: reaching a password form needs a region's diary to answer. Nothing here changes what #186 could not answer: a thumb, a haptic, a real GPU, a real launcher. -## What the batch before added: the first walk of the app on a device, and the twelve defects it found - -Merged as `c26eace`. **What #186 moved.** Android: the widget picker's preview draws again -(#167); the widget follows a class switch made inside a live Glance session (#168); a look at -another school year no longer takes the current year's terms away (#169); a server that -cannot be reached is worded by the app, not by OkHttp (#177); «Схема unknown» is gone from -the about card (#172); the one-line widget sizes say «Ничего не задано» rather than «0 -предметов» (#173); a toolbar tab's highlight is a circle (#179); a dropped tab is drawn where -the finger left it (#180); the long press that opens the arranging mode also picks the tab up -(#181); a touch anywhere but the bar closes the mode and reaches nothing underneath (#182); a -scrolled section goes under the pill's round end (#183); segments in a picker's tray are as -far apart as they are from its edge (#184); the build scripts use `directories` rather than -the deprecated `srcDirs` (#185). Server: `tzdata` for Windows (#170). Tests: three that failed -on a Windows checkout pass there (#178). Project: shared Gradle run configurations in `.run/`. - -**The first batch made on a machine with an emulator (#109).** On 26 September 2026 the owner -handed the session Android Studio, an emulator and the live Telegram bot, and asked for every -«nobody has looked at this» to be looked at. It was walked on the AVD `Pixel_10_Pro_XL` -(API 37, `google_apis_playstore`, x86_64, 1344×2992 at 480 dpi, the emulator's GPU through the -host's RTX 3070), against a local server (`seed_demo`, «9А», plus a second class «10Б» in -Asia/Yekaterinburg) and against production, whose «11А» was driven from the bot in the -owner's own chat. Two builds were used side by side: the debug build from this branch, and -the release build the APK workflow made from `bd7c816`, already installed and joined to -«11А». - -### What was seen, by issue - -- **#156, crash reports and the backup — confirmed.** A real crash (`am crash`) wrote - `crash_reports/crash_…_00.log`; `bmgr backupnow` through the local transport, the files - deleted, `bmgr restore`: a probe file in `files/` and one in the `external` domain came back, - the report did not. Again with the transport flagged `is_device_transfer=true`: the same. - The Google transport was put back afterwards. The issue closes on this. -- **#119, warmup and `/start` — read.** See the opening paragraph. Closes. -- **#114, arranging the tabs.** The long press opens the mode (labels fold, the icons wobble); - a second touch dragging «Задания» to the first slot lands there; the reader stays on - «Календарь», which moves with its tab; back leaves the mode, not the app; the order - survives a force-stop. That was the build before #181; since it, the long press carries on - into the drag, and a recording of one injected touch shows the mode opening and the same - touch carrying «Календарь» a slot. **Not answerable on an emulator:** whether half a slot - is right under a thumb, and whether the haptic lands with the mode. -- **#115, the correction mode.** Outlines sit on the app's labels and never on subjects, - times or rooms; a long press on a row with a switch opens «Исправить строку» and leaves the - switch as it was; «Установлена v0.1.0» opens as `Установлена %1$s`; a long press inside the - editor does nothing. The editor lists two keys where two rows share one Russian text - (`settings_debug`, `debug_reports_open`) — by design, not filed. -- **#116, two classes and the join modes.** Joined, listed with «Показывается сейчас», both - ways out named. The widget follows a switch — and did **not** follow a second switch made - inside a live Glance session (#168, fixed). The production class «11А» turned out to be - invite-only already; its class code gets `403` «Этот класс принимает только по личному - приглашению из бота», the release phone that joined it earlier still syncs, and the app - words the refusal as «Этот класс подключает телефоны только по личному приглашению…». A - personal code from the live bot's «📱 Подключить телефон» (a spoiler, fifteen minutes, one - phone) linked the release build: «Телефон привязан · Роль: Владелец · можно - редактировать»; replaying the spent code answered `404`. The `429` was seen for the first - time: «Слишком много попыток. Попробуйте через 15 минут.» (`Retry-After: 866`). -- **#117, the upgrade path.** A debug build of `fa4fe0c` (before #140) was set up — old first - run, «9А», tabs rearranged — and `bd7c816` installed over it with `install -r`: the class - stayed, the first run did not come back, the tab order held, and the first sync was a - `304`. A later install over a build with a widget on the home screen kept the widget - drawing without re-adding it. The same APK re-signed with a fresh debug keystore was - refused with `INSTALL_FAILED_UPDATE_INCOMPATIBLE: … signatures do not match newer version`, - and the installed app was untouched — which is the sentence `docs/build.md` asserts. Both - builds were signed with this machine's debug key: the release keystore lives in CI. -- **#113, the widget's sizes.** Four launcher sizes, not twelve rungs, because the launcher - resizes by cells and the home screen had neighbours: 2×1 «ДЗ на послезавтра · 3 предмета»; - 2×2, about 195×226 dp, which lands on LARGE and cuts «Алгебра в 08:…»; 4×1; 4×2. At font - scale 2.0 the 4×1 still fits and the 2×1 reads «Д… 3 предмета» (#174). The picker's - preview was broken on every launcher from API 31 (#167, fixed). Stays open for the other - rungs and for the corner radii on a real launcher. -- **#111, the ribbon's cost — relative only.** Twelve flings of Monday's ribbon, `gfxinfo`: - debug SHADER p50 200 ms / NONE 250 ms; release SHADER 150 / NONE 200; the system Settings - app scrolled the same way at p50 150 ms, 88 % janky. The shader adds nothing measurable - above this emulator's floor; the floor itself is the emulator. With no lesson running the - ribbon renders one frame in ten seconds, so nothing redraws per frame when idle. Stays open - for a phone. -- **The first run, both ways in.** All five steps in Russian and in English; the legal links - online (GitHub, the English terms) and offline (the bundled «Privacy policy, Edition 1 of - September 25, 2026»). The diary way: the region list; Алтайский край's Госуслуги-only hand-off - to `netschool.edu22.info`; Амурская область's school search, which asked that region's live - «Сетевой город» server over TLS **from the phone** and got its real schools back — - kindergartens included; the «Моя школа» hand-off to `gosuslugi.ru/school`; the password form - with its host and the `http://` warning. No password was typed anywhere. -- **The calendar.** Week, month, the day's ribbon and list, «Подробно», the year picker, and - 2025/26 fetched on demand with «Загружаю год». The ribbon did not crash (#79's defect). -- **Offline and the server badge.** The cache stays on screen when the server goes away; the - about card's badge met a real server for the first time («Сервер: база и код разошлись» - on a `create_all` database, correctly). -- **Studio's Logcat**, read on the owner's request: the release build's periodic - `SyncWorker` ran eleven seconds against production, cold start included; WorkManager's - «onNetworkChanged() not implemented in … SystemJobService» on API 37 is the library's, not - ours; «Davey! duration=1046ms» opening a lesson sheet is a debug build's JIT on this - emulator's floor. - -### The defects, each filed before its fix - -| # | What was wrong | What it does now | -| --- | --- | --- | -| #167 | The picker's preview was «Couldn't add widget.»: a plain `` in `widget_preview.xml` | `FrameLayout`; `RemoteViewsLayoutTest` refuses any class RemoteViews will not inflate | -| #168 | Two redraws inside one Glance session drew the first snapshot: the widget stayed on the class just left | `WidgetRedraws` counts redraws, and a live composition re-reads when it moves | -| #169 | A sync of another year replaced the class row's terms; a `304` never put them back | `replaceWindow` keeps other years' terms and takes the window's own | -| #170 | The server did not start on Windows: no time-zone database | `tzdata` declared for Windows only, and left out of the bundle on purpose | -| #172 | «Схема unknown» on the about card | the server's sentinel is no revision, and draws no chip | -| #173 | «0 предметов» on the one-line widget sizes | «Ничего не задано», from the one place that words the count | -| #177 | OkHttp's English inside «Не удалось подключиться: …» and «Не удалось обновить: …» | the app's own sentences; `SyncMessage.Failed` carries no detail | -| #178 | Three tests failed on a Windows checkout (paths with `/`, a blank line without `\r`) | normalised; `JoinErrorTest` no longer asserts the #177 defect as correct | -| #179 | (the owner's request) a tab's press and focus highlight was a square | drawn inside the tab's `CircleShape`; the press still takes the whole box | -| #180 | (the owner's report) a dropped tab was drawn for a frame in the wrong place: tabs composed by position, and the selection read from the pager's index | tabs keyed by label and animated by where they are; the selection read from the tab being kept on | -| #181 | (the owner's request) picking a tab up took a second touch after the long press | one detector on the initial pass opens the mode and carries the tab; the long press stays a TalkBack action | -| #182 | (the owner's request) a tap outside the bar did not close the mode, and reached the page | `ArrangingDismissLayer` between the page and the bar | -| #183 | (the owner's report) a scrolled section was cut by a straight edge 8 dp inside the pill | Material's side padding moved inside the rows, so the pill's own round clip is what cuts | -| #184 | (the owner's report) segments in a tray 2 dp apart, 4 dp from its edge | the gap is the tray's inset; bare pickers keep Material's connected 2 dp | -| #185 | (the owner's screenshot of a sync) six warnings that `srcDirs` is deprecated in AGP 9.4 | `directories +=` with the same paths; `LegalBuildPropertyTest` matches the new line | - -Left open, with their reasons in the issue: **#171** (a join fetches the year twice, three -times once; seen on the build before #140 too), **#174** (small widget sizes), **#175** -(a repeated sentence on the sign-in form), **#176** (a stale join error that did not -reproduce the second time). - -Every fix was checked again on the emulator it was found on, except #173's wording, which -the widget at its current size does not draw (`SubjectCountTest` holds it), and #180–#184 — -see the next section. - -### The owner's toolbar, checked on the emulator while the owner used it - -#180–#184 came in one at a time over the evening and the night, each as a sentence and -most with a screenshot. Each has a Robolectric test that fails on the code before it: the -drop is read on its first frame (horizontal centres, to a dp and a half — the scale and the -jiggle both turn about the centre), the one-touch gesture is driven with the long-press wait -on the composition's clock, the layer is asked with the real bar on top of a page that counts -its own taps, and the two gaps are read as geometry. `ToolbarShellCallerTest` puts the bar -under a caller shaped like `LessonsApp` — the list latched, the order written and read back -some frames later — and asks for one commit and a row that stays where it was dropped. - -On the emulator, the check was a screen recording of one injected touch, cut into frames -with `ffmpeg`. It showed the one-touch pickup working, the round end of the pill clipping a -tab that slid out, and **two defects in this branch's own unmerged code**, fixed before the -merge and so not filed: the label that folds as the mode opens was on the bar's bouncy -spring, and with the drag already under way its dip below nothing carried a neighbour out -under the pill's edge for a third of a second (it now folds on `toolbarSettleSpring`); and -keying the tabs had taken the gap after each tab along with it, so a drop that moved the last -tab into the middle landed the tab behind it 8 dp short (the gap is `ToolbarGap` now, owned by -the slot). - -It also showed what could not be settled there: **the owner was using the emulator at the -same time.** The injected touch was once cancelled by the system for another device's -(«Canceling pointers for device 4»), the tab order changed between two screenshots with no -command of this session's in between, the guide was open where the calendar had been, and -Google Calendar came to the front mid-check. The final order that recording left in storage -was one no single drag of the injected touch could produce, and the same arrangement in the -JVM gives exactly one commit — so the device run is not evidence either way, and the session -stopped driving the emulator rather than fight for it. **Not seen on the device:** the drop -without its flash (#180), a tap outside closing the mode (#182), and #184. - -### The machine, and what it cost - -- **The emulator image's SystemUI crash-looped** on `SecurityException: Need - android.permission.BLUETOOTH_CONNECT` — its runtime permissions had been revoked — which is - also the Bluetooth crash in the owner's note to the bot. `pm grant` for every denied - permission fixed the running session; **the Quick Boot snapshot still held the revoked - state**, so every quick boot brought the crash back, and the long press on the launcher - stayed dead until a reboot. Saving a new snapshot with `adb emu avd snapshot save` froze - the emulator — it stalled writing `textures.bin` — and the stuck process had to be stopped; - the next start was a cold boot and came up healthy, with the grants in place. That freeze - briefly blocked the owner's own «Run» from Studio. -- **The Quick Boot revert.** A restart of the emulator mid-session quick-booted from a - snapshot taken before this session, which took back the debug app, its data, the widgets and - the permission grants: a build installed afterwards met a fresh first run. The release build - predates that snapshot and kept «11А», probably without the personal-code link made later. -- **C: had about 2 GB free**, which is why the emulator refused to start once («Your device - does not have enough disk space to run avd»). The AVD alone is 12 GB, 8.5 GB of it the - Quick Boot RAM image; `./gradlew clean` in this worktree gave back what its builds took. -- **Android Studio is set up** (none of it in this repository, all of it the owner's - machine): the repository root opened with `android/` linked as a Gradle project on JDK 21 - (`android/.gradle/config.properties`), `.claude/worktrees`, the venvs and the caches - excluded from indexing, a `server/.venv` for the Python plugin, local run configurations - for uvicorn, the seed, pytest as CI runs it (no source roots on `sys.path`), ruff and mypy, - Logcat favourites for this project, Kotlin auto-import, a project dictionary, and a 4 GB - heap (`studio64.exe.vmoptions` in the config directory). **Waiting for the next restart of - the IDE:** registering `server/.venv` as the Python SDK, turning the root module into a - Python one (which quiets «Unsupported Modules Detected»), and disabling the third-party - «Python Portable» plugin that fails to load on every start — the IDE rewrites those files - on exit, and the owner was using it. -- **The release keystore** (a folder on the owner's machine, handed over during the session) is PKCS12 - and came without its passwords, so nothing was signed with it and its certificate was not - compared with the build on the emulator. Before it replaces the key CI signs with: an APK - signed by a different key does not install over the one already on a phone (above, #117). - -### Gates - -At this branch's last commit before the close-out: `ruff check app tests scripts migrations` -clean; `pytest -q -n auto` **2024** passed (9 min 56 s here, against CI's four); -`python -m mypy` clean, 100 modules; `./gradlew test` **1438** (`:core:model` 125, -`:core:data` 537, `:core:designsystem` 112, `:widget` 113, `:app` 551); `assembleDebug` and -`assembleRelease` build, and a sync prints no deprecation. - -### What nobody has verified in this batch - -Everything in the list above that says «emulator» and is a question about a hand: the -threshold under a thumb, the haptics, TalkBack, a real GPU's frame times, Doze on a school -morning, the widget's other eight rungs. No diary was signed in to. Nothing was signed with -the release key. The Python SDK and the plugin change in the IDE wait for a restart. The -owner's toolbar requests are held by JVM tests and, on the device, only as far as the section -above says: #180, #182 and #184 were not seen there. - -## What the batch before added: «Сетевой город» on the server, and a way in through your own school's diary - -Open as PR #140, from `claude/school-diary-api-routes-cc4o1n`, on milestone 10 -(`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`). Twenty-two commits on -`fa4fe0c` when this was written, `4c34cb5` to `8bad211`, then the fixes of the review that -was running on the branch and this close-out. It is two batches on one branch, and both -halves of the project moved. - -The second part was planned in design documents and a decision record that stayed in the -session's scratch space, as #134's generator did. What they settled is in the commit bodies, -in #141 and in `docs/architecture.md`, so nothing needs them; but a session that goes looking -for a design document in the repository will not find one. - -### Part one: «Сетевой город» on the server (#139) - -Seven commits, `4c34cb5` to `9ceef0c`, and their documentation, `42fdf0a`. The project read -one diary, Петербург's, wired straight into `services/diary.py` and `/diary/signin`. This -part puts a seam between the service and the provider, adds a second provider behind it, and -reads either from the same bot and API. - -- **A provider-neutral diary seam** lives under `server/app/providers/diary/`: the shared - models, a `DiaryError` family (`PetersburgError` re-exported as an alias so nothing that - caught it breaks), a `DiaryProvider` / `DiaryConnection` `Protocol` contract, and a - `registry.py` whose `binding()` is the single resolver of a class's diary binding. - Петербург goes behind it **byte-for-byte unchanged**. -- **«Сетевой город»** (`server/app/providers/netschool/`) — ИРТех NetSchool, the main diary - of about twenty regions, one route set for all. It carries a region **allow-list** (the - only origins ever contacted — the SSRF guard), windows-1251 salted-MD5 password sign-in, - the weekly diary mapped onto the existing models (homework is assignment type 3), - keep-alive, and school search for binding. -- **The service dispatches by provider.** `POST /api/v1/diary/login` accepts optional - `provider` / `region` / `school_id`, and `services/diary_keepalive.py` keeps every live - «Сетевой город» session alive from `GET /api/v1/cron/tick` with `GET /webapi/context`, - within a batch cap and a time budget, never touching `last_used_at`. `TickOut` gained - `diary_sessions_kept_alive`, `diary_sessions_lost` and `diary_keepalive_failed`. -- **The bot binds and reads either diary.** An admin binds a class to «Сетевой город» through - a provider chooser → region → school-name search; the read path (`bot/handlers/diary.py`) - is provider-neutral, and the sign-in card names the bound diary in the genitive. -- **Three diary defects fixed (#136, #137, #138).** Revoking a member drops their diary - sessions and links, not just invites and subscriptions; `/diary/signin` re-checks the - class binding at submit and refuses **before** spending the ticket if the diary was unbound - or rebound after the ticket was issued; four false diary comments corrected and two dead - type names removed. - -Its gates at `9ceef0c`, a record of that commit: `pytest -q -n auto` 1668, `python -m mypy` -clean across 97 modules; Android was not touched. - -### Part two: a way in through your own school's diary (#141) - -Fourteen commits, `17c0473` to `8bad211`: four on the server, five on the phone, one for CI -and four of documents. - -- **The first run has two ways in.** After «Продолжить», the introduction and the - permissions, a family picks the class code, as before, or its own school's diary: the - region — all 89, found on every keystroke in Russian or English, by nickname, city, code, - the wrong keyboard layout or transliteration, or by typing a school's name — then the - school, searched on the region's own «Сетевой город» server, then the region's systems - with the recommended one highlighted and «Почему?» beside it, then the sign-in, then the - import under a wavy progress bar, then a summary. The path is a saved list of steps, - `OnboardingFlow`, in `android/app/.../ui/onboarding/`. -- **On that path the password never reaches our server.** The phone signs in to Петербург or - «Сетевой город» itself — over https, only to an origin in the bundled catalog, with no - redirects and no cookie jar (`core/data/.../upstream/`) — and hands the session to - `POST /api/v1/diary/session`, which reads once with it from its own address, seals it with - Fernet and answers with our diary bearer. A `password` key in that body is a `422`. The app - no longer calls `POST /api/v1/diary/login`; the endpoint stays for older APKs, and - `docs/api.md` and the bot's `/diary/signin` page now say plainly that on those two routes - the password passes through this server. -- **The phone knows what the server can do before a password is typed** - (`GET /api/v1/diary/capabilities`), every diary `503` says why in `X-Diary-Unavailable` - (`disabled`, `address-refused`, `upstream`), and a session the diary refuses from our - address is a `409` rather than `/login`'s `401`, because asking for the password again - would loop. `JoinResponse.diary` hands a joining phone its class's binding. -- **A phone that reads only its diary has a home of its own.** `ShellMode` is none, class or - diary: a phone in no class with a diary session opens on the diary, whose settings keep - «Дневник» and «Выйти из дневника» (#151), and periodic class sync is armed only in class - mode (#152). Every diary failure has its own words through `DiarySignInProblem` and - `DiaryProblemText` (#153). -- **The phone keeps what it reads.** `diary.db` is a second Room database, written only by - successful reads; `DiaryImport` fetches pupils, terms, timetable, homework and marks with - weighted progress and resumes from the phase that failed. The one unprompted read is a - refresh when the app comes to the foreground and the copy is older than 30 minutes; - `SyncWorkerSourceTest` fails if the worker or the widget ever names the diary. -- **The widget says which way in a phone took**: a diary-only phone is told «Дневник — в - приложении» rather than asked for a class code, and a phone with neither is offered both - ways. -- **The terms and the privacy policy exist and are linked.** «Продолжая, вы принимаете - Условия использования и Политику конфиденциальности» is always drawn under «Продолжить»; - `docs/legal/{terms,privacy}.{ru,en}.md` and `legal.json` are bundled in the APK, opened in - the browser when online and from the bundle otherwise, and also from «О приложении». - `LESSONS_LEGAL_BASE_URL` / `lessons.legal.baseUrl` becomes `BuildConfig.LEGAL_BASE_URL`, - https only, one per fork; `apk.yml` derives it from the repository it runs in unless the - repository variable of that name overrides it. -- **A catalog of all 89 regions** — `server/app/catalog/data/regions.json`, generated by - `scripts/region_catalog.py` from `docs/diaries/regions.md` and a hand overlay - (`scripts/region_catalog.toml`): each region's systems, which one is recommended and the - reason codes for it, and the allow-list's «Сетевой город» origins byte for byte. The phone - bundles the same file in place as its only source of a diary host, and `--check` and a - test fail when the survey or the allow-list changes without a regeneration. -- **An anonymous school directory.** `GET /api/v1/directory/school-regions?q=` answers which - regions a school may be in, from DaData; a name that exists everywhere («Школа № 5») is - answered `generic` without calling DaData. It is throttled at 20 calls per 15 minutes per - caller and capped at 4,000 of DaData's 10,000 daily requests, counted per Moscow day in - `usage_counters` (`services/quota.py`, migration `0016`), so onboarding cannot spend the - search the bot's create-class step depends on. -- **Known-answer vectors both halves run.** `server/tests/vectors/diary_protocol.json` pins - both sign-in protocols, the login cleaning and the parsing of raw answers; the Python tests - and the Kotlin port run every case, so the two implementations cannot drift apart silently. - That proves they agree, not that either is right. -- **Each CI job runs whenever a file its tests read changes** (#159), not only its own - folder — `docs/deploy.md`, `docs/build.md`, `docs/diaries*`, `docs/legal/`, the catalog - and the vectors included. - -### The defects, each filed before its fix - -Twenty-one, on top of part one's three (#136–#138): - -| Issue | What was wrong | Fixed in | -| --- | --- | --- | -| #145 | «📒 Мой дневник» kept reading the «Сетевой город» region a class had been rebound away from | `6fa1c6e` | -| #146 | the keep-alive could overwrite a credential a diary read had rotated while the ping was in flight | `6fa1c6e` | -| #147 | a sign-in without `cacheVer` sent the word `None` upstream as `ver` | `6fa1c6e` | -| #148 | malformed «Сетевой город» sign-in answers escaped the diary errors as `500`s | `6fa1c6e` | -| #149 | the school search kept a result whose id was JSON `true` and bound the class to school 1 or 0 | `6fa1c6e` | -| #150 | comments and documents described a CA bundle, a breaker, a region order and a password route that do not exist, and the bot told families their password went «прямо в дневник» | `6fa1c6e`, `0a9a188`, `6281dea`, `5efca54` | -| #151 | a phone that left its last class kept its diary sign-in but could neither open «Дневник» nor sign out of it | `b19e6b2`, `c032ff2` | -| #152 | a phone in no class had its periodic sync re-armed on every cold start | `b19e6b2`, `c032ff2` | -| #153 | the diary said «HTTP 429», «Дневник не отвечает» for a switched-off diary, and a raw «HTTP 504» | `6fa1c6e`, `b19e6b2`, `c032ff2` | -| #154 | the join screen, settings and the guide promised a default server the APK does not have | `c032ff2`, `5efca54` | -| #155 | the design credit ran into the word before it, «по мотивамEssentials» | `ce9c749` | -| #156 | crash reports went into the cloud backup although the first run says they stay on the phone | `ce9c749` — **stays open** until a phone confirms it | -| #157 | comments and `docs/design.md` described a four-screen first run and a six-character class code | `c032ff2`, `5efca54` | -| #158 | the bot's sign-in page sent a «Сетевой город» family to Петербург's diary on an unreadable answer | `0a9a188` | -| #159 | CI skipped the server tests that read `docs/deploy.md` and `docs/build.md` when only those changed | `ba9170c` | -| #160 | contributor and agent documents quoted a stale test command, stale counts, wrong secret names and milestone facts | `8bad211` | -| #161 | a join whose screen was gone before it landed left its result behind; the next «Добавить класс» sheet closed on it, and the first run could skip the class's diary sign-in | `061a716` | -| #162 | Dependabot and the issue templates applied labels the project does not have, so bumps arrived bare and reports outside `type:` and `status:` | `f31e5ed` | -| #163 | the join and diary sign-in throttles counted before they recorded, so a burst went past them (24 wrong passwords against a limit of 10) | `6b0878f` | -| #164 | the server's checks assumed SQLAlchemy 2.0 while every fresh install resolves 2.1: one test compared SQL without casts, and mypy failed on `main` | `d208251` | -| #165 | a session registered from a phone names its own login, unchecked, and that login keys another family's corrections | `e01443d` — corrections are now the child's, by the owner's decision | - -Twelve more, from an adversarial review of the new Android data layer, were fixed in -`9c797a2`, each with a test that failed before its fix. They are listed in that commit's -body and have no issues of their own: they were in code this branch adds, and none of it -had reached `main`. The same holds for the thirty findings of the second review of the -screens (`061a716`, 31 in all, one of them #161) and for twenty of the audit of the server -half (`6b0878f`, 22 in all: #163 fixed there, #165 in `e01443d`). The change for #165 had a -review of its own: five lenses, two refuters per finding, 17 of 23 findings confirmed. All 17 -are fixed in the same commit, and its body lists them. - -**One commit body is wrong, and the code is right.** `6fa1c6e` says rebinding a class to -another *school* expires its diary sessions. `services/diary.expire_off_binding` expires them -when the provider or the region changes and keeps them for another school in the same region, -because a «Сетевой город» session is an account on the region's server rather than on one -school. The documents follow the code. - -### Schema - -`EXPECTED_REVISION` is `0017`. Production was at `0014`, three revisions behind, until the -transaction below: - -- **`0015`** (`0015_diary_provider_columns.py`) adds five nullable columns to - `diary_sessions` — `provider`, `region`, `kept_alive_at`, `keepalive_attempted_at`, - `upstream_ok_at` — and three to `classes` — `diary_region`, `diary_school_id`, - `diary_school_name`. A `NULL` provider means Петербург, the only diary before the column. - Its downgrade expires every non-Petersburg session before dropping the columns that tell - one apart. -- **`0016`** (`0016_usage_counters.py`) creates `usage_counters` and nothing else. -- **`0017`** (`0017_corrections_per_child.py`) is data only (#165). It rewrites - `diary_overrides.login` from a login to the child's scope: `CHILD:petersburg`, or - `CHILD:netschool:` and the regional server's host. It deletes the branch-only - «Сетевой город» hash-keyed rows, which could no longer be read. Where two rows corrected - one field of one child, it keeps the newest. On PostgreSQL it takes a lock first. It is a - third shape, «a rewrite of a key»: free where there are no rows, and **after** the merge - where there are, for the reasons its docstring and `docs/deploy.md` give. - -`0015` and `0016` are additive, and rewrite and destroy no row. `0017` would destroy rows -only where there are corrections, and production had none. So all three went on **before** -the merge, together, through the Neon connector. The DDL was taken from the revisions -rendered offline for PostgreSQL, and it matched the models' own DDL statement for statement. -The database's state was read first, and `alembic_version` was stamped in the same -transaction, last. - -**Applied on 26 September 2026 at 12:26 UTC, before the merge, as one transaction through -the Neon connector.** The owner had allowed the migrations on one condition: that the code -they serve has no known defect. That was met once #165 was decided and fixed in `e01443d`, -and CI went green on that commit. The database was read twice first, at 11:22 and at 12:25 -UTC. Both reads showed head `0014`, none of the eight columns, no `usage_counters`, **0** -rows in `diary_overrides` (0 of them legacy «Сетевой город» keys), **0** diary sessions and -**1** class. The transaction ran the eight `ADD COLUMN`s of `0015` and the `CREATE TABLE` of -`0016`. Then `0017` ran its lock, its two deletes and its rewrite, and last came the stamp -`UPDATE alembic_version SET version_num = '0017' WHERE version_num = '0014'`. Every -statement was taken from the revisions rendered offline for PostgreSQL, which matched the -models' DDL. Read back afterwards: head `0017`, one stamp, all eight columns nullable with -the declared types and widths (`VARCHAR(32)`, `BIGINT`, `VARCHAR(300)`, `TIMESTAMP WITHOUT -TIME ZONE`), and `usage_counters` with primary key `(scope, day)`. There were still 0 -corrections, 0 sessions and 1 class, so nothing was rewritten and nothing was destroyed. -Until #140 merges and deploys, the running code is older than the database, and -`/api/v1/warmup` answers «База впереди кода…»: the window the correct order creates. The one -thing the window could lose is a correction typed through the old `/diary/login` before the -deploy, which would be filed under a login. No diary session existed to type one. - -### What was deliberately left alone - -- **No Госуслуги (ЕСИА) sign-in, no WebView and no cookie capture, anywhere.** A Госуслуги - session is a session to the person's whole state-services account. ТОР «Моя школа» and the - three Госуслуги-only «Сетевой город» regions (`altai-krai`, `primorye`, `tula`) hand off to - the official site instead, and a generator test refuses any catalog field for an in-page - sign-in. This is the code's answer to #135's second and third questions; the issue stays - open for the owner to close. -- **A diary-only phone's widget, «Сегодня», «Календарь» and alerts show nothing from the - diary** — - #142, `status:next`, no milestone. Feeding them would mean a background read, which would - count as the family's activity and keep a session alive with nobody behind it. -- **A diary session opened on the phone is invisible to the bot** — #143, `status:someday`, - no milestone. Phone-registered rows carry no Telegram account and no class. -- **A fresh install has no default server** — #144, a decision for the owner, no milestone. - The address is asked for where it is first needed; there is no - `LESSONS_DEFAULT_SERVER_URL`. -- **The class's binding reaches the phone in `JoinResponse.diary` only**; `ClassOut` does not - carry it. -- **The password routes stay.** The bot's `/diary/signin` and `POST /api/v1/diary/login` - still pass a password through this server, for the bot and for older APKs, and the texts - now say so. -- **The phone does not refuse a login longer than the server's 200 characters**; the server - answers `422` at registration, which the phone reads as an app bug. -- **Left from part one:** the refresh-token grant (LoginType 9) is in the client and - unverified live, and SignalR reports — final marks, attendance letters — are not read. -- **The older sections of this file quote the milestones' old titles** where that is what - they were called at the time; the table maps each to its new one. - -### Gates - -Run, not quoted. The server was run on the branch at `e01443d`, against **SQLAlchemy -2.1.1**, which is what CI and Vercel install now (#164): `ruff check app tests scripts -migrations` clean; `pytest -q -n auto` **2024** passed (1634 on `main`); `python -m mypy` -**Success** across **100** modules (84 on `main`). The alembic chain from nothing lands on -`0017`. The Android tests were run at `061a716`, -and Gradle found every test task up to date against the sources at `f31e5ed`: `./gradlew -test` **1408** (968 on `main`), with `:app` 548, `:core:data` 532, `:core:designsystem` 99, -`:core:model` 125 and `:widget` 104; they were rerun with `--rerun` after the texts of -#165's fix changed, with the same counts. `assembleDebug` and `assembleRelease` were last run -locally at `061a716`, and CI builds both on every push. A checkout set up before 2.1 was -published keeps SQLAlchemy 2.0.54 until it is upgraded. The suite passes on both, and a -mypy run on 2.0 does not see what 2.1's typing sees. `b19e6b2` and `c032ff2` report the -grep for Russian in Kotlin finding nothing new but `UpstreamMarkers.kt`, the diaries' own -words matched in their answers. It was not re-run for this close-out, and no Kotlin has -changed since `061a716`. - -### What nobody has verified in this batch - -Section 5 carries each of these with the reason it is unverifiable. In short: - -- **Nothing has met a live diary.** «Сетевой город» has never been signed in to for real, on - the server or through the phone's port, and Петербург never through the phone. -- **Whether a session opened on a phone is accepted when our Frankfurt server replays it** is - open for both diaries. A `409` is the designed failure; the owner's first live session - decides it. -- **Nothing has run on a device**: the first run, the swap between the three homes, the - handoffs to the browser, the backup exclusion (#156), TLS against the regional servers, - Android's own windows-1251, `diary.db` on a real phone, the widget's new sentence on a - launcher. -- **DaData**: whether its company rows carry `region_kladr_id`, the codes of the four regions - admitted in 2022, and whether its day turns at Moscow midnight. -- **The legal texts have never been read by a lawyer.** -- **The throttles' record-then-count (#163) is proven on SQLite only.** On PostgreSQL it - rests on READ COMMITTED showing each statement every commit before it, and it has not run - against a live database. Neither has `alembic upgrade head` on an empty PostgreSQL. The - permission system refused a local server, so `0015`'s guard for a database that `0001` - built is proven offline and on SQLite. - -## What the batch before added: the electronic diary of every Russian region, and the routes each platform exposes - -Merged as PR #134 (`fa4fe0c`), from `claude/school-diary-api-routes-cc4o1n`, in the milestone -then called `v0.8.0 — On a device`; it closed #130. **Documentation only.** No file under -`server/`, `android/` or `.github/` changed, and there is no migration. - -The project reads one diary, Петербург's. Until this batch nothing in it said what a school -anywhere else keeps its marks in, how a client signs in there, or which routes it exposes. -So the question #127 names, «что делать, если у нас не Петербург», could not even be scoped. - -- **`docs/diaries.md`** maps all 89 federal subjects to the platform their schools use in - September 2026. It gives what each region left behind and where it is moving, and a table - of the platforms: how a client signs in today and which open client to read first. It - describes the sign-in pattern across the country, what the survey means for this project, - and what it does not cover. The mandatory regions are marked and had a deep check of their - own: Санкт-Петербург, Москва and the eleven of the «Моя Школа» region picker. -- **`docs/diaries/`** holds one page per platform, nineteen in all, with 1916 routes - between them. Each row gives the method, path, authentication, parameters and response, - the client it was read from, and whether it is *current*, *legacy* or *uncertain*. - `regions.md` beside them carries the quoted, dated evidence for every region. -- **The index, `CLAUDE.md`, `README.md`, `docs/architecture.md` and the `docs-keeper` - agent** now count nine documents and link the survey. - -### How it was made, and how far it can be trusted - -It is the method `providers/petersburg/` was written by, at the scale of the country: - -- **Routes.** Every open client found on GitHub, GitLab, Codeberg, PyPI and npm was cloned - and read. A second reader grepped each route back to its source, and a third dated it. -- **Regions.** Every region was researched, then re-checked by an independent pass told to - refute the first. A completeness critique listed what both passes had missed, and a second - round went after that list. -- **Official apps.** Two platforms were read from their official apps: ТОР «Моя школа» from - «Госуслуги Моя школа» 5.0.0.454, and ЭПОС.Школа from «ЭПОС» 1.53. ТОР has no open client; - ЭПОС.Школа's only one dates from 2022. - -**Nothing was tried against a live diary.** Every diary host refuses a connection from a -cloud session. So a route in these pages is what a client's code sends, never what a -server was seen to answer. #121 records the same caveat for the one provider that exists, -and each page dates its clients for this reason. - -**The generator is not in the repository.** The pages were rendered from the research data -by scripts that stayed in the session's scratch space, because they read agent transcripts -that exist nowhere else. A later correction is an edit to the Markdown. - -**Other people's credentials were redacted.** Several public clients hard-code the OAuth -`client_id` / `client_secret` pairs of Дневник.ру and «Сетевой город». Every one is -`` in the pages, and the assembly refused to write a page that still held one. - -### What it found that decides the next provider - -- **A password is now the exception.** `/diary/signin` is built around Петербург's email - and password, and that is unusual. In most regions Госуслуги is the only door, and the - clients that last keep a token a person brought from a browser. A second provider cannot - reuse `/diary/signin` as it stands. -- **Twenty regions moved to ТОР «Моя школа» on 1 September 2026**, by the official list of - its first wave. They share one API, and one batched call carries the whole diary. But - the sign-in is Госуслуги's own and its `client_secret` is signed on Госуслуги's side. - Nobody outside has got in except through a person signing in inside a WebView. Whether - that is acceptable under Госуслуги's terms was not reviewed. -- **«Сетевой город» is the largest group that still takes a password.** It is one route set - on each region's own server, and it is the main diary of 20 regions, though - some of them allow Госуслуги only. It is the obvious first candidate, and the МЭШ family - comes after it. - -### What was deliberately left alone - -- **Provider code.** #130 asked for the map and nothing else. Which provider comes second, - and how it signs in, is the owner's decision. It is filed as #135 and set out in - section 7. -- **The teacher's side, and a parent with several children.** The open clients barely touch - either, and the overview says so rather than guessing. -- **The generator**, for the reason above. - -### Gates - -No file the gates read changed, so `ruff`, `pytest` and `./gradlew test` were not re-run. -CI's path filter skipped the Server and Android jobs on every head, and «What changed» -passed. What was checked instead, on the final head: - -- every relative link and anchor in the new and touched documents resolves; -- every table row has its header's column count; -- the redaction scan finds no credential. - -## What the batch before added: the tracker (#128), its rule (#129), and their close-out (#133) - -Merged as #128 (`3c3b728`), #129 (`a43c6e8`) and #133 (`5a77d14`). Documentation and agent -configuration only. No model, endpoint, screen or test changed, so the gates stood exactly -where #85 measured them. - -- **#128** opened the issue tracker: forty-two issues, #86–#108 closed and #109–#127 open, - labelled `type:`, `area:`, `status:` and `needs:`. It also moved the work to a local - machine with an emulator and a phone, and wrote down what that unlocks and what it still - cannot do. That is the section «Where the work happens from here» above. -- **#129** made it a standing rule that a found defect becomes an issue before it becomes a - fix, with one issue per finding, `Closes #NN` in the pull request and both numbers in the - release notes. The rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` - skills. The owner created the ninth milestone, `v0.8.0 — On a device`, and #129 put its - number into the tables. -- **#130** was opened by the owner on 23 September: map every region's diary platform and - the API its open clients use, as a document in `docs/`, with no code. It is `status:now` - and needs no device, so it is the natural first task for a session that has none; #134 - is that task. -- **#133**, the close-out, fixes two defects that were found while writing it, and each got - its issue first. **#131**: #129 left the milestone table's `Dependencies` row stranded below - two paragraphs, so GitHub drew a table without it. **#132**: `CLAUDE.md` still quoted 1610 - server tests, while the other three places say 1634. `CLAUDE.md` is not on the `handover` - skill's list of places where the count lives, which is how it drifted. The list is left as - it is: the `Commands` line is the only count in `CLAUDE.md`, and one more place to remember - is what this issue now records. - -**Nothing new has been verified.** Everything in sections 5 and 7 still stands, and both -already point at their issues. `/api/v1/warmup` has still not been read since #61 (#119). - -## What the batch before added: the gesture #84 shipped did nothing, and the variables nobody could find - -Merged as PR #85 (`ef07739`), in the milestone `v0.7.0 — Оптимизация`. It is one defect, and -it is the defect that the feature merged an hour earlier did not work: **a tab dragged to -another slot went back where it came from and the order was never stored.** On the screen it -looked right the whole way — the icons slid, the row opened a gap, the neighbours moved — -because all of that is recomputed every frame. Only the drop was wrong, and the drop is the -part that is remembered. - -### Why it survived #84's tests - -`Modifier.pointerInput` keyed on `Unit` starts its coroutine once and never restarts it, and -its element compares equal on the key alone — so the node is never even handed a newer -lambda. Whatever `detectHorizontalDragGestures` closed over on the composition that opened -the mode is what it still calls minutes later. `held` and `dragPx` survived that, being -state reads through a delegate; **the landing slot did not**, being a plain `val` computed -in the caller's composition. Every drop therefore asked where the tab had been *before* the -finger moved, which is no slot at all: `moveItem` refused the out-of-range index, the order -came back unchanged, and the preferences were written with the order they already held. - -Nothing in #84 could see it. `ToolbarReorderTest` asks the arithmetic in pixels with no -composition, and it was right; `ToolbarReorderModeTest` asks which callback a press raises, -and those were right too. **Between the two sat the one question neither asked — whether -the number the gesture computes is the number the gesture reports.** #84 wrote down that the -drag was driven from no test, and gave a good reason (a synthetic swipe of «half a slot» -measures Robolectric's densities rather than the gesture). The reason was sound and the -conclusion was not: a drag of ten thousand pixels lands on the last slot under *any* -density, because `dropIndex` parks a finger that has left the bar at the end. That is what -`ToolbarDragTest` does. Two of its first three went red on the shipped code straight away; -the third passed, and passed for the wrong reason — see the trap below — which is worth more -than the two that failed, because a test that is right by accident is how a defect survives -a batch in the first place. - -The fix is `rememberUpdatedState` on the four gesture callbacks — the same pattern -`Corrections.kt` in this module already uses for exactly this reason, which is the part that -stings. Restarting the coroutine instead, by keying `pointerInput` on something that -changes, would cancel the gesture under the finger every time the drag moved a pixel. - -### And the frame #84 left deliberately is closed - -That close-out recorded a one-frame flicker at the end of the gesture and said the proper -fix — the component dropping its permutation by the identity of what it is handed rather -than by the mode closing — risked silently double-applying a drag. It does the opposite: -`working` is now keyed on the order of the labels it permutes, so a list swapped under a -live permutation replaces both in one step instead of two. A caller that hands the committed -order straight back is now drawn correctly, which is the case that would have double-applied -before, and the shell's latch is no longer load-bearing for that — it stays because it keeps -two drags of one session describing permutations of the same list. - -The test for it hands the bar its own reported order mid-mode. On the code without the fix it -drew «Задания, Сегодня, Календарь» for a drag that asked for «Календарь, Задания, Сегодня» — -the permutation applied twice, which is what the comment in #84 predicted and priced as too -risky to close. - -One trap in the test itself is worth carrying: `translationX` here is a `graphicsLayer`, and -`positionInRoot` — which every bounds assertion goes through — counts that layer in. Read six -frames after the finger lifts, a tab that had not moved at all sorts into the place the drag -had merely carried it, and the assertion passes against the very defect it was written for. -The springs are given 120 frames now. - -### The configuration nobody could find in one place - -Two questions came out of a screenshot of the Vercel variables, and the answer to the first -was «yes, in `docs/deploy.md`», which is only two thirds of an answer. **`server/.env.example` -— the file every set of instructions says to copy — was missing three of the eleven**: -`WEBHOOK_SECRET`, `CRON_SECRET` and `BOT_USERNAME`. Two of those three are ones a deployment -refuses to start without, so the cost of each was a deploy to find out. It was also missing -`TRUSTED_PROXY_HOPS` and `WEBHOOK_PATH`, which are real knobs nothing outside `config.py` -mentioned. It now carries all fifteen settings the code reads, each with what empty means, -and says in prose why the sixteenth — `VERCEL` — is deliberately not a line in it. - -Nothing could have caught that. **A missing variable is not a missing field:** every setting -has a default, which is the whole reason the refusal-to-start check exists, so the server -runs perfectly well against an example file half a year behind. `tests/test_env_example.py` -is the guard — four tests, pinning the file to `Settings` in both directions, pinning the -prose about `VERCEL`, and pinning that every secret a workflow reads is named in -`docs/build.md`. Each was watched going red: the first against the file as it was this -morning, the last against a ninth secret added to a workflow. - -Two documents grew rather than one, because the configuration lives in three places and no -page said so. `docs/build.md` opens with **«From a clone to a working pair»** — four steps, -each one saying how much of `.env` it needs, from «the API alone, no Telegram account at -all» to the school search — and then **«The other place variables live»**, a table of the -eight secrets GitHub Actions holds with what reads each and what happens without it. The -three facts worth more than that table: `ci.yml` reads no secret at all, which is why a -fork's pull request runs the whole gate; `CRON_SECRET` is one value in two places and -**nothing checks that they match**, so a mistype is a `403` on a schedule with both halves -looking configured; and `DIARY_SECRET` is deliberately *not* an Actions secret, because -nothing there imports the server's code. `docs/README.md` gained the row that sends a reader -to the right one of the three. - -### Gates, measured on this branch - -`./gradlew test` **968** (was 964) and both assembles. The four new Android tests are -`ToolbarDragTest`: what a drag reports, where the row is drawn afterwards, what a second drag -reports, and what happens when the list is swapped under a live permutation. On the server, -`ruff` clean, `python -m mypy` clean across 84 modules, `pytest -q -n auto` **1634** (was -1630) — the four are `test_env_example.py`. Database at `0014`. - -### What nobody has verified in this batch - -**Nothing of the configuration work is proved against a real deployment.** The example file -and the two document sections are checked against `config.py` and against the workflows by -tests, which is the half that can be checked; that the eleven on Vercel are the eleven that -should be there, and that `CRON_SECRET` matches what the external cron sends, is the half -nothing here can see. - -**Still nothing on a phone.** The drag now reports the right slot in a JVM test with -Robolectric's densities and the clock held by hand; whether half a slot is the right -threshold under a real thumb, and whether the wobble is plausible, are the same two -questions #84 left open and neither has been asked of a device. The APK for #84 was built -against the code that did not work, so it is worth nobody's time — the first useful install -is the one built after this merges. - -## What the batch before added: the home screen's tabs, arranged by the person using them - -Merged as PR #84 (`1b32623`), in the milestone `v0.7.0 — Оптимизация`, three commits — -`bf80a9d` the two halves, `14f5374` the shell wiring, `05e0c47` the close-out. **Read the -batch above before trusting anything here**: the drag it describes did not report what it -computed, and the section that follows was written believing it did. Asked for -in one sentence: «сделай так, чтобы при зажатии кнопки вкладки на главной, можно было -переставить, включался режим перестановки и кнопки потрясывало как иконки на ios». -Long-press a tab on the home screen; it and its neighbours wobble; any of them can be dragged -somewhere else; the order is the reader's from then on and it is remembered. **Nothing -outside `android/` was touched**, which is why CI's server job is skipped rather than green. - -### The risky half was not the gesture - -**Everything downstream stopped holding a position and started holding a tab.** The pager's -index used to mean one destination for the life of an install; it now means whichever tab is -in that slot today, and every place that had quietly relied on the old meaning had to be -found. The scroll-offset holders are keyed by tab rather than by index — an index-keyed one -hands an arriving screen the fade depth of the one that left. The pager carries a key per -tab, so each keeps its own saved scroll instead of inheriting whatever had been filed under -«page 1». And the default tab is latched as a **tab** rather than as an index, which after a -reorder would have sent predictive-back home to a screen nobody chose. - -The shell's four back handlers became one rule in one function (`navigation/ShellBack.kt`), -which is what makes «a back press leaves the arranging mode» a thing a test can ask at all; -without it the press would have been taken by the predictive gesture and left the app. - -The bar is handed a **latched** copy of the order for the life of the mode. It was thought -load-bearing — that feeding the committed order back mid-gesture would apply the drag a -second time — and #85 made that false: the component now drops its permutation when the list -it permutes changes. The latch stays for the other reason, which is that both drags of one -session then describe permutations of the same list. - -### Two deliberate departures from iOS, each a decision rather than a shortfall - -- **The long press does not flow into the drag.** One gesture would mean a tap detector and - a long-press-drag detector on one node, and which of them sees an event turns on which - claims the press — behaviour that cannot be settled by reading, and that nothing in this - module can exercise, there being no instrumentation here. -- **A tap inside the mode closes it** rather than navigating. There is no wallpaper under a - floating bar to tap instead. - -### Three things the tests found and the code did not - -- **`IconButton` cannot carry a long press.** Material's has no `onLongClick`, and a - detector added to the modifier handed to it never fires, because it applies its own - `clickable` *after* that modifier and the press is claimed before anything passed in can - see it. It was written with an `IconButton` first, the long press simply never arrived, and - a test said so. The tab is a `Surface` with one `combinedClickable` now. -- **The drag threshold was asymmetric by a pixel.** `roundToInt` breaks a tie towards - positive infinity, so exactly half a slot rightwards rounded to one slot and exactly half a - slot leftwards to none. `dropIndex` rounds away from zero. -- **The lesson of #83's floor test decided the shape of this one.** That replacement test - kept its own copy of the arithmetic and stayed green against the very mutation it was - written for, so the drag's arithmetic is a file of its own here — - `component/ToolbarReorder.kt`, pure, pixel-facing, knowing nothing about a pointer — and - the tests call the production expression rather than a second copy of it. - -### The jiggle runs only when it is allowed to - -It runs **only while the mode is open** and **only when the reader has animation on**. The -first is not a nicety: an infinite animation means Compose's clock is never idle, so every -test that composed the bar would hang rather than fail — the trap this project has now paid -for twice. The second is that somebody who turned animation off said that about their phone, -not about this bar. Each icon is out of phase with its neighbours, because a row rotating in -lockstep reads as the bar itself flexing rather than as several things each loose in its own -right. - -### Also, and deliberately - -- **The settings default-tab picker lists the tabs in the reader's own order.** It is a - picture of the bar it is about, and two orders on one screen is a mapping exercise to - answer one question. -- **A stored order repairs itself rather than being trusted.** It is a list of member names, - and every way it can be wrong has an answer: an unknown name is dropped, a member the - string does not mention is appended in declaration order, a duplicate collapses, whitespace - is ignored, and nothing stored at all is the declared order. The appending is the clause - that matters — the day a fourth tab is added, every installed phone holds a three-name - string, and the new tab has to appear rather than the bar quietly losing it. -- **`SELF_STUDY` keeping its lessons, and the other non-decisions from #83, still stand** — - the lookahead row, `DayKindName`'s four kinds against `/bundle`'s six, the missing rule - against a composable reading `BuildConfig`, and `CONTRIBUTING.md`'s `python -m pytest`. - None of them was touched here and none of them has moved. - -### Gates, measured on this branch - -`./gradlew test` **964** (was 929) and both assembles — and see #85, which found that four -of those tests covered every part of the gesture except the one that was broken. The -thirty-five new tests are 10 on -the drag arithmetic, 5 on the reorder mode's contract, 8 on the stored order's repair, 11 on -the shell's index arithmetic and its back rule, and one pinning the default order — the bar -somebody who has never opened the setting sees, which is also what every screen gets while -the preferences file is still being read. The server half was not touched at all and -its gates stand at #83: `ruff` clean, `pytest -q -n auto` **1630**, `python -m mypy` clean -across 84 modules. The database stays at `0014`. - -The count is corrected in all three places it lives — this file's cheat-sheet, the README's -«Honest status» table and `docs/architecture.md`. - -### What nobody has verified in this batch - -**Nothing here has been seen on a phone.** Whether the wobble is plausible, whether half a -slot is the right threshold under a real thumb, and whether the two-step gesture reads as -deliberate are all unmeasured — and none of the three is a question a JVM test can be asked. -**The drag is driven from no test at all**: Robolectric reports its own densities, so a -synthetic swipe of «half a slot» would measure the environment rather than the gesture, which -is exactly why `ToolbarReorderTest` asks the arithmetic directly, in pixels, with no -composition in it. — That paragraph is the one #85 came out of. The reason is still true and -the conclusion was wrong: a drag does not have to be «half a slot» to be worth driving, and -the one that goes clean off the end of the bar answers the same under any density. - -~~**One frame at the end of the gesture can draw the pre-drag order.**~~ Closed by #85, and -by exactly the fix this paragraph priced as too risky: the component now keys its permutation -to the order it permutes, which replaces both in one step. The risk named here — silently -double-applying a drag — is the thing the key *prevents*, and there is a test that showed the -old code doing it. - -There is a second window of a frame or two, and it is inherent rather than a defect: the new -order goes out through the preferences and comes back later, so between the drag ending and -the preferences answering the pager's index still names the old order. A `LaunchedEffect` on -the arrived order closes it by putting the pager back — without an animation, which here -would be a page visibly sliding to a place it never left. - -## And before that: an audit of nine areas, and the twenty-four defects it found - -Merged as PR #83 (`3a4a924`), in the milestone `v0.7.0 — Оптимизация`, eight commits. -Eleven read-only passes first — the nine areas of `.claude/skills/audit/SKILL.md` plus -strings, documentation and a security sweep — and then the fixes. **Every one of the -twenty-four was re-verified by hand here before it was fixed, and every one is closed by -a test that was watched going red** on the code without the fix. Nothing in it is a model -change, so there is no revision and the database stays at `0014`. - -### Three a user would have hit - -**A substitution could be written onto a date that draws nothing.** The write check asked -`school_year_bounds` and the resolver asked the class's own terms, its holidays and the gaps -between them, so three kinds of date passed the check and resolved empty: past the date the -class's own «🗓 Четверти» ends on, inside the holidays between two terms, and on a public -holiday. The bot answered «Готово», the audit log recorded it, every subscriber with -`notify_changes` was told, and the row appeared on no phone, in no widget, in no calendar -feed and in no digest. **The second copy of the rule *was* the defect**, so the fix is not a -third: `off_reason_for` is module-level now and the resolver and the write check both ask -it, and the refusal names which of the three it is, because the way out differs — move a -date in «🗓 Четверти», or put an event on the day instead. - -**«🌿 Отгул» was a label with no behaviour.** It printed the word and then listed all six -lessons under it, everywhere. `DAY_OFF` clears the day exactly as `HOLIDAY` does now — the -same early return, so the kind, the note, the events and the homework stay and only the -lessons go. Three of the auditors found this independently. - -**`/find` with a long query answered nothing at all.** The needle was escaped and never cut -and the «ничего не нашлось» branch had no budget, so about four thousand characters made a -message Telegram refuses whole — and `cmd_find` is a `Message` handler, with no callback to -apologise on. With hits it was worse in a quieter way: `clamp` cuts from the end and the -oversized heading is line 0, so a search that found fifteen assignments rendered as «… и ещё -17 строк» and showed none of them. The realistic way in is the obvious one — pasting an -assignment back into `/find` to locate it. The school-search prompt had the same shape. - -### The widget, from three photographs - -**The ladder measures in dp and its type sizes are in sp**, which at the system's largest -font are about twice apart. The box still measured its full size, so the largest rung was -still chosen, and the widget drew eight timeline rows, a week strip, two homework blocks and -the next school day into the room for about half of that: «ПЕРЕ…» for the state word, chips -over a third of the surface, the last rows off the bottom edge. `of()` divides by the font -scale now — **the height, and only the height**, because height is what larger type spends -and spends in proportion, while the ladder uses width for structure. Dividing the width as -well was written first and the tests rejected it: a four-cell widget at the largest font -fell past the narrow column onto a rung with no timeline at all, so a reader who asked for -bigger type lost the rest of their school day. - -**The trailing detail starved the subject to zero width.** A `LinearLayout` measures its -unweighted children first and hands the remainder to the weighted ones, so a room number or -a teacher's name took what it wanted and the subject, which carries the weight, got what was -left. One row drew «10:50 Надежда Петро.» with no lesson on it. Two weights split the -remainder now, with the detail end-aligned in its own share. - -**The week strip's chips had no gaps, and the code said they did.** `padding` before -`background` is margin in Compose and nothing of the sort in Glance: `applyModifiers` folds -every padding in a modifier chain into one `setViewPadding` on the view the background lands -on and throws the order away, so the 1 dp meant to separate the seven days was drawn inside -their own colour and they read as one grey bar. The gap is an outer box. A `Spacer` between -them is the Compose answer and the wrong one here — seven chips and six spacers is thirteen -children of a container that keeps ten, so Saturday and Sunday would have gone missing in -silence. - -Two smaller ones from the same pass: `ellipsize` collapses whitespace before it counts, -because a Glance `Text` at one line hard-clips at the first newline and an event title typed -on two lines in Telegram reached the home screen cut with no «…» to show for it; and the -launcher's placeholder layout rounded at 20 dp against a live surface of 24, a visible step -on a cold start its own comment says can take most of a minute. - -### Three of this project's own guards did not hold what they claimed - -This is the half worth carrying forward, and one of the three was written by the batch -below. - -- **`test_test_imports.py` matched one of two spellings.** It refused `from tests.x import - …` and not the bare `from x import …`; six live test modules used the bare one and the - guard stayed green. They pass today only because pytest's default import mode puts - `tests/` on `sys.path` — under the mode pytest now recommends, three of them die at - collection with the exact error the guard exists to prevent. The shared fakes have moved - into `conftest.py`, which is where the guard's own docstring said they belonged. -- **`DeviceClockTest` listed module paths and filtered them by `isDirectory`**, so a - renamed or moved module drops out of the scan in silence while the test stays green on the - rest. Its own KDoc records that `:core:designsystem` was left out by accident once, that - it is the module where the last clock-shaped defect landed, and that - `ResourceTranslationTest` had the same hole for the same module — and the recurrence was - unguarded by the very `filter` that would do the dropping. It discovers modules now. -- **`NarrowLabelBudgetTest` allowed two characters more than the column holds**, with no - derivation, and `+ 2` was exactly the current data: «Homework today» is fourteen against a - budget of twelve, on the ceiling with nothing to spare, under a comment saying the title - should be *shorter* than the column. Glance cannot ellipsize, which is that file's whole - premise. The English string is what moved — a test tightened onto a string that does not - fit is a test reporting the defect it was written to prevent. -- **`test_the_entry_point_exists_where_vercel_json_says_it_does` never read `vercel.json`.** - It checked a hardcoded path, so the file going missing was caught and the two drifting - apart was not, which would silently drop `maxDuration: 30` under a name promising - otherwise. -- **And my own floor test from #82 was wrong twice over.** The 6 dp floor is unreachable - from any rung, so walking the ladder cannot tell the floored expression from the unfloored - one — and the first replacement kept its own copy of the arithmetic and stayed green - against the very mutation it was written for. `innerCornerFor` exists so a test can call - the production expression with a padding the enum does not have. - -**Plus the guard that did not exist.** `MarqueeText` runs `Int.MAX_VALUE` iterations, so -Compose's clock is never idle and a test that composes an overflowing line **hangs rather -than fails**, taking the whole Gradle run with it. Twenty-two of twenty-five Compose test -classes compose a component that can draw one, and the rule was held by a KDoc. They pass -today only because Robolectric lays text out without fonts at about a pixel a glyph, so -nothing overflows; the day a label grows, CI stops for forty-five minutes and says nothing. -`MarqueeClockTest` walks every file that calls `createComposeRule`, and each of the thirteen -that neither holds the clock nor could overflow says in its own words why not — per file, -because an exemption in bulk is a KDoc again. - -### The rest of the server half, and the sync layer's three false promises - -Four more on the server. **One superscript digit could take down the whole «Дневник» -screen**: `mapper.number()` did a bare `int()` on a string it had only checked with -`isdigit()`, and a `ValueError` is not a `PetersburgError`, so it walked past the guard that -exists to drop one unreadable row and the phone got a bare 500 while the bot's button spun -for ever. **The schools registry could not say its own shape had moved** — an unreadable -suggestion was logged at `debug` against a logger at `info`, so a DaData restructure looks -exactly like a school that is genuinely not in ЕГРЮЛ. And two comments in applied revisions -were wrong about the library rather than about this project: `sa.Enum(native_enum=False)` -emits no CHECK on SQLAlchemy 2.0, so the lower-case value lists in `0003` and `0008` are -inert and could never have rejected the upper-case names the ORM writes. **No DDL changed.** - -In `:core:data`, three of the four findings are a written claim that stopped being true -rather than a wrong screen — nothing was broken for a user today and a reader of the code -would have been told the wrong thing four times. **A bundle `ETag` outlived the class it -described** (`forget` had one caller, eviction, so leaving a class dropped its rows and kept -its tags for the life of the install), fixed structurally: `SessionRepositoryImpl` no longer -holds the DAO, it takes a narrow `TimetableCache` implemented by the repository that owns -the tag store, so joining, leaving, signing out and the worker's sweep all go through the -one object that can drop rows and tags together. **`syncedAtEpochMillis`'s KDoc named it as -the eviction rule** while eviction sorts by distance from the current year — two documents -in one repository giving opposite rules for one decision. And **`deleteLookaheadOf` was the -one delete in the DAO leaning on `PRAGMA foreign_keys`**, against a file whose `clear` says -in so many words that the wipe must not, with the in-memory fake *more* thorough than the -real query so no unit test could see it; a source-reading test now parses every `DELETE FROM -school_day` out of the DAO and demands the matching child statements. - -### The calendar, and the deployment that could not create its own schema - -Four findings in `:app`. **«День» → «Список» blamed a filter nobody had set**: on a year this -phone has not fetched it said «Ничего не подходит», with no chip selected, and said the same -thing while the year was still arriving — the exact distinction `synced_window` exists for, -and the other three surfaces of that tab already made it. **The list scrolled something -nothing reported**, so switching modes left the status-bar blur wearing the ribbon's stale -value over a list at its top. **The period arrows announced «неделя» in four of the five -modes** — the header text was right and only the content descriptions were left behind, so -TalkBack said «Следующая неделя» over a button that steps a day, or a month; -`ScheduleView.stepOf(dayMode)` is one answer now, and the test pins the moved date and the -spoken unit *separately*, because a test that only asked whether they agree would stay green -for ever once they share a function. And **«О приложении» drew the schema and not the -expectation**, so «база отстала» and «база впереди кода» — opposite mistakes with opposite -fixes, in the type's own words — looked identical. Both chips now; `detail` stays undrawn on -purpose, because it is the server's Russian sentence and that card is read in two languages. - -**`docker compose up -d --build` brought up a Postgres with nothing in it.** It is three -commands in `docs/deploy.md`; `app.main` calls `create_all` only for SQLite, the image -carried neither `migrations/` nor `alembic.ini`, and the one in-image alternative, -`python -m scripts.init_db`, refuses a non-local URL by design. What the reader saw was -worse than a failure to start: the container came up, `/api/v1/health` answered green -because it opens no connection, and the first ORM read failed — which for the bot is the -middleware, so every update died at once. The revisions ship in the image now and a one-shot -`migrate` service runs `alembic upgrade head` before the server is allowed to start: a -service rather than a line in the server's command, so a failed migration stops the stack -instead of being buried in the API's log and `docker compose run --rm migrate` is something -a person can do by hand. It takes only `DATABASE_URL`. - -One more that cost several thousand untracked files: **`.gitignore` spelled the virtualenv -`.venv/` exactly**, so an audit pass building `.venv_audit` beside it offered the lot for -commit. This repository is public and an environment committed by accident is expensive to -take back out of the history. - -### The documents, brought level - -Fourteen files, every number re-measured rather than copied. The Android total was 849 -against a real 929, `:core:designsystem` 74 against 80, `:widget` 74 against 90, `:app` 305 -against 357, `:core:model` «ninety-four tests in eight classes» against 117 in ten, and the -server count was quoted as 1559 in one document and 1610 in two others while it is 1630. -Two documents disagreed with themselves: `docs/build.md` said at the top that no workflow -asks for an artifact retention and thirty lines later that «artifacts live a week» — the -fourth place to quote the wish rather than the setting, in the file already corrected once — -and `architecture.md` gave `:core:model` two different test counts nine lines apart. The -descriptions that had gone false: «День» and «Лента» are one tab, and four documents still -described «Лента» as a separate view, one of them the guide the app itself serves. Two rules -had been written in code comments and nowhere else, and both span three modules, so -`docs/design.md` is where they now live: the concentric-rounding rule with the four places -it deliberately does not apply, and the day's two readings with the arrows stepping a day in -one and a month in the other. - -### What was deliberately left alone, and each is a decision rather than an oversight - -- **`SELF_STUDY` keeps its lessons.** «Эти уроки, но дома» is a reading nobody has ruled - out, so `DAY_OFF` was brought into line with `HOLIDAY` and self-study was not — and a test - records that as a decision, so the next person has to change a test that explains why - rather than a line that looks like an omission. -- **The lookahead row is neither fixed nor removed.** The server resolves `next_school_day` - at most 21 days past the last lesson *inside the window asked for*, and since the window - became a whole school year that lands in June — out of season for every class, so the - field comes back null on every bundle this app asks for. Making it work means resolving - from the window's end and about a hundred days of lookahead, paid by every phone on every - sync, for a row that matters in the last days of May; removing it means a Room version - bump under `fallbackToDestructiveMigration`, which wipes the cache on every installed - phone. All five places that described it now say so, and what answers «what is next» - across a gap is `firstTeachingDayAfter` over the cached year. -- **`DayKindName` accepts four day kinds while `/bundle` can return six**, so a phone cannot - write back the value the server just sent it. Found, verified and written into - `docs/api.md` out loud; not fixed, because widening the accepted set is a contract change - and belongs with whoever decides what a phone may set a day to. -- **Four composables read `BuildConfig` directly and nothing stops a fifth**, which is - exactly how #81 happened. The guard is a source-reading test and belongs with the rest of - the meta-tests; this batch added the marquee one and stopped there. -- **`CONTRIBUTING.md` still recommends `python -m pytest -q`**, which `CLAUDE.md` warns - against by name — the `-m` form puts the current directory on `sys.path` and is the reason - a `from tests.… import` passed locally and failed at collection on CI. Its numbers were - corrected in this batch and its command was not, because that line is a contributor-facing - choice rather than a stale fact. -- Also left: the day sheet ignoring `isFetched`, and a widget day-tap landing on a month - when the stored mode is «Список». - -### Gates, measured on this branch - -`ruff check` clean, `python -m mypy` clean across 84 modules, `pytest -q -n auto` **1630 -passed** (was 1610), `./gradlew test` **929** (was 896) — `:core:model` 117, -`:core:designsystem` 80, `:core:data` 285, `:widget` 90, `:app` 357 — and both assembles. -CI was green on `3c7a2f5`; the two commits after it are the documents and this close-out. -The database stays at `0014`: **no migration was needed and none was applied.** - -### What nobody has verified in this batch - -**Nothing of the widget's fixes has been seen on a launcher**, and that is the surface this -batch changed most — the tests reproduce the arithmetic and the budgets, not the rendering, -and the two claims about what Glance does with a modifier chain come from reading its -translator rather than from pixels. **No Compose test was actually made to hang**, so -`MarqueeClockTest` is reasoned from the marquee's iteration count and the call-site list. -**`docker compose up` has never been run** — there is no Docker here — so the compose file -is parsed and its dependency conditions asserted rather than watched. **`/api/v1/warmup` is -unreadable from here**, because the deployments answer a redirect to a Vercel login page. -The diary has still never been opened for real, so the mapper fix is proved against a -fixture rather than against the upstream that would send such a row; and the tag sweep's -prefix arithmetic is written and not run, because `LessonsPreferences` needs a `Context` and -`:core:data` has no Robolectric. - -## What the batch before added: the rounding rule, applied everywhere it is actually true - -Merged as PR #82 (`c7767c8`), in the milestone `v0.7.0 — Оптимизация`. One sentence of a -request — «"Подложка вкладок — зазор скруглений одинаковый по периметру." — исправь все -подложки по приложению» — and most of the work was deciding where it does *not* apply. - -**The rule.** Two nested rounded rectangles look right for exactly one pair of radii: the -inner radius plus the padding equals the outer one. Any other pair leaves the gap wider at -the corner than along the edge, which reads as a wonky corner rather than as a wrong -radius — easy to see, hard to name. #80 applied it to the segmented picker and stopped -there. - -**Where it applies is narrower than «все подложки».** It needs two rounded rectangles -nesting *with a gap*. Every shape in `:app` and `:core:designsystem` was read against that -test and exactly one more place in the product qualifies — and it is the one where the rule -matters most, because there the gap is not one number. - -### The widget was wrong by a different amount on every phone - -`WidgetCard` was a flat `18.dp` and the pill behind the current lesson a flat `12.dp`, both -drawn straight onto a surface of `24.dp`. What separates them is `WidgetSizeClass.paddingDp`, -which runs from 8 dp on the smallest rung of the twelve-rung ladder to 16 dp on the largest. -So the gap was even at **no size at all**, and worst where the widget is biggest: at 16 dp of -padding a concentric block wants 8 dp and it drew 18, more than twice as round as the -surface around it can carry. - -`WidgetSizeClass.innerCorner()` derives it per size class now, with a 6 dp floor. The floor -is the interesting half: square is the *honest* answer for a rectangle inset past the curve, -and wrong here, because the rows beside it are rounded and one square corner among them -reads as a rendering fault rather than as a decision. `WidgetSurfaceCorner` moved in beside -it — two numbers that have to agree belong in one place. Glance takes a `Dp` and nothing -else, so this is `concentricCorner`, the arithmetic form, next to `ConcentricShape`, which is -the same rule deferred to draw time when the inner radius is a percentage of a height nobody -has measured yet. - -### What was deliberately left alone, and it is most of the survey - -Each carries its reason in the file, because the next reader will ask exactly this. - -- **The seven weekday chips.** The strip sits in the middle of the layout, so its corners - are next to other rows rather than in the surface's rounding: no corner nested in a - corner. A chip is also about as tall as the radius the rule would hand it, which is a - pill, not a chip. -- **`RoundedCardContainer` and its rows.** The rows are *clipped* by the container rather - than padded inside it. No gap, no rule — and that flush clip is exactly what makes a group - read as one slab instead of a pile of cards. -- **The hero card's tile and every `Pill`.** `RoundedCornerShape(percent = 50)` is a circle, - not a nested rectangle. -- **«О приложении».** It opens and closes with centred text, so nothing it holds has a - corner in a corner — and its horizontal and vertical paddings differ on purpose, while a - concentric corner is only defined for one gap. - -**Verified, and not.** `./gradlew test` **896 tests**, up from 891, and both assembles. -`WidgetInnerCornerTest` is five, and two were shown red against the old flat 18 dp before -being trusted. One of those two was written `<=` at first and passed against the very -constant it was meant to catch; it asserts a **strict** inequality now, between every -adjacent pair of size classes whose paddings actually differ — and that the ladder really -carries more than one padding is itself a test. **Nothing here has been seen on a launcher**: -the tests reproduce the arithmetic, not the rendering, and `cornerRadius` is a no-op below -API 31 in any case. - -## What the batch before added: a test that asserted its own build's configuration - -Merged as PR #81 (`28f6ea3`), in the milestone `v0.7.0 — Оптимизация`. One defect, found -the way this kind is always found — by the thing it broke rather than by anything reading -the diff. - -**The APK workflow could not build an APK.** The first `apk.yml` run after #80 merged died -at `:app:testDebugUnitTest`, on a test #80 had added: `AboutCardTest > a build that was -told nothing about itself says that rather than nothing`. It read -`BuildProvenance.current()`, which answers with whatever *this* build was told — so it -asserted a property of the build configuration rather than of the card. - -It passed everywhere it was run and failed exactly where it mattered. `ci.yml` sets none of -the five `LESSONS_BUILD_*` properties, so `current()` came back empty, the card drew -«Собрано вручную» and the assertion held — on every pull request, including the one that -introduced it. `apk.yml` sets all five, because naming the commit an APK came from is what -they are *for*, so the badge the test demanded was correctly absent. - -**The workflow whose entire job is to produce an APK was the only thing that could see it, -and it saw it as a failing string on a settings page.** - -The provenance is a parameter now, defaulted to `current()` at the single call site, and -`AboutCard` is `internal` with it. The ordinary fix — and it buys what the old shape could -not: the badges are testable at all. Three tests replace one, including the contradiction -that was previously unreachable (a card claiming both a commit and «собрано вручную»). - -**Deliberately left alone, and it is the part worth carrying forward.** Nothing enforces -this shape. Another composable reading `BuildConfig` directly would reintroduce exactly -this, would again be green on every pull request, and would again be red only in the -workflow nobody runs on a pull request. A rule forbidding `BuildConfig` outside a -provenance type would be the real guard; it is not written, and writing it was not worth -widening a one-defect batch. The gap in the gate is structural: **`ci.yml` cannot catch -this class and should not try** — it does not build an APK anybody installs, so the -difference only exists in a workflow run by hand. - -**Verified, and not.** `./gradlew test` **891 tests** in *both* environments — with the -five properties exported and without them, because only running both tells them apart — -and both assembles. The red case was reproduced before the fix and shown green after. - -## What the batch before added: six things that drifted on a real screen - -Merged as PR #80 (`9b8eba7`), in the milestone `v0.7.0 — Оптимизация`. Six reports from one build on a -phone, plus a lie the previous batch's own CI log had been printing all along and nobody -had read. - -### The retention was wrong in four places at once - -The repository's artifact retention is **one day**. `apk.yml` asked for ninety, `ci.yml` for -a week, `docs/build.md` promised both numbers and `CLAUDE.md` a third. Every run reduced -them and said so — `##[warning]Retention days cannot be greater than the maximum allowed -retention set within the repository. Using 1 instead.` — in a job nobody opens when it is -green, in a sentence that reads like a build problem. - -No workflow asks for a number any more: the repository setting is the only thing that -decides, so there is nothing left for a workflow to disagree with, and the summary says -where to raise it. Worth keeping as a shape: **a wish written next to the thing that -overrides it is not a setting**, and three documents had been quoting the wish. - -### A marquee that stopped after three passes - -Reported as «на некоторых лейблах не двигается, а на некоторых двигается, даже на одном -экране», and the diagnosis that invites is wrong. The line *is* a marquee — it is clipped -mid-glyph with no «…», which is `TextOverflow.Clip`, which this component only sets when it -has decided to scroll. It had simply spent `MarqueeDefaults.Iterations`, three, and parked -itself back at the start. The budget is per composition, so a row just scrolled into view -moves and a row that has been there a while does not. - -**The cost of fixing it is a perpetual animation, and that is not free in tests.** Compose's -clock is then never idle, so `waitForIdle` — which every assertion calls into — hangs rather -than fails. It is the same trap `runTest` against `WeekViewModel`'s clock cost a whole -Gradle run for. Three suites now hold the clock and advance it by hand; a new test that -composes an overflowing line and forgets to will hang, and the note is in `MarqueeText` and -in each of them. - -### «Календарь» wrapped after «Календар» - -The title shared one `Row` with a year chip and three icon buttons under `weight(1f)` — -about eight characters at 411 dp — so the «ь» went to a second line and the subtitle to a -third. Nothing about it looks wrong in the code: `weight(1f)` is the correct way to share a -row, and the row was asked to hold more than it has. Title on its own row now, controls on -theirs. - -The second half was movement rather than wrapping: «сегодня» is offered only when it would -do something, and while the *button* was what appeared, both arrows slid 48 dp sideways -every time the reader stepped into or out of the current week. The slot is kept whether or -not the button is in it. - -### The picker's tray was rounded by a token rather than by its buttons - -24 dp — `LessonsShapeTokens.Group`, the radius of a group of *rows* — around Material's -connected button shapes with 4 dp of padding. Three numbers chosen in three places, so the -gap between the two curves was wider at the corners than along the edges, which reads as a -wonky corner rather than as a wrong radius. `ConcentricShape` computes it: inner radius plus -padding, the one outer radius that keeps the gap even. A `Shape` rather than a computed -`RoundedCornerShape`, because Material's connected corners are a percentage of the button's -own height and the answer is only known once the tray has been measured — which also makes -it a pure function of a size and a density, and therefore testable. - -### «День» and «Лента» are one tab - -Asked for, and asked about first: the literal reading of the request removed the immersive -ribbon entirely, which is a feature the owner had commissioned in detail two batches -earlier, so it was worth one question. The answer was to merge rather than replace. - -They were never two views — both answer «что идёт», one for the day in front of you and one -for the month around it — and four four-letter labels across a 360 dp phone was most of what -the picker's marquee was doing its work for. `DayMode` switches them on the screen itself -and is stored like the ribbon's other three settings. **The two modes cover different -spans on purpose**: the ribbon is one date, because it draws the breaks between lessons; the -list is the month, because «в какой день больше всего» is a question about a stretch. So the -arrows step a day in one and a month in the other, which is what each mode already implies. - -### The about card, and where a build came from - -It was padded twice — once by the settings list's `contentPadding`, once by itself — so it -came out 32 dp narrower on each side than every group above it, and its two link buttons -broke «Essentials» into «Essent / ials». Full width now, one button per row. - -The badges say two things nothing else in the app can. **How the bound server answered**, -including the state that is invisible from everywhere else: API up, database at a different -Alembic revision, which is the window between a merge deploying itself and the migration -being applied by hand — `/health` is green all through it. And **which repository, ref and -commit this APK came from**, with the commit chip opening that exact diff. - -That needed five build properties, because **a build keeps no memory of its own checkout**: -an APK cannot work out its repository, branch or commit unless whatever ran the build says -so. `apk.yml` fills them from the runner's own `github.*` rather than from repository -settings, so a build of a fork describes itself honestly. `BuildPropertyReachTest` already -existed for exactly this class of mistake and earned its keep in the same hour: it caught -`LESSONS_BUILD_TIME` being `export`ed inside the run script, where nothing outside the step -can see it. - -**Deliberately left alone.** Material's three iterations exist so a screen is not in -perpetual motion, and this batch chose readability over stillness for lines that cannot be -read any other way. That is a trade rather than a fix, and if a list of long titles turns -out to be unpleasant the answer is probably to shorten the titles. - -**Verified, and not.** `./gradlew test` **889 tests**, both assembles. The card, the header -and both link buttons are asserted **displayed** rather than merely composed, which is the -lesson of the batch before. The server half was not touched; its gates were last green at -#77 — `ruff` clean, `pytest -q -n auto` 1610, `python -m mypy` clean across 84 modules. -**Nothing here has been seen on a screen**: whether the concentric corner looks concentric, -and whether a marquee that never stops is pleasant, is unmeasured. **The server badge has -never been drawn against a real server** — `ServerStatus` is exercised from a fake and no -test opens a socket. - -One note for whoever writes the next Compose test here: **`performScrollTo` drives the -scrollable's animation.** With the clock held for the marquees it moves nothing, and every -node below the fold reports «not displayed» — which is indistinguishable from the element -being absent, and cost two rounds here. Give the test a tall window instead. - -## What the batch before added: the three defects the first real build had in it - -Merged as PR #79 (`a1f2392`), in the milestone `v0.7.0 — Оптимизация`. Not a feature. #77 -shipped a screen -that crashed on opening, and this is the batch that reads the report and closes it — all -three defects are mine, all in `DayRibbonView.kt`, all introduced in #77. **None of them -would have fixed itself**: #78 changed the cache and the calendar and never touched that -view, which is what the report assumed it would. - -### A key that was never interpolated - -`RibbonEntry.identity()` read `"lesson/${'$'}startsAt/${'$'}{lesson.index}"` — Kotlin's -escape for a *literal* dollar — so every lesson row carried the same constant string, every -event row another, every break row a third. `LazyColumn` throws the moment it measures the -second row of a kind, which is every school day there has ever been. The line was written -through a shell heredoc that escaped the dollars, and nothing ever read the result back. - -### The rows were unreadable because the fade was sized for a screen - -The ribbon is handed the height left under the header and the picker, and it put a fixed -48 dp `progressiveBlur` fade at each end of it — on a phone held sideways, 96 dp of about -150. Worse, `progressiveBlur` paints a 65 % wash of the surface colour under each fade and -**the shell already does exactly that to the whole page**, so the ribbon stacked a second -one inside the first. The fade is a share of *this* view now (`ribbonEdgeHeight`, 12 %, -capped at 48 dp) and carries no tint of its own. «Ничего не было видно, из-за соотношения» -is precisely the shape of that bug: the shorter the view, the more of it was curtain. - -### And the camera distance was multiplied by the density - -Which is the trap `SchoolBell.kt` already carries a paragraph about: the unit goes straight -to `RenderNode` and is density-independent, so scaling it put the camera several times -further away than the default and flattened the tilt by a different amount on every phone. -A second use written without reading the first — the one thing `CLAUDE.md` asks for by name. - -### What the logs settled - -The owner installed the APK of #77 (`versionCode` 24, Room at v4) and sent back a full -Android bugreport — **the first time any of this code has been looked at running on a phone -rather than on a runner**. It is worth knowing what it did and did not contain. - -Six fatal exceptions are in it. Three are SwiftKey's; the other three are ours, and all -three are the same `IllegalArgumentException: Key "lesson/$startsAt/${lesson.index}" was -already used` — the platform quoting the defect back with the dollars still in it. Two on -opening the day, and **the third is the rotation**: `WindowManager` logs -`changed={CONFIG_ORIENTATION}, not-handles={}`, so `MainActivity` handled the change -without being recreated, and what rotation did was re-measure at the new height — the same -duplicate key, at the same place. That closes the question #79's body left open: rotation -is not a fourth defect, it is the third occurrence of the first one. - -Nothing else of ours is in it. No ANR, no exception out of `:core:data`, no SQLite or network -error, and no crash dialog of our own — «снова предлагало сбросить кэш» is the platform's -prompt after a crash, not a screen this app has. The `SQLiteOpenHelper: DB version upgrading -from 3 to 4` line is the cache being dropped and refilled, which is what -`fallbackToDestructiveMigration(dropAllTables = true)` is there for. - -**One thing in it is unexplained and is written down rather than guessed at.** Eighteen -times over seven minutes the app logged `AdrenoVK-0: Shader compilation failed for -shaderType: 4` followed by `Pipeline create failed`, on the render thread, spread across -screens rather than clustered on the ribbon — and **no other app on that device logs it**. -At Android's `I` level, with no shader source and no reason attached, and with nothing the -owner reported that maps to it, there is no fix to write from here; it is a real signal and -it is unclosed. Whoever looks next should start by asking whether the AGSL sheen is the -source at all, since a failure in `RuntimeShader` would normally throw in-process instead. - -### The test that was missing, and the two screens nobody had drawn - -`DayRibbonLayoutTest` composes the ribbon for real, inside the `Column` with a `weight(1f)` -that `RibbonPage` puts it in, at a portrait height, at a landscape one, and at one shorter -than the fades themselves — and asserts the rows are **displayed**, not merely that nothing -threw. It fails on the first run against the shipped code, which is the only reason to -believe it. - -That distinction is the lesson of this batch. The day ribbon shipped with three test suites, -all passing, and **not one of them ever drew it**: `DayRibbonTest` covers its arithmetic, -`RibbonFocusTest` where the focus button lands, `RibbonDepthLevelTest` which devices get the -shader. A screen that is built and shows nothing passes every test that only asks whether it -was built. So the other two screens of that batch are drawn here too, before somebody else -has to find them — the **year picker** and the ribbon's **settings sheet**. Both turn out to -be fine, which is worth writing down rather than assuming. - -**Deliberately left alone.** The 12 % share is a judgement and not a measurement: it keeps -both fades under a quarter of the view at every height, which is the rule that was missing, -but nobody has looked at whether 48 dp is still the right maximum on a tall screen. - -**Verified, and not.** `./gradlew test` **863 tests**, both assembles; two of the three -fixes proved red first — restoring the constant key fails `DayRibbonLayoutTest`, restoring -the fixed 48 dp fade fails two of `RibbonEdgeHeightTest`. **The camera distance has no -test**, and that is not an oversight to close later: what it changes is how deep the tilt -looks, `cameraDistance` is written straight onto a `RenderNode`, and nothing on this side -can read it back. It is held by the comment in both places that set it, which is a weaker -guard than a test and is the honest description of it. The server half was not touched and its gates were -last green at #77: `ruff` clean, `pytest -q -n auto` 1610, `python -m mypy` clean across 84 -modules. **What the fixes look like is still unseen** — the log proves the crash was what -this batch says it was, and proves nothing about the tilt, the blur or the shader. The next -APK is also the first to carry a Room schema of 5, so its first run on that phone drops the -cache and re-syncs a year. - -One note for whoever writes the next Robolectric test against a screen in a `weight(1f)`: -compose it **inside the box the real page gives it**, not at `fillMaxSize()`. Every defect -in this batch is a measurement, and a test that hands the view the whole window reproduces -none of them. - -## What the batch before added: a cache that holds more than one school year - -Merged as PR #78 (`559b306`), in the milestone `v0.7.0 — Оптимизация`. One item, and it is -the one #77 wrote down as a decision the owner had to make: **scrolling the calendar by -years**. They -chose the honest option — a sync windowed on demand — over binding a picker to the year -already synced, which would have scrolled to a year with no days in it. - -### The invariant that had to go - -The cache held exactly one window per class, and `replaceAll` wiped that class's rows on -every sync. So scrolling into another school year could not work at all: arriving would -have destroyed the year being left, and coming back would have destroyed the one just -fetched. Every date outside the one window read «Нет данных» — on screen the same thing as -a week with no lessons in it. - -A window is a school year now, named by the year it opens in, and `replaceWindow` replaces -one of them. `synced_window` is a table rather than something counted off the days present, -because **a year fetched and genuinely empty has to be tellable from one never fetched** — -a class made in March has no rows before it either way, and counting would leave the -calendar on a spinner that never stops. - -**The server needed nothing.** `/api/v1/bundle` has always taken an arbitrary `start` and -up to 280 days, and a school year is 274. The whole batch is Android. - -### What fell out rather than being added - -The Monday anchor is gone with the whole-class wipe that was its only reason, and its -summer bug with it: applied in July it reached back far enough to ask for some 320 days, -past what the server accepts, and the window came back silently clipped in April. -`refresh` lost its `days` — a parameter nothing could honour, threaded through -WorkManager's input data to be ignored. And the `ETag` store keeps a tag per window, -bounded by the cache's own cap rather than a second rule. - -### Three defects the tests found and the code did not - -1. **Eviction by fetch time was not a rule.** It is not «least recently used» — a year - revisited and unchanged answers `304`, which touches the class row rather than the - window's — and it ties, so four years fetched inside one millisecond left the order to - the query, which returns the newest year first, so the year just asked for was thrown - away. It goes by distance from the year holding today now, which is clock-independent. -2. **A year asked for while another was in flight was dropped and never retried**, because - the period had not changed since. It works because the collector *awaits* each fetch: - one coroutine, so a request in flight parks the collector, and a `StateFlow` conflates, - so what it resumes on is where the reader ended up. Launching each fetch instead is the - obvious-looking change, and it is what the test now fails on. -3. **An «already in flight» guard that could never fire**, for the same reason — removed - rather than left as a claim about the code that stops being true silently. That is the - second unreachable guard this session found; the first was in the day ribbon. - -### On screen - -A «2026/27» chip in the header opens a picker of five school years, each marked «загружен» -or «не загружен». Nothing has to be pressed: the calendar fetches the year it is scrolled -into, whether it was stepped to, tapped to, picked or opened from the widget — one -collector watching the period actually drawn, both ends of it, because a week can straddle -31 May. And a day now says which kind of empty it is: «нет уроков», «загружаю год» and -«год не загружен» were one sentence before. - -**Deliberately left alone.** Three years per class, which is a number rather than a -measurement: the question a calendar is asked reaches about one year either side of the -one it is in. Nobody has watched what four or five costs on a phone, and the constant is -one line (`MAX_YEARS`). - -**Verified, and not.** `./gradlew test` **849 tests**, both assembles, and every guard -proved red first — the old whole-class wipe fails two, letting any year write the lookahead -fails a third, dropping the lookahead exclusion fails a fourth. The server half was not -touched and its gates were last green at #77: `ruff` clean, `pytest -q -n auto` 1610, -`python -m mypy` clean across 84 modules. **Nothing has been seen on a screen** — not the -chip, not the picker, not what a school year takes to arrive over a school's wifi, and not -what three years of rows cost a `LazyColumn` that re-reads them on every write. - -One note for whoever writes the next test against `WeekViewModel`: **do not use `runTest`.** -It shares its scheduler with `Dispatchers.Main` when Main is a test dispatcher and then -drains every pending delay by advancing virtual time, which against this view model never -finishes — its clock is `while (true) { emit(now); delay(30s) }`. It hung a whole Gradle -run once. - -## What the batch before added: the school's own dates, the calendar, and a day you can scroll - -Merged as PR #77 (`ddfd305`), in the milestone `v0.7.0 — Оптимизация`, eighteen commits. Three parts: a -defect reported from a real class, the calendar the owner asked for on top of it, and the -day screen that calendar leads to. - -### The dates an admin typed decided a term's name and nothing else - -«2 полугодие» was given an end of 28 May 2027 in «🗓 Четверти». The phone, scrolled to May -2027, still drew a full day of lessons on the 29th, the 30th and the 31st — after a manual -refresh, and after leaving the class and re-joining it with a fresh code. Neither could have -helped: **the server was sending exactly what it meant to.** `_resolve_day` asked -`school_year_bounds`, which is `SCHOOL_YEAR_END_MONTH` — 31 May, and always will be. - -It was mis-diagnosed twice here before it was found, and the way it was found is worth -keeping: the transport was proved correct end to end (the bot's write, the `ETag`, the -phone's `replaceAll`, the flow) and the app turned out to have **no screen that draws a term's -dates at all**. Only the owner's answer — «судя по трём точкам, прокрутив календарь до мая -2027» — said what was actually being looked at. The two round-trip tests written during the -wrong diagnosis are kept as regression guards and labelled as guards rather than as the fix. - -The horizon now comes from the class's own `Term` rows, and the gaps **between** terms are -out of season by the same rule — which is how the autumn holidays are described by moving -two dates rather than by marking nine days. - -### The calendar - -`services/holidays.py` holds fourteen statutory non-working days and twenty-five -observances, apart because they behave differently: a statutory day stops the lessons, -«День учителя» is a full Wednesday with a badge. **The yearly transfers are deliberately -absent** — they are set by decree each December, and a wrong non-working day removes a real -day of teaching while looking exactly like a correct one. - -Every day carries `off_reason` (`out_of_year`, `between_terms`, `public_holiday`, or -nothing) **beside** `kind` rather than inside it, so an older client draws what it drew -before. The month grid gives each reason its own accent, joins consecutive days of one -reason into a single band, and writes «Летние каникулы» across a month with no teaching in -it. A range can be marked self-study, remote or a day off, not only as holidays. The -calendar filters and the order are in both shells — the chips and «по загруженности» in the -app, the same narrowing in the bot's list of marked days — and the month can be read as a -list, which is the one view an order can apply to at all. - -### «Календарь → День» is a ribbon now - -The hour ruler is **gone**, not kept beside it. It drew the day by position, so a forty-minute -break was forty minutes of blank screen: nothing to read, nothing to press, two clocks to -subtract. The day is flattened into a `Ribbon` in `:core:model` — lessons, events, and the -gaps as rows of their own — and every row says when it runs, how long for, and where the -clock is inside it. The widget's `remainingTimeline` is that ribbon filtered now rather than -a second copy of the merge and its tie-break, which nothing had ever tested. - -The view owns the page's height instead of adding to its length, which is what the magnetism -and the tilt both need: a list can only snap, and a card can only lean away from the middle -of the screen, if the list *is* the viewport. Three settings are the reader's, stored rather -than remembered — which way the progress runs, whether the scroll settles on a whole row, -whether the cards have depth — and they live in a sheet on the screen itself because all -three show what they do the moment they are pressed. - -The depth is a ladder of three: AGSL lights the running row where its clock has got to on -Android 13 and above, everything from `minSdk` 26 up to Android 12 keeps the gradient and -the perspective tilt, and off is off at every version. `ribbonDepthLevel` is a function of -the API level rather than an `if` at the call site, so all ten versions this app installs on -are checked by a test instead of whichever one the runner emulates. - -### What CI caught that the local gate could not - -`CLAUDE.md` documented the server gate as `python -m pytest`; **CI runs the bare `pytest`.** -The `-m` form puts the current directory on `sys.path` and the bare one does not, so -`from tests.test_api import _token` passed here and failed at *collection* on CI. Fixed in -three layers: the import is gone, a test now refuses any test module importing another, and -the documented command is the one CI runs. - -**Deliberately left alone.** Scrolling the calendar **by years** is not in this batch and is -not a refusal — it is blocked on a decision only the owner can make. The phone's cache holds -**one school year** by construction: `SchoolYear.boundsAt(today)` picks the window, -`TimetableDao.replaceAll` wipes the class's rows on every sync, and the server caps a bundle -at `MAX_BUNDLE_DAYS = 280`. So either the year picker is bound to the synced year (cheap, -and very nearly useless — it would scroll to a year with no days in it), or the sync becomes -windowed on demand, which breaks the one-window-per-class invariant and touches `replaceAll`, -the Room schema and the `ETag` signature. The second is a batch of its own and the wrong -thing to start without being asked. - -**Verified, and not.** Both halves of the gates are green: `ruff` clean, `pytest -q -n auto` -**1610 passed**, `python -m mypy` clean across 84 modules, `./gradlew test` **830 tests**, -both assembles. Every fix was proved red first by mutating the implementation. **Nothing in -the calendar or the day screen has been seen on a screen** — not the four accents beside one -another, not the summer's tint across sixty cells, not the tilt, and not the shader, whose -cost on a mid-range phone is unmeasured. The new day kinds have not been pressed in a real -Telegram. The Vercel preview is behind SSO, so nothing could be checked against a running -server either. - -## What the batch before added: an audit of the whole project, and a typeface that can draw it - -Merged as PR #76 (`01f7a30`), in the milestone `v0.7.0 — Оптимизация`. Twelve agents swept the -nine areas of `.claude/skills/audit/SKILL.md` plus documentation, strings and access, -read-only; every finding below was then re-verified by hand here and closed by a test proved -red without its fix. What was found is larger than what is fixed, and the rest is listed at -the end rather than quietly dropped. - -### The app shipped a typeface that cannot draw Russian - -**Google Sans Flex has no Cyrillic. Not a dropped subset — none.** Its coverage metadata on -Google Fonts lists latin, latin-ext, vietnamese, math, symbols and five scripts nobody here -writes, and zero code points in U+0400–U+04FF; `&subset=cyrillic` returns an empty answer. -This app's product language is Russian. So every Russian word was drawn by the device's -fallback face while the digits and Latin beside it came from the bundled file — two -typefaces in one row, at different x-heights — and «системный шрифт» was close to a no-op -for the only language on the screen. It had been that way since the design system was taken -from Essentials, which is an English app and had no way to notice. Nothing failed and -nothing was logged. - -**The app now bundles both faces and chains them by coverage.** Google Sans Flex draws -Latin and digits, Onest (193 056 bytes, 162 Cyrillic code points) draws Cyrillic, and -`FallbackTypeface.kt` puts them in one `Typeface.CustomFallbackBuilder` — Latin, then -Cyrillic, then the system — handed to Compose through `AndroidFont`, one chain per weight. -That construction is the only one that chooses by coverage: a Compose `FontFamily` picks by -weight and style, and so does a font-family XML. **`CustomFallbackBuilder` is API 29 and -this app's floor is 26**, so Android 8.0 and 9.0 are set in Onest alone — correct, and -merely less like itself. - -Google Sans Flex is committed frozen from six axes to `wght` alone, 3.81 MB to 0.26 MB; the -command that produced it is in `docs/build.md`. Both files now carry one axis and the app -varies it, so **the build-time instancer from the batch before is gone**: there is nothing -left to freeze, and `./gradlew` needs no Python again. The guard stayed where the fix was — -`FontAxisTest` fails if the pair cannot draw the Russian alphabet, if either file carries an -axis `Type.kt` never varies, or if a bundled file is named by nothing, and each was proved -red by breaking it. - -`GoogleSansFlexRounded` went too. It had three callers asking it for SemiBold and Bold, and -it was registered at one weight, so Compose synthesised what they asked for rather than the -font drawing it — and neither file now has a rounded axis to offer instead. - -### Two rules that existed in one shell and not the other - -**«🔔 Звонки» in the editor silenced lessons and told nobody.** It wrote the bell rows by -hand instead of going through `structure.write_bell_periods`, which is the half that answers -«which lessons stop ringing». A five-row paste took lessons 6 and 7 off every phone, out of -the widget, the calendar feed and the digests, under «✅ Звонки сохранены: 5 уроков» and not -a word more — while the *same* paste through «⚙️ Класс» warned properly. Two of the twelve -agents found this independently. It now goes through the service, the warning sentence lives -once in `render.silenced_lessons` so the two editors cannot drift again, and the handler's -private copy of `BELL_LINE` is gone in favour of the shared grammar. - -**A substitution could be written on a day the resolver never draws.** `_resolve_day` -returns before the override loop out of the school year and on a day marked «выходной»; -`api/edit.py` had refused both since it was written, and the bot had neither check. It was -believed safe because its lesson picker offers nothing on such a day — true of the picker, -not of the flow, because the bot's calendar bounds the year 1 September to 1 August under -the same function name as `schedule.school_year_bounds`, which means something else. So June -is two taps away, and the row was stored, logged and pushed to every subscriber. The rule -and its three sentences now live in `services/timetable_edit.why_no_lesson_can_be_drawn` and -both shells call it. - -Also: «✅ Звонки сохранены: 1 уроков» and «Расписание создано: 1 уроков» now count in Russian. - -### Gates - -`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` -**1565 passed** (was 1559). `./gradlew test assembleDebug assembleRelease` green: **770 tests -across 106 classes**. The release APK is **3 852 053 bytes** — 80 KB more than the 3 771 298 -it started the day at, which is the second typeface bought with the alphabet. No model changed, so no migration: the database stays at `0013`. - -### Found and not fixed — the list is the deliverable - -None of these is closed; all are verified enough to act on. - -- **Cleartext HTTP is permitted for every host** (`network_security_config.xml`), and the - comment justifying it says «No credentials, no personal data». That stopped being true - when the app grew its own diary sign-in: `DiaryApi.login` posts a dnevnik2 password - through the same OkHttp client at whatever address the reader typed. Nothing checks the - scheme. -- **`POST /api/v1/diary/login` counts only a 401 against its limiter.** A 200 of HTML from - the upstream becomes a 502 and costs nothing, which `api/diary_web.py` already decided the - other way at length for the same exception type. -- **419 of `:app`'s 779 strings can never be corrected**: the translation pull request writes - to `values/strings.xml` only, and `:app` splits its resources across eight files. -- **Twelve callback handlers have no fallback**, so a press on a card whose FSM state is gone - answers nothing and the button spins — reachable through the command breakout. -- **«Мои задачи» draws up to forty rows over ten buttons**; the tail cannot be ticked or - deleted. -- **`DATABASE_URL` set to blank or with a leading space** walks past `deployment_problems()`. -- Four rotation defects in `:app` (correction editor, diary correction sheet), the widget's - narrow-column labels, `docs/widget.md`'s size ladder disagreeing with `docs/design.md`, - stale counts in `docs/architecture.md` and sections 1, 5 and 7 of this file, `docs/app/` - missing from the CI path filter, and a dozen string findings — three names for the app, - two Russian names for `VIEWER`, a nominative weekday where the sentence needs accusative. - -### Where the seam actually falls - -Traced after the pull request was opened, against both files' `cmap` rather than -guessed. The chain resolves per character, and the base wins every code point it -covers — **464 of them are in both files**, so on API 29+ Onest never draws Latin, -digits or punctuation even though it can. - -| | drawn by | -| --- | --- | -| `Algebra`, `08:30–09:15`, `«»`, `—`, `…`, `·` | Google Sans Flex | -| `Алгебра`, `ё`, and **`№`** | Onest | -| `каб. 214` | `каб` Onest, `. 214` Google Sans Flex | -| `9А` | `9` Google Sans Flex, `А` Onest | -| emoji | the system, third in the chain | - -`№` is the one worth knowing: Google Sans Flex does not cover it, so «Урок №3» -breaks between the `№` and the `3` rather than between the word and the number. -That and «каб. 214» are the two most frequent mixed strings in the app, and they -are where to look first for a visible seam. - -### What nobody has verified - -Onest has not been drawn on a device: what is checked is that it declares the axis the app -varies, covers the Russian alphabet, carries its own OFL notice, and renders under -Robolectric. The twelve agents' reports are in this session's transcript, not in the -repository. - -## What the batch before added: the typeface is compressed by the build - -Four commits in `dev`, merged as PR #75 (`01a69fc`), in the milestone `v0.7.0 — Оптимизация` -(number 8), which the owner created for this batch because none of the seven fitted. Its -number was not handed over and nothing here lists a milestone, so it was assigned as 8 — the -next after the seven — and then **read back off the pull request** rather than assumed, which -is the only check available and is what the `github-pr` skill means by reading a number back. - -Its title is Russian where the other seven are English, which is the one place the project's -own rule — Russian on the screen, English in everything written about the project — is not -kept today. It is the owner's milestone and theirs to rename; nothing here touched it. - -**The instanced font was committed, and that was the arrangement that could not survive an -update.** The batch below took the file from 3.81 MB to 0.29 MB with `fonttools` and -committed the result. It works exactly until somebody updates the typeface, because the -obvious way to update a font is to download it again — and the download is the six-axis -file, so two megabytes come back into the APK with nothing failing. `FontAxisTest` would -have caught it; the point is that it should not have to. - -So the font is a **source** now. `core/designsystem/fonts/google_sans_flex.ttf` is the file -as it was downloaded, and `instanceFont` writes the compressed copy into the -variant's generated resources on every build. What is in the repository is the thing you -would download. - -**The compression is a setting, which is what was actually asked for.** -`-Plessons.font.axes` takes a list of axes to keep, or `all`. Measured on one tree, three -builds: - -| `lessons.font.axes` | the font | release APK | needs | -| --- | --- | --- | --- | -| `wght,ROND` — the default | 0.29 MB | 3.60 MB | Python 3.10+ with `fonttools` | -| `wght` | 0.27 MB | 3.58 MB | the same | -| `all` | 3.81 MB | 5.71 MB | nothing | - -`wght` is not the default although it is smaller: it bakes `ROND` in at 100 and the code -goes on asking for an axis that is gone, which Android answers by drawing the default and -logging nothing. Fifteen kilobytes is not worth that. `all` is the escape hatch for a -machine with no Python, and it is a correct build — the file that ships is the file that was -downloaded, to the byte. - -**The cost is that Gradle now needs Python.** Without `fonttools` every Android task stops, -with a message naming `-Plessons.font.axes=all` rather than a stack trace out of a missing -module — proved by pointing the task at interpreters that do not exist. Both Android -workflows install `fonttools==4.65.0`, pinned because that is the one the sizes above were -measured with. - -**Two things AGP 9 decides for you here.** `sourceSets["main"].res.srcDir(provider)` is -refused outright — a static directory carries no task dependency, so the font would be -merged before it was written — and the supported way, `addGeneratedSourceDirectory`, is -per variant and chooses the output path itself. Hence one task per variant (the second is a -build-cache hit) and the tests being handed the path rather than guessing it. - -**`FontAxisTest` was rewritten around the setting**, and every guard was proved red on its -own side: an axis the app asks for that the shipped font neither declares nor freezes; an -axis the shipped font carries that the build was not told to keep (reproduced by building -`all` and running the tests at the default); a `fontAxisPins` value that disagrees with -`Type.kt`; and the file not actually shrinking. `instance.py` refuses a pin for an axis the -font does not declare, because that is the one hole a test cannot see — the tag would still -be in the build file's map and the test would pass while nothing had been frozen. - -**The licence claim was wrong and is now right.** `Type.kt`, `docs/design.md` and the OFL -notice inside the APK all said the file is not modified here. It is: freezing an axis -rewrites the outlines. The OFL permits it outright, and its rename requirement applies only -to a Reserved Font Name, which this typeface declares none of; the `name` table is left -alone, so the copyright and the licence entry in the shipped file are the downloaded file's -own and `FontLicenceTest` still reads them out of what ships. - -### Gates - -`./gradlew test assembleDebug assembleRelease` green: **770 tests across 106 classes** (was -768 across 106). The server was not touched, so its gates were not re-run — `ruff`, `mypy` -and the 1559 tests were last green on the batch below. No model changed, so no migration: -the database stays at `0013`. - -### What nobody has verified - -Nothing in this batch has been drawn on a device; what is checked is that the shipped font -declares what the code asks for, that it is smaller than the source, and that it renders -under Robolectric like any other resource. The `all` setting is exercised here by hand and -**not in CI** — CI builds the default, because a CI run exists to build what ships. - -The Android workflows' `pip install fonttools==4.65.0` **has** now run on a GitHub runner, -which was the one thing the local gates could not answer: CI was green on `b6f0869` and -again on `3126597`, and neither job could have built at the default setting without the -instancer. - -What it costs, read off the job log rather than off the job totals: **4.2 s** for the pip -install, and 0.1 s for `setup-python`, because 3.12 is already on the runner image. The two -`instanceFont` tasks span 2.4 s inside a two-and-a-half-minute Gradle build, beside -everything else it is doing. The three Android jobs came in at 4 min 14 s without any of -this, 5 min 43 s with it and 3 min 09 s with it again — that spread is Gradle's cache being -cold or warm, and nothing about this step can be read off it. - -## What the batch before added: a signed build, two megabytes off it, and the documents - -Three commits in `dev`, merged as PR #74 (`9920a9a`), in the milestone `v0.6.0`. This batch -is different from the ones below it: most of it came out of the owner configuring the -release keystore and the two optional secrets **for the first time**, which turned up what -the documents did not say and what the workflow did not tell you. - -### The APK is signed now, and the first one cost three attempts - -All four keystore secrets and both optional ones are set, and run #21 produced a release APK -signed with the owner's own key — the first this repository has ever made. What it cost is -the useful part. The first attempt died at «Decode keystore» with `base64: invalid input`, -which names neither the secret nor this project; the value had lost its last two characters -to a selection in a phone terminal that stopped one gesture early. PR #73 replaced that -message: it reports the value's length **modulo four**, because base64 always comes in -groups of four and the remainder is the whole diagnosis, and `keytool` now opens the rebuilt -file before the build starts rather than letting a wrong password surface eight minutes -later inside Gradle. - -**The next install is an uninstall.** The build on the owner's phone is debug-signed; this -one is not, and Android compares certificates before versions. It takes the classes, the -device token, the diary session and the corrections with it. It is the last time. - -### Two megabytes, and not one of them was a dependency - -The release APK was **5 989 554 bytes** and is **3 771 086** — `res/fU.ttf` was 2296 KB of -it, 40% of everything shipped and more than all the code. - -Nothing about dependencies was the problem, and the batch is worth reading for that as much -as for the saving. The debug APK is 27 MB against the release's 5.7, so R8 already removes -about eighty per cent; `material-icons-extended` declares thousands of icons, 112 are used, -and the rest were gone already. Compose with Material3 is a couple of megabytes of dex on -its own and no pruning reaches it. - -The font was all of it, for a reason that is not about character coverage. It ships with six -variation axes, and a variable font pays for an axis in `gvar` — outline deltas per axis per -glyph — which was **3411 KB of a 3811 KB file** while the outlines themselves were 31 KB. -The app touches two: it varies `wght` and sets `ROND` to 100. The four that never move are -frozen now; all 657 glyphs are kept and the file is 0.29 MB. `ROND` stays a real axis rather -than being baked in, which costs 0.02 MB and keeps the code's request meaning something. - -`FontAxisTest` holds both directions, each proved red on its own side: an axis the code asks -for and the font does not declare (Android ignores it silently and draws the default), and an -axis the font carries that nothing asks for — which is the saving coming back through the -obvious way to update a typeface. The `name` table is untouched, so `FontLicenceTest` passes -and the OFL travels with the file. - -### The documents were read end to end, and sixteen things were wrong - -Not stale — wrong. `docs/widget.md` said alarms go through `setWindow`, which was removed -because Doze held it, and that `SCHEDULE_EXACT_ALARM` is not requested, while the manifest -declares it and `USE_EXACT_ALARM`. `docs/api.md` described refusals `PUT /overrides` no -longer makes, gave `POST /diary/login` no throttle although it finally has one that works, -named `reminders.yml` as the cron's caller against what `deploy.md` and `CLAUDE.md` say, and -put the FSM sweep at a day where `STALE_AFTER` is two. `docs/bot.md`'s `/find` was wrong -twice. `docs/design.md` gained the section the `MarqueeText` crash deserved. The index, -`docs/README.md`, was accurate end to end and was left alone. - -`docs/build.md` gained what the first configuration turned up: the OAuth App registration as -a table over the form's own fields, and **«Expire user access tokens» must be unticked** — -`AccessTokenDto` has no `refresh_token` field anywhere in `:core:data`, so with that box -ticked the token dies after eight hours, `/user` answers 401, the app forgets it, and the -reader is back at «Войти через GitHub» every day with nothing logged. - -### Gates - -`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` -**1559 passed**. `./gradlew test assembleDebug assembleRelease` green: **768 tests across 106 -classes** (was 765 across 105). No model changed, so no migration: the database stays at -`0013`. - -### What nobody has verified - -The instanced font has not been drawn on a device — what is checked is that it declares what -the code asks for and renders under Robolectric like any other resource. Nothing in the -GitHub sign-in has run against live GitHub either; the secrets are set and the button is in -the build, and the first press will be the owner's. - -## What the batch before added: the two loose ends - -One commit in `dev`, merged as PR #72 (`cb20b45`), in the milestone `v0.6.0`. Both were named -by the batch below as found-and-not-taken, and both are now taken. - -**A command the bot does not have answers.** Telegram stays silent on one, and for a bot with -a single screen that is fine — but once a command started breaking out of a half-finished -form, silence became misleading: «/wek», a typo for «/week», dropped what somebody was -filling in, said so, and then nothing happened. It says «🤔 Не знаю такой команды. Наберите -/help, чтобы увидеть список.» - -The handler is a router included **last** in `build_router()`, because it matches any command -at all and so everything that answers one has to be asked first. That contract is invisible, -so a test walks the whole `COMMANDS` list — the one BotFather shows — and fails if any of -them reaches the catch-all, turning a comment that had stood over that list since it was -written into something checked. Proved red both ways: unregistering the router fails the two -unknown-command tests, and moving it to the front fails all twenty-four menu commands. -Private chats only, because in a group Telegram hands «/start@otherbot» to every bot that can -see it. - -**«Отладка» keeps the report being read when the phone is turned.** It is the screen where a -rotation costs most — the report is open while its important line is being copied into a -message to whoever can fix it — and a rotation dropped the reader back to five -identical-looking timestamps. The name is saved rather than the file, and the file is looked -up in the list again, the same shape as the calendar's lesson sheet. - -**One thing a test here does not prove, and says so in its own words.** The second case, a -report whose file has gone, does not discriminate between looking the name up in the list and -building a `File` from it blind: the body is read with `runCatching`, so a deleted file is an -empty string either way and the test passes against both. That was checked by running the -second implementation, not assumed. The lookup is still right for a reason no test here -reaches — the name comes out of a bundle another build wrote, and the lookup can only ever -yield a file this app listed. - -### Gates - -`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` -**1559 passed** (was 1533). `./gradlew test assembleDebug assembleRelease` green: **765 tests -across 105 classes** (was 763 across 104). No model changed, so no migration: the database -stays at `0013`. `docs/bot.md` gained the unknown-command rule beside the refusal it already -described, and the test counts moved in all four places. - -### What is left - -Nothing here has run on a device or against a live Telegram, as with everything above it. -**What only the owner can do** is unchanged and still outstanding: register an OAuth App with -**Enable Device Flow** ticked, put its client id in the repository secret -`LESSONS_GITHUB_CLIENT_ID` and an address in `LESSONS_CONTACT_EMAIL`. Until then «Войти через -GitHub» is in no build and the APK run summary says «off». - -## What the batch before added: the four things the sweep would not decide - -Three commits in `dev`, merged as PR #71 (`0cdd7f1`), in the milestone `v0.6.0`. The batch -below found these four and deliberately left every one of them, because each is a decision -rather than a correction. The owner took all four; what follows is what each decision *was*, -because the code is the easy half. - -**A command wins over a half-finished form.** `/week` typed at «Теперь пришлите текст -задания:» was committed as an assignment whose text was «/week», audited, and pushed to every -subscriber — and which commands escaped was an accident of which router was included first. -The decision could have gone the other way (refuse the command, keep the form); it did not, -because somebody who types a command mid-form wants to be somewhere else. So the state is -dropped, the bot says «✖️ Форма отменена: вы отправили команду.» and the command runs as -though the form had never been open. - -The mechanism matters more than the behaviour. It is **one outer middleware on the message -observer**, not a check in each step: the state has to be *cleared*, which no filter can do — -a filter would let the command run and leave the form sitting there to eat the next plain -message — and clearing `raw_state` with it means no state-filtered handler can match a -command, whoever writes the twenty-sixth step. The rule-holder test is parametrised over every -`State` discovered in the two state modules, so a new form step is a new case with nothing to -remember. Unregistering the middleware fails 45 of its 48 tests and reproduces the production -defect exactly; the three that stay green are the three that must be green both ways. - -**`request_approve` has one home.** Forty lines carried twice, in `api/manage.py` and -`bot/handlers/manage.py`. `services/access.py` holds them; both shells find the request, call -it, translate the refusal into a 403 or a Russian alert, commit and notify. The API keeps its -extra freedom to name a different role in the body, which `can_grant` still gates inside the -service. An anti-drift test watches both shells call it. - -**A class that moves from 9 to 10 stops being called «9А».** Moving `grade` or `letter` -recomposes the name — **unless the same request also sets `name`**, because an admin who names -the class has said what they want. The audit line is written only when the name actually -changed. The bot has no grade editor, so there is no twin to keep in step today; if «⚙️ Класс» -ever grows one, the rule belongs in `services/terms.py` rather than in the endpoint. - -**The calendar's two sheets survive a rotation.** `Lesson` cannot be saved — it comes from -`:core:model`, which is pure JVM and must stay that way — so what is saved is what the sheet -is *about*: the date and the lesson's number, which name one lesson, because the server -resolves a date into at most one lesson per number and nothing between there and the screen -adds a row. The lesson is looked up in the week on every composition, and one that is no -longer there opens no sheet. That lookup closed a second defect the rotation only made -visible: the sheet held the object it was handed, so withdrawing a substitution while its -sheet was open left the room, the teacher and the homework of a lesson that had stopped -existing on screen, with no rotation needed. - -### Gates - -`ruff check` clean, `python -m mypy` clean across 82 modules, `python -m pytest -q -n auto` -**1533 passed** (was 1474). `./gradlew test assembleDebug assembleRelease` green: **763 tests -across 104 classes** (was 760 across 103). No model changed, so no migration: the database -stays at `0013`. `docs/bot.md` gained the command rule beside its FSM paragraph, and the test -counts moved in all four places that carry them — `CLAUDE.md`'s was two batches stale. - -### What is left, and what nobody has verified - -Nothing here has run on a device or against a live Telegram. Two loose ends were found and -not taken: «/notacommand» now gets the «Форма отменена» line and then silence, because this -bot has no unknown-command handler — a separate card if it is wanted; and «Отладка» holds the -crash report it is reading in a plain `remember`, so a rotation drops the reader back to the -list. That one is a file name and saves cheaply. - -**What only the owner can do** is unchanged from the batch below and still outstanding: -register an OAuth App with **Enable Device Flow** ticked and put its client id in the -repository secret `LESSONS_GITHUB_CLIENT_ID`, and an address in `LESSONS_CONTACT_EMAIL`. -Until then «Войти через GitHub» is in no build, and the APK run summary says «off». - -## What the batch before added: the crash, the button that was never built, and twelve defects - -Seven commits in `dev`, merged as PR #70 (`7bde4f7`), in the milestone `v0.6.0`. Three parts: -the crash the batch below could not explain, a feature that was missing from every APK ever -built, and a five-agent sweep of the whole tree. - -### The crash after the link, which was a line of layout - -It closes the report the batch below could not answer — «приложение вылетает через несколько -секунд после привязки Telegram», and then «предлагает очистить кэш» — and **it was not the -link.** - -The bug report the owner sent from the phone carries the fatal exception, on the main -thread, once at 14:36 and then in a loop for seventy seconds: - -``` -java.lang.IllegalStateException: Asking for intrinsic measurements of SubcomposeLayout -layouts is not supported. This includes components that are built on top of -SubcomposeLayout, such as lazy lists, BoxWithConstraints, TabRow, etc. -``` - -The stack is R8-obfuscated and names neither a file of ours nor a caller of one. What it did -not have to name: **the app contained exactly one `SubcomposeLayout`**, the -`BoxWithConstraints` inside `MarqueeText`, and that component is drawn at two dozen call -sites — every group row, every lesson row, every section header, the toolbar, the pickers. -A `SubcomposeLayout` cannot answer «how tall would you be at this width», and nothing in this -repository spells `IntrinsicSize`, which is exactly why it looked safe: Material spells it -inside its own rows, so the question arrives at a call site that never mentions it. **Which -Material component asked was not identified and did not need to be** — the component that -could not answer now can, wherever it is placed. - -It came in with #62 and has been in every build since, including the one the owner is -running. The link had nothing to do with it beyond redrawing the screen. - -The fix is the width without the subcomposition: `Modifier.onSizeChanged`, outermost of the -three modifiers so that it reports the window rather than the string the marquee scrolls -through it. The price is one frame — until the line has been measured once its width is -`Constraints.Infinity`, nothing can overflow it, and a line that will scroll is drawn still, -which is what the first frame of a marquee looks like anyway. - -Three things about the tests are worth carrying forward: - -* **The reproduction is one line.** `Row(Modifier.height(IntrinsicSize.Min))` is the - question, and it throws that exact exception on the old component. -* **Three of the component's own tests were named for a line that scrolls and never reached - one.** Robolectric lays text out with no fonts — every glyph costs about a pixel — so - «По этому предмету ничего не задано» measures 35 px and sits inside a 120 dp box with room - to spare. They use a string twenty times as long now. One of them, «stays inside its box», - was also reading a number that says nothing: a scrolling line's text node really *is* as - wide as the string. What holds is that the row is not pushed apart, so what the test looks - at is a neighbour placed after it. -* **`NoSubcomposedLeafTest` holds the rule rather than review.** It reads - `:core:designsystem`'s source and fails on a `BoxWithConstraints`, a `SubcomposeLayout`, a - `TabRow` or a lazy list, with the same `//`-above opt-out `NoEllipsisedLineTest` uses. - `:app` and `:widget` are outside it for a reason and not for convenience: a lazy list on a - screen is the root of its own layout and nothing above it asks it to predict a size — seven - screens hold one on those terms. The rule is for a component written to be placed inside a - layout it does not own. - -Each of the three guards was proven red first — the intrinsic query against the old -component, the scrolling test with the width feed cut, and the source rule with the word put -back into a component. - -### «Войти через GitHub» has never been in an APK - -The row is shown only when the client id is non-empty, `app/build.gradle.kts` reads it from -`LESSONS_GITHUB_CLIENT_ID`, and **`apk.yml` passed that property on no day of its life**. So -every build the workflow ever made had it blank: the row hidden, and with it the only way to -file a bug report from inside the app and the only way to send a correction as a pull -request. `LESSONS_CONTACT_EMAIL` was the same story one button along, which is «Отправить -письмом». Nothing failed and nothing warned — an unset property is an empty string, and -downstream that is a feature switched off. - -Hiding the row stays: a row that opens a sheet saying «не настроено» is a row about the build -rather than about the reader, and that is written down in `docs/design.md`. What it costs is -that the whole weight then rests on the build actually passing the property, so the run -summary reports each one as on or off. `BuildPropertyReachTest` reads the build script and -the workflow together and fails on a property that is read and never assigned; its first -version passed on the name appearing in a comment, and was caught by breaking the wire on -purpose. Both files are declared inputs of the test task — without that, editing the workflow -left the task `UP-TO-DATE` and the check unrun. - -### Twelve defects, from five agents, each closed with a test proven red - -On the server: **the diary sign-in throttle did not exist and a wrong password answered -500** — `JoinAttempt.client_key` is `VARCHAR(64)`, a SHA-256 digest fills it exactly, and the -diary's key was that digest with «diary:» in front, so the insert raised out of the `except` -that was re-raising the 401; SQLite ignores a `VARCHAR` width, which is why the test named -after that limit passed all along. **A substitution could be stripped of the subject that -made it visible** — the guard ran only on create, and the row is reachable in two writes. -In the bot: a typed year one digit too long left the handler through `OverflowError`; «²» -passes `isdigit()` and `int()` refuses it, in two callback handlers as well as the date -parser; a lesson edit whose slot had gone was audited as though it had happened; the canteen -could be marked on a break the bells no longer ring. - -On the phone: **the widget's loading layout drew its message white on near-white for Android -8 to 12** — `DeviceDefault` below API 29 is the dark variant and the surface comes from -`values/`, so the layout drew exactly the blank rectangle it exists to prevent. **The guide -froze in one language for ever once refreshed in the other** — one manifest version for two -files, recorded under language-less keys. **One dropped request ended a GitHub sign-in that -GitHub had already granted.** **The edge wash was drawn on every phone below Android 13 while -the only switch that names it said it was off and could not be pressed** — the blur is gated -on API 33, the gradient tint is not, and the row gated the whole switch on shaders. **Turning -the phone re-opened a pull request already opened** — a `LaunchedEffect` key survives a -recomposition, not a configuration change. - -**Reported and deliberately not fixed**, because each is a decision rather than a correction: -a command typed into an open bot form is saved as the answer, so «/week» at «пришлите текст -задания» becomes homework called «/week» and goes to every subscriber, and which commands -escape is an accident of router order; `request_approve` is forty duplicated lines across the -API and the bot; `PATCH /manage/class` can move a class from 9 to 10 without its name ceasing -to say «9А»; `WeekScreen`'s two sheets close on a rotation, and `Lesson` cannot be made -parcelable without breaking `:core:model`'s purity. - -### Gates - -`ruff check` clean, `python -m mypy` clean across 81 modules, `python -m pytest -q -n auto` -**1474 passed** (was 1465). `./gradlew test assembleDebug assembleRelease` green: **760 tests -across 103 classes** (was 738 across 96). No model changed, so no migration: the database -stays at `0013`. - -**What only the owner can do.** Register an OAuth App — Settings → Developer settings → OAuth -Apps → New OAuth App, with **Enable Device Flow** ticked — and put its client id in the -repository secret `LESSONS_GITHUB_CLIENT_ID`, and an address in `LESSONS_CONTACT_EMAIL`. -There is no client secret to register. Until then the run summary says «off», which is the -honest answer rather than a silent one. And install a build carrying all of this and link a -phone again: none of it has run on a device, and the uninstall-first caveat below still -applies to a debug-signed APK. - -## What the batch before added: a crash report that its own phone can read - -One commit in `dev`, merged as PR #69 (`cbb81e8`), in the milestone `v0.6.0`. It is the answer -to a question that could not be answered: **«приложение вылетает через несколько секунд после -привязки Telegram» — and there was no way to get the stack trace off the phone.** - -The switch that records crash reports has always been on «О приложении», where everybody can -reach it. The two ways to *read* one were the administrator's — the bug button beside the -toolbar's pill and the management page's own row. So anybody who is not an administrator -could turn the feature on, crash, and then have nothing: the file is in the app's external -files directory, which Android 11 stopped file managers from opening, and no screen they -could reach would show it. On a Samsung, with no computer, that is a dead end. - -The row is now directly under the switch that writes the reports — the same row the -management page had, moved to `ui/debug/DebugRow.kt` and shared rather than copied, with its -strings losing the `admin_` prefix along with the gate. Two tests: one composes the row, -presses it and asserts the sheet opens; the other reads `SettingsScreen.kt` and fails if the -«О приложении» group stops calling it or starts gating it on the role, because a composition -test cannot ask whether a row is on the page everybody has. Proven red against the code -without the fix. - -**The crash itself was not fixed by this batch — the one above does that**, and it was none -of the things ruled out here. What was ruled out, by reading and -by one throwaway Robolectric reproduction: the account section's composition survives the -link landing under it (`Ready(unlinked)` → `Loading` → `Ready(linked, ADMIN)` → -`isRefreshing` both ways); the exact-alarm path catches its `SecurityException` and asks -`canScheduleExactAlarms()` first; nothing polls `/me`; and linking triggers no sync at all — -`syncNow` has two callers, `SessionEffects` and the widget. So the sync whose state updates -in the report is the periodic one, landing near the link by coincidence rather than because -of it. The next step needs the stack trace this batch makes reachable. - -`./gradlew test assembleDebug assembleRelease` green: **738 tests across 96 classes**, up -from 736 across 95. - -**What only the owner can do.** Install a build carrying this row — which on the current -debug-signed APK means uninstalling first, and that takes the device's classes, token, diary -session and corrections with it. And the reports stay off until the switch is on, by the -earlier deliberate decision about what may land on disk: this batch changes who can read what -is written, not when it is written. - ---- - -## What the batch before added: the guide is fetched, and a debug-signed APK explained - -Four commits in `dev`, merged as PR #67 (`0957628`), in the milestone `v0.6.0`. Two -unrelated things that arrived in one batch because the first was a question about the -second's build. - -**Installing 0.6.0 over an older build failed, and the repository was wrong about why.** -«Приложение не установлено», after offering to update, with the version raised. The cause is -that **the debug keystore is generated on the machine that builds and thrown away with it**: -the alias and both passwords are constants, the key pair is not, a runner is a fresh machine -every run, and the Gradle cache covers `~/.gradle` rather than `~/.android`. So every APK run -signs with a certificate that has never existed before, and Android compares the certificate -before it looks at any version. Measured rather than reasoned — the APK from run 15 carries -`CN=Android Debug` with `validFrom` two minutes into that run's own build step. - -Two statements in this repository said otherwise. `docs/build.md` said the debug key "is the -same for everybody"; `apk.yml` said twice it is "the same certificate on every machine on -Earth, so anybody could then build an update Android would accept". **Nobody can** — the key -is gone, which is the real cost, because that includes whoever published it. The second real -cost is authorship: `CN=Android Debug` is what every debug build says. The gate that refuses -to publish an unsigned release is unchanged; only its reason is. `docs/build.md` now has the -section a reader meets this in, including that the only cures are an uninstall — which takes -the device's classes, token, diary session and corrections with it — or the four secrets. - -**`apk.yml` also discarded any `versionCode` it was given**, overriding it with the run -number and offering no input for it. There is a `version_code` input now; blank still means -the run number, and it is validated before anything else runs — empty, `0`, `-3`, `1.2`, -`abc`, `"12 34"` and a command substitution are all refused rather than evaluated. - -**The in-app guide stopped being 103 string resources.** It is two markdown files in -`docs/app/` — `guide.ru.md`, the source, `guide.en.md`, its translation — plus a manifest -naming the documentation's version and the app version it describes. The app fetches them -from `raw.githubusercontent.com`, stores them in its own files, and falls back to the copy in -its assets; `docs/app/` **is** `:core:data`'s asset folder rather than a copy of it, so the -bytes in the APK are the bytes in the repository. Verified by listing the assets of both -built APKs. - -The format is a deliberately small subset — `##` a page with its metadata comment, `-` a -list, `1.` with a bold lead a step, `>` an aside, and `**bold**`, `` `code` ``, `[text](url)` -inside a line. **The parser never throws**: an HTML error page, a JSON body or a truncated -file parses to no pages, and the repository keeps what it already had rather than replacing a -working guide with an empty screen. - -**Every page now states which documentation it is** — version, date, and the app version it -was written for — and adds a second line only when there is something to say about the copy: -no network, an answer that was not a guide, or the copy the app shipped with. - -**The sections stopped being screens.** They are peers, so they are a `HorizontalPager` -swiped like the three home tabs, and the toolbar scrolls it rather than pushing a screen. -Back therefore has one meaning here, which is what the arrow beside the pill does: leave the -documentation. `DocsHistory`, the page enum and the depth-per-section that existed to animate -pushes between peers are gone. Pull to refresh uses `LessonsPullToRefreshBox`, the same -expressive loader the two other refreshing screens use, and it shows while the automatic -check runs as the guide opens. - -**One defect found by re-reading the diff rather than by a test.** `storedOrBundled` -preferred a fetched copy over the bundled one unconditionally, so a phone that fetched -version 3 a year ago and then installed an APK carrying version 5 would have been shown the -**older** guide — offline, for as long as the network stayed down, which is exactly the case -the fallback exists for. The rule is a named function of two numbers now, `preferStoredCopy`, -and it is tested; proven red against the code without the fix. - -**What it gives up, and it is a real cost.** The guide's text is no longer a resource, so -correction mode cannot touch it and `ResourceTranslationTest` no longer guards it. A wrong -sentence in the documentation is now a pull request against `docs/app/` — the same place the -app reads it from. `DocsGuideParityTest` took over what could be kept: both languages parse to -the same pages, in the same order, with the same ids, from the same blocks, with no list of -one point, no step numbered out of sequence and no paragraph written twice. It reads the -shipped files rather than a fixture. - -`./gradlew test assembleDebug assembleRelease` green: **736 tests across 95 classes**, up -from 725 across 93. The README, `docs/architecture.md` and this file's cheat-sheet carry that -number; `architecture.md` gained the section describing the pipeline and `design.md`'s line -about the documentation's longest page is corrected. - -**What nothing has verified.** Not one line of the fetch has run against GitHub — the parser, -the parity of the two files and the choice between two stored copies are tested, the network -path is written and never executed, exactly like the translation flow in #64. Nothing has -been pressed on a device: the pager, the loader, the banner and the arrow are laid out by -code and seen by nobody. The bundled assets are proven only by the APK's contents, because -`:core:data`'s tests have no `Context`. And the new `version_code` input has never been run. - -**The chain of close-outs stops by rule now, and merging no longer waits for a sentence.** -Every batch ends in a close-out, whose own merge is then a thing no close-out describes — -and writing one for that needs another, for ever. The rule: a close-out rides inside its -batch's own pull request while that pull request is open, it names itself as the only thing -open, and **the SHA of its own merge is written by the next batch** rather than by a pull -request about it. Separately, the owner asked for a green pull request of this session's own -work to be merged without being asked each time; that is recorded in the `github-pr` skill -as their standing instruction, with the five things to check first and the cases it does not -cover — an unsettled migration, somebody else's pull request, and «I want to look at this -one». - -**And the hook added in #65 was wrong, in the one case the rule prefers.** It fired after -#67 merged, saying the close-out was missing — while `HANDOVER.md` had described that batch -since `6caca07`, inside the pull request, which is exactly what the rule asks for. A -close-out written that way is landed **by** the merge commit, so it is always older than it, -and a hook comparing only timestamps calls it missing every time the rule is followed -properly. It now asks first whether the merge's own diff touched `HANDOVER.md`; the -timestamp is the fallback for a close-out committed after a merge instead. Tested in all -three directions in a throwaway repository — carried by the merge, not carried, committed -afterwards — and silent on this tree, where it had just spoken. - ---- - -## What the batch before added: a correction goes out as a pull request - -Three commits in `dev`, merged as PR #64 (`e4361a0`), in the milestone `v0.6.0`. Before them, -PR #63 (`ec0d976`) carried the previous batch's close-out in this file and nothing else, and -went into `main` on the owner's instruction. - -**Correction mode used to end in a fragment somebody else had to paste.** It produced a -`` element, and that was the whole delivery: the reader copied it, or shared it, and -the work reached the project only if a second person carried it. The session sheet now also -offers to open a pull request, and it is opened **from the account the reader signed in -with**, not from the project's. - -**The sign-in row moved to where it is needed.** It sat in the group about GitHub under -«О приложении»; it now sits directly above the correction-mode switch, which is where -somebody looking for it will be. Signing out stays in the old group beside the bug report -the account is otherwise for — two rows on one page showing the same account state is one -row too many. **Signing in is not required to make corrections:** the mode, the editor and -the session are local and work offline, so only the button that *sends* them goes dark -without an account. The anonymous update check was left alone for the same reason — it needs -no token, and a sign-in wall there would break something that works. - -**Putting a corrected string back is its own file, with its own test.** `StringsDocument` -replaces one element's body and leaves every other byte of `strings.xml` where it was. Seven -tests hold the parts that would go wrong quietly: `name="settings_title"` must not match -`settings_titles_plural`, a `` of that name is a different resource, an -attribute written before `name` must not hide the element, a `>` inside a value must not cut -the body short, and a key the file does not declare is refused rather than appended. - -**What was taken from Essentials, and what was not.** Taken: where the row sits, the shape -of the flow, the two states of the account row. Not taken, because each is a defect rather -than a decision — their submit button is enabled while signed out and bounces the press to a -prompt; they clear the session on a *posted comment*, which is not a delivered correction, so -if the workflow behind it fails the reader's work is gone and nothing says so; their -`triggerWorkflowDispatch` passes the user's OAuth token as a workflow input, where it is -visible in the Actions UI and kept in the run record; and their translation feature carries -hard-coded English literals beside `stringResource` calls, which `ResourceTranslationTest` -would refuse here. - -**The transport is different on purpose.** Essentials' public path is a comment on a -hard-coded discussion thread, turned into a pull request by a workflow holding -`contents: write`; the contributor survives only as the commit author. That needs a -discussion, a workflow and a write permission this project does not want — and it does not -do what was asked, because the pull request is not the reader's. A fork and a pull request -are, and the `public_repo` scope the sign-in already requests covers both, so nobody has to -re-authorise. - -**Two defects in this batch's own code, found by re-reading it rather than by a failure.** -A repository merely *named* `lessons` was taken for the fork — the check asked for -`/repos/{login}/lessons` and read any 200 as "the fork is there", so a reader who already -owned an unrelated repository of that name would have had a branch cut in it and a commit -written to it, over a corrected string; it now reads the body and requires a fork whose -parent is this project. And the submit ran on `rememberCoroutineScope()`, which dies with the -composition, while the comment above it claimed the view model owned it and it survived -dismissal — closing the sheet cancelled the work. The launch moved to `viewModelScope`, which -fixed the comment's honesty as well as the behaviour. A third was caught before it shipped: -acknowledging the outcome inside the `LaunchedEffect` that opens the browser would have -cleared the message in the same frame it appeared. - -**Two things in that code that are easy to get wrong.** The branch is cut from the -**upstream** commit, not from the fork's own head: a fork made once and never synced is -behind by everything merged since, and would offer all of it back as reverts. And the -**owner of a repository cannot fork it** — GitHub answers 422 — so their branch goes straight -to the upstream repository, which is the case the first person to try this will hit. - -**Three places said 718 tests across 92 classes; the suite is 725 across 93.** This file's -cheat-sheet, the README's «Honest status» table and `docs/architecture.md` are corrected. -`docs/architecture.md` was wrong in a second way that the total had hidden: its per-module -breakdown still summed to 709, because the previous batch moved the total and not the five -numbers under it. They now read `:core:model` 94, `:core:data` 234, `:core:designsystem` 54, -`:widget` 68, `:app` 275 — counted from the test XML of a real run, and they add up. - -**What nothing has verified, and it is the whole point of the batch.** Not one line of the -fork, the branch, the commit or the pull request has executed against GitHub. There is no -test for it and no way to write one here — it needs an account, a token and a real -repository. The two defects above were found by reading, and the same reading cannot prove -there is not a third. **The first press should be the owner's, not a reader's.** Nothing has -been pressed on a device either: the row, the dark button, the spinner and the message after -it are laid out by code and seen by nobody. - -**Updating this file is now a written rule rather than a request (PR #65).** It had to be -asked for twice — once after #62 and once after #64 — and each time a batch had been called -done while the document a new session starts from still described the batch before it. The trigger is -the merge, and it is written in `CLAUDE.md`, in `AGENTS.md`, in the `handover` skill (which -also lists what goes stale mechanically, because reconstructing that list by hand is most of -the work) and in `github-pr`'s new «After it merges» section. `/where-are-we` now compares -the document's claimed state against the commits and says when it is behind. And a second -hook, `.claude/hooks/handover-behind.sh`, says one sentence on `Stop` when a merge commit is -newer than the last commit touching this file — which is true only in the window after a -merge and before the close-out, and stops being true the moment the file is committed. - -**The hook has since fired for real, and it was right.** It was proved in a throwaway -repository before it was committed, and the pull request that carried it said in as many -words that nothing had seen it fire in a session. #65 merged, `dev` was fast-forwarded, and -it spoke — about #65 itself, which this file did not yet describe. That is what the sentences -above and the paragraph at the top of this file are. **The regress ends the same way #63 -ended it:** the close-out describes its own pull request while that pull request is open, so -the file is already true when it merges. A close-out does not get a close-out of its own. - -**Deliberately left alone.** Milestone 6's description on GitHub still reads «PRs #60–#62» -though it now holds #63 and #64 as well — no tool here edits a milestone, so that is the -owner's line to change. The update check stays anonymous: it asks GitHub for the latest -release, needs no token, and putting it behind the sign-in would take a working feature away -from everybody who never signs in. - ---- - -## And before that: nothing on a screen is cut off - -Five commits in `dev`, merged as PR #62 (`f13d60e`), in the milestone `v0.6.0`. Three pieces, -and the second and third are consequences of the first rather than separate work. - -**A line that does not fit now scrolls instead of ending in «…».** «По этому предмету ничего -не задано» was drawn as «По этому предмету ничего н…» in a sheet with a screenful of room -under it. The app already had the better answer in one place — the segmented picker's labels -scroll and fade at both ends, because on a picker the whole word *is* the button — and that -behaviour is `MarqueeText` in `:core:designsystem` now, on 21 call sites. It measures the -string against the width the box actually has before deciding, because the layout cannot be -asked: `basicMarquee` hands the text unbounded width, so the node never reports overflow and -`onTextLayout` answers `false` for ever. A label that fits is left exactly as it was. - -**The nine blocks that cannot scroll stopped being capped instead.** A `maxLines = 2` block -has no single line to move sideways, and stopping there would have left the ellipsis -standing — only the shape of the answer had to change. Every one of the nine sits inside -something that scrolls, so the cap is simply gone: a sheet heading, a screen header and its -subtitle, the supporting line of both row shapes, `RowText`'s subtitle, a lesson's hand-typed -note, the hero card's detail. The row grows and nothing is lost. The one with least excuse -was `TimetableSheet`, which echoes the lines the parser refused so the typo in them can be -found and was cutting them at two. `TimelineBlock` on the week ruler went the other way: its -height *is* the lesson's duration, floored at 30 dp, so it is the one block in the app that -genuinely cannot grow, and its title marquees. - -**Then the test found a silent clip nobody was looking for.** A bare `maxLines = 1` with no -`overflow` does not ellipsize — it clips, with nothing to show that anything was cut, which -is the same refusal with the warning removed. The hero card's countdown row had one: the row -wraps its content and shares no weight, so at a large font scale the number takes the width -and «до конца» loses its end in silence. That label marquees with a weight now. The countdown -beside it deliberately does not — it is rebuilt every tick, so a marquee would be handed a -new string each second and restart from the left for ever. - -`NoEllipsisedLineTest` holds all of it, and it reads **every** module rather than the one it -lives in — the same correction `ResourceTranslationTest` once needed, for the same reason. It -refuses any `TextOverflow.Ellipsis` and any bare `maxLines = 1`, with one opt-out: a `//` -line saying why, which six places carry. Proven red twice, and the second time against real -code rather than a planted fault — the comment explaining one cap sat above the `Text(` -instead of above the cap itself. - -**Three documents said 709 Android tests across 90 classes; the suite is 718 across 92.** -The README's «Honest status» table, this file's command cheat-sheet and -`docs/architecture.md` are corrected. A fourth mention is deliberately left standing: this -file records the gates «on the whole tree at `d330d68`, the last commit before the merge», -and at that commit there really were 709 across 90. Rewriting it to today's number would -turn a true record of a named commit into a false one. - -**Every pull request now carries a milestone, and the rule is written down.** Sixty-two had -gone in without one, and they have one only because somebody went back and did it by hand. -There were no issues in this repository then — #128 opened the first — so the milestones -were the only grouping its history had. Seven existed and they are **retrospective**: the -boundaries were read off the history rather than declared, and nothing here has ever been -tagged or released, so `versionName` is still the `0.1.0` default. +## The milestones **The milestones as they are now.** The owner renamed all nine on 25 September 2026, so that every title names what its version delivered and every description names its pull requests @@ -2736,817 +340,13 @@ the ninth on 22 September 2026 and the tenth on 25 September. **The ninth was th milestone that groups issues rather than pull requests**, and the first whose work cannot be done without an emulator or a phone. -From here the rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` skills: -a found defect becomes an issue before it becomes a fix, the pull request ties itself to it -with `Closes #NN`, and a release explains every change with both numbers beside it. - -**What that rule had to record is what a session cannot do.** Nothing here creates a -milestone or even lists one — no tool, no `gh` CLI, and `issue_write` accepts only a number -that already exists. So when none fits, ask the owner with the title and the description -already written, rather than inventing a version or leaving the pull request bare. Two traps -are written down beside it: a milestone's number can be read back by assigning it and -searching `milestone:""`, whose result embeds the milestone object; and GitHub's -search index lags the write by up to a minute, so `is:pr no:milestone` reported two bare -pull requests that already carried one. The procedure is in the `github-pr` skill, with a -pointing line each in `CLAUDE.md` and `AGENTS.md`. - -**Deliberately left alone.** `:widget` is outside the no-ellipsis rule and cannot be brought -in: Glance has no `TextOverflow` at all, and no marquee either, because RemoteViews has no -frame loop and a widget cannot animate anything. `WidgetStrings.ellipsize` writes the «…» -into the string by hand because the platform leaves no other answer, and the test says so -where it excludes the module rather than letting a vacuous pass look like coverage. -`.github/copilot-instructions.md` did not get the milestone rule: it is short on purpose -because it is read on every request, and every line in it is about what not to suggest -inside code. - ---- - -## Earlier still, on top of the audit - -Twenty-five commits after `13348d5`, in five pieces. The first two finished the audit batch; -the last three are things that batch left behind, and one of them was found by re-reading -the session's own work rather than the project's. - -**A re-check of the whole batch, and then the remainder of it.** The server half: both bells -writes now answer the caller with `silenced_lessons`, because shrinking a schedule leaves -every lesson past its new last rung stored and drawn nowhere and only the bot was saying so; -a substitution on «1 сентября» is no longer refused as a summer date (`school_year_bounds` -files both June and the first days of a September whose 1st falls at a weekend before -`year_start` — the next four are 2029, 2030, 2035 and 2040 — and one sentence covered both); -`render_import_preview` stopped writing its cap -twice; and `MESSAGE_LIMIT`'s comment now names the one direction in which a raw character -count reads *lower* than Telegram's, which is emoji outside the BMP. The Android half reads -that new field and says «2 урока перестали звонить» under «Сохранено». `docs/bot.md` gained -the budget rules, which were true in six renderers and written down nowhere, and `docs/api.md` -documents the field. - -**Three Android gaps closed.** A phone that signed out and rejoined in the same process got -one refresh and then nothing until the next cold start — `schedulePeriodic`'s only caller -watches the interval, and a re-join moves no interval, so the re-arm moved into -`SessionEffects`. The `304` path stopped re-reading the whole cached year to re-derive an -alarm it almost always finds already armed, and asks `FLAG_NO_CREATE` instead; what that -gives up is written where the decision is. And the alarm chain, the change fingerprint and -both of the widget's reads — the redraw and the tick scheduler that arms it, which is the most -frequent read there is — now take a fortnight rather than a year, through `snapshotAroundToday`, -the bounded read that -`docs/` said could not be written, because `schoolDayAfter` has to reach September from July; -it is resolved in SQL beyond the bound and handed over as `nextSchoolDay`. Separately, -`PeriodsForm` keeps its six bell times through a rotation, and `StabilityPromiseTest` is no -longer one regex for `var`. - -**Dependency injection with dishka** (`server/app/di.py`). A session was made in three -places — a FastAPI dependency, `SessionLocal()` in the bot's middleware, and `session_scope` -in `scripts/seed_demo` — each with its own view of whether the caller or the maker commits. -`session_scope` is the one still standing, because a script is not a request and has no scope -to take a session from. It is -now one container: `Settings` and the session factory at app scope, one `AsyncSession` per -HTTP request or Telegram update. All sixty-four endpoints ask with -`session: FromDishka[AsyncSession]` and `db.get_session` is gone; the bot's -`ContextMiddleware` opens the update's scope itself and takes the session from the same -provider, and still commits there. Dishka rather than FastAPI's `Depends`, which is -already a DI system, for one reason: `Depends` cannot serve an aiogram handler. Three things -worth knowing before adding to it are written in the module: it must not import -`dishka.integrations.aiogram` (that puts aiogram on every cold-start path), the container is -built with `STRICT_VALIDATION` so a duplicate provider is an error rather than silent -shadowing, and `app/api/routing.py` exists because dishka's compiled wrapper carries its own -globals, so under postponed annotations FastAPI took an endpoint's `-> Response` for a -response model. - -**An adversarial re-pass over the container work itself**, which found seven things — most -of them latent, one of them behaviour, and several of them defects in what the session had -just written rather than in the project. - -* `write_bell_periods` answered «перестали звонить уроков: N» with a *state* — which rows - these bells do not cover — while the field it fills is documented as an *event*. Nothing - deletes an orphaned row, so the same write repeated said it again, and so did nudging one - bell by five minutes. It asks `lessons_silenced_by` now, which is what the other way of - losing lessons already asked. -* `close_container()` forgets the container, but `setup_dishka` had put a *reference* on - `app.state` at import and a reference does not update itself — so a second lifespan in one - process, which `tests/test_startup.py` is, served every request from a container that had - shut its app scope. The lifespan re-reads `container()` on the way in now. -* A closed dishka container goes on answering, and asking it for an app-scoped object - **builds a new one** in a scope whose exit stack has already run — so nothing will ever - close it. With an app-scoped HTTP client that is a leaked socket per ask. Invisible today - because nothing app-scoped here owns a resource, which is exactly why it is pinned now. -* `setup_dishka` registers one middleware on every observer, each opening a scope on the - *root* container — so a message got two **sibling** scopes, not nested ones, and anything - resolving a session at update level would have had its own that nothing commits. A comment - claimed the opposite and claimed it had been verified; the verification had tested - something else. `ContextMiddleware` opens the one scope itself now, from `container()` read - per update — which also stops the dispatcher `api/telegram.py` caches for the life of the - process serving webhooks from a container closed at shutdown. -* Three documentation defects: `session_scope` named as the cron tick's, the September - comment missing 2030, and three documents still describing the `setup_dishka` arrangement - after it had been replaced. - -The pass also confirmed four things that would otherwise have stayed assumptions: one session -per request across every `@inject`ed dependency including the sync `_service`; the -`MissingGreenlet` branch in `_touch_last_seen` still answering 200 after a failed commit; all -68 routes carrying real response models with `app.openapi()` generating clean; and -`/api/v1/health` still opening zero connections under the new ASGI middleware. - -**One defect found by the clock.** «📒 Неделя» in the diary took its Monday from -`today - today.weekday()`, so on a Sunday it showed the six days that had just ended. It -surfaced as a test that had been wrong since it was written and went red for the first time -after midnight Moscow time on a Sunday. - -That batch is two pieces. The first took two things from -[GMS Flags Reborn](https://github.com/polodarb/GMS-Flags-Reborn) (Apache 2.0, © polodarb) — -the expressive loader and the transformation between first-run steps — and then, on a second -pass over that repository, the two practices this project was actually missing: lazy-list -content types where a list holds mixed shapes (`DocsScreen` alone), and a Compose stability -configuration. The stability one was measured rather than guessed: the compiler's own report -said 36 of 94 classes in `:app` were unstable, almost always for one `LocalDate`, and -`compose-stability.conf` takes that to 29 with every screen state that holds a date now -stable. What is deliberately **not** promised is written at length in that file. Their module -layout, Koin and MVI were deliberately not taken, and their Gradle configuration and CI are -behind this project's rather than ahead — the detail is in `docs/design.md`. - -The second piece is **the nine-area audit protocol run a second time**, by area, each finding -re-verified by hand before it was fixed and each closed by a test proven red without the fix: -**23 defects**, and then a ninth area — the integrity of the test suite itself — found eight -places where CI was green about things it does not check, `api/index.py` among them: nothing -in the repository read the file Vercel routes every request to, so renaming the symbol left -both gates green and every request a 500. Tests: 1391 → 1450 on the server, 605 → 668 on -Android. Three of the seven -batches reported tests that passed on the broken code when first written and rewrote them -rather than shipping them, and **a fourth found a pre-existing test asserting a defect as -correct behaviour** — `test_the_star_moves_when_another_schedule_is_made_the_default` built a -bell schedule with no rows and asserted the star moved onto it. The fixture was given rows; -the fix was not relaxed. That is the **third** time this project has found a test holding a -defect in place. - -The ones that would actually have been felt, one line each: - -* **nobody could sign in to the diary** — `login` read the session cookie with - `response.cookies.get`, which raises `CookieConflict` on the two-cookie answer, and that is - not an `httpx.HTTPError`, so it escaped as a 500 and spent the sign-in ticket every time; - `_session_cookie` was written for exactly that failure and sat one line away; -* eight bot renderers could still send a message Telegram refuses whole — «🗓 Неделя» - measured at 4648 characters, «👥 Доступ» at 4623, and that is the only screen a class on - «по приглашению» can reopen its door from; -* two screens echoed back text the database had truncated, so the confirmation claimed a - subject or a title that was not saved; -* substitutions announced to the whole class and drawn nowhere, from two independent causes — - a replacement with no subject over an empty number, and the summer rule reaching one screen - further than anybody had checked; -* re-pointing a class at a shorter bell schedule took every later lesson off every weekday - with nothing anywhere naming them, and from the bot an **empty** schedule could still be - made the class default, which blanks the phone, the widget, the calendar feed and the - digest at once *and* disables `can_ring`; -* below API 33 the app recreated itself on every cold start for anyone who had chosen a - language, and the recreation ate home-screen widget day-taps; -* the alert chain cancelled itself across any break longer than the planner's eight-day - horizon, with only a cold start to revive it; -* the widget's «Дальше» column listed the lesson an assembly on screen had replaced. - -**What only the owner can do.** Three decisions were deliberately left rather than taken, two -of them in section 7 — the widget's tick cadence, and whether the diary credential should -carry a bound — and the third named in the merged pull request: whether the four API -announcements that interpolate a person's text should carry `shorten`, which is a decision -about what a notification ought to say rather than a defect. Beyond those, an APK on a real -phone is the only thing that can settle the list below, and only the owner has one. - -Gates on the whole tree at `d330d68`, the last commit before the merge: `ruff` clean, -`python -m mypy` clean across all 81 modules, `pytest -q -n auto` 1465 passed; -`./gradlew test assembleDebug assembleRelease` successful with 709 Android tests across 90 -classes and 0 failures. CI was green on that head and on the four before it. - -**What nothing has verified**, and it is now on `main` rather than proposed: - -* **None of the Android work has run on a real phone.** The `304` path and the widget's - bounded read are claims about battery that only a device can confirm; what the first gives - up is written where the decision is — it trusts a `PendingIntent`'s existence as proof an - alarm stands, so a vendor battery manager that drops one and keeps the other is not healed - there. `BellRowsRotationTest` uses `StateRestorationTester`, which re-composes rather than - killing the process, so it proves the saver round-trips and not that the bundle survives a - real low-memory kill. «2 урока перестали звонить» has never been drawn. -* **`BoundedSnapshotParityTest` reproduces the bound rather than driving the real - repository.** `CachedWindow` and the in-memory DAO are `internal` to `:core:data` and - Kotlin `internal` does not cross a Gradle module, so driving them from `:widget` would mean - adding `testFixtures` to another module's surface for one test. It is reproduced locally - the way `WidgetSizeClassTest` reproduces the launcher's rule; `CachedWindowTest` owns the - other half — that the repository implements that bound against the real DAO. -* **The dishka wiring has now run on Vercel** — see the warmup read above, which is one - request and not a measurement. The 26 ms it adds to a cold start is still measured on a - development machine rather than there, and that the webhook path still defers aiogram is - read off the imports rather than timed there. -* **The bot has not been driven end to end since the container moved under it.** Every - handler is covered by tests that call it directly with a session; nothing in the suite - feeds a real update through `build_dispatcher()`, so `ContextMiddleware` opening its own - scope is proven by unit tests and by reading, not by an update arriving from Telegram. - -Before this batch, after PRs #47, #48, #49, #50 and #51 were merged. The -last of them is the agent configuration in `.claude/` and the whole written layer of the -project moved into English (see "Everything written about the project is English" in -section 6). It landed as `85064cd`, and `main` and `dev` are level. The database is at -head `0013` and `EXPECTED_REVISION` did not move, so that merge needed no migration. The -production deployment it triggered is `READY` on `85064cd`, and `/api/v1/warmup` was read -after it: `{"status":"ok","api_version":1,"schema":"0013"}`. That endpoint opens a -connection, so it answers for the database too, not only for the code. - -After that batch, two small ones: #55 and #56 corrected this file's own header — it said -PR #51 was open minutes after it had been merged — and a sweep over every document -re-measured the numbers they quote. What that sweep found is at the end of section 6. - -Two batches earlier: publishing the repository and everything that followed from it (the -history reviewed for secrets, `pytest` in CI spread across cores, artifacts living a -week), a deployment that refuses to start rather than quietly taking a local default, and -the Google Sans Flex licence — it is OFL 1.1 rather than MIT, as the comment and the -documentation claimed: the licence text now travels inside the APK, stands as the eighth -row under «Лицензии», and `FontLicenceTest` reads the typeface's own `name` table so that -what is claimed and what lies beside it cannot drift apart. - -**PR #50 is merged**, five commits; it needed no migration — the model did not change and the -head stayed `0013`. The first two commits are the translation-correction mode across all of -the app's text (see "The correction mode knows about all the text" in section 6 and the new -section of `docs/design.md`). The other three are **an audit of the whole project by nine -subagents, split by area**: the API, the bot, `services` + `schedule` + `models`, the -providers + config + migrations, `:core:model` + `:core:data`, the design system + the -widget, `:app`, the correction mode itself, and separately the build, CI, the scripts and -the integrity of the test suite. - -Thirty-one findings, every one verified by hand before it was fixed; each closed by a test -that fails on the code without it. Tests: 1362 → 1391 on the server, 578 → 605 on Android. -The most serious, one sentence each: - -* five of the bot's renderers and the evening digest went past Telegram's 4096 characters — - the message is refused whole, and `/today` (a plain `answer`) replied with nothing; -* an empty bell schedule could be made a class's default: `/bundle` handed back zero - lessons, `/now` said «выходной» on a Monday, and the timetable lay untouched throughout; -* renaming a subject onto a name that exists only in the homework failed with a 500 and lost - the rename entirely; -* shortening the bells silently took every lesson above the new ceiling off the timetable; -* a `401` on `/bundle` never reached `onTokenRejected` — a `Response<T>` in Retrofit does not - throw — and a revoked device kept a class and a year of somebody else's data; -* a `304` against an empty cache answered "success" for ever: the app stayed empty; -* a duplicated session cookie dropped the whole diary into a 500 on every call; -* `POST /diary/login` was an unlimited password oracle against somebody else's service; -* a release tag could publish an APK signed with the debug key — the gate checked one secret - of four; -* `seed_demo` wrote to wherever `DATABASE_URL` pointed, saying nothing about it. - -**Three tests asserted the defect as correct behaviour** and were replaced. The full list of -findings and what was done with each is in the bodies of commits `5ec62a6`, `afba3c5`, -`b8d8deb` and `3997b29`. - -What is still open: - -1. **The external cron is not set up.** Until it is, the digests go out whenever GitHub - deigns to run the schedule — measured at 6.7 times a day instead of 288. The bot's promise - that they arrive "within about five minutes" is untrue until then. What exactly to set up - is in `docs/deploy.md`, "The clock". -2. **The production Neon endpoint's host and the project id stayed in the history.** They are - out of the working tree, but the repository is public and that does not change the - history. The owner changed the role's password and updated `DATABASE_URL` in Vercel, so - the address in the history is no longer enough on its own. **The variable is set for - Production only:** Preview fails with `ModuleNotFoundError: No module named 'aiosqlite'` — - which is the refusal at the door, just from before it learned to name itself. Either set - it for Preview too, or do not look at preview deployments. - -If you are an agent: `CLAUDE.md` first (the project's rules), then this file (what is already -done and what is left), and the agent configuration is in `.claude/` (see section 6, "The -agent configuration lives in `.claude/`"). Treat everything below as verified fact as of the -date above, but **re-check the branches and CI before your first action** — they live their -own lives, and this file goes stale the moment it stops being updated. - ---- - -## 1. In one paragraph - -**There are exactly two branches, `main` and `dev`,** and after PR #43 they met. Everything -that had piled up in `dev` is now in `main`: the former working branch, five dependabot -branches — cryptography, asyncpg, AGP, the androidx group and the Gradle wrapper — and eight -substantive commits on top. The six original branches are deleted and their pull requests -(#35, #36, #38, #39, #41, #42) are closed with the status **Closed rather than Merged**: -GitHub counts a pull request as merged only when its commits reached its own base, and the -base for all six was `main`. The code was not lost: it arrived through #43. - -On top of that, ten substantive commits landed in `dev`: - -* `8ec2e31` — a phone holds several classes at once and switches between them; -* `569bab8` — six defects that four audits found in `8ec2e31`. The first is serious: a `401` - on one class threw the device out of **all** of them; -* `ce02348` — corrections laid over the diary, with an undo, and revision `0009`; -* `c6ba66c` — fifteen findings from two audits of `ce02348`; -* `59c7a77` — the class's join mode, the personal connect codes, revisions `0010` and `0011`, - and seven findings from one more audit; -* `98c8018` — the database brought up to `0011` through the Neon connector, **before** the - merge; -* `70b9dcb` — a `429` on the code screen says how long to wait rather than "HTTP 429"; -* `ab488ad` — twenty-one findings from three audits: Android, the bot and the documentation; -* `8aa4ecd` — three of the app's screens are pressed in the build (Robolectric in `:app`); -* `bf74233` — «🗓 Четверти» crashed in production on every press; fixed; -* `a58d2be` — the "does the code reach for an attribute that does not exist" check across the - whole server; `rows_affected`; thirteen tests on the flows in `content.py`; -* `33deca3` — the rest of the bot's cards are drawn in tests, and eight of them turned out to - be broken; -* `a9be1c4` — every drawn row has a button, the alert is cut at Telegram's ceiling, a dead - renderer is deleted; -* `6a1dded` — a forged press gets a refusal rather than an endless spinner; -* `f3839c8` — a date that is not in the calendar is rejected rather than crashing the handler; -* `c2038e4` — an event's kind and a lesson's number are checked where they are picked; -* `1d84d89` — a far-away date answers 422 rather than 500, and `PATCH /tasks` does not put - NULL into a NOT NULL; -* `ae8e3b8` — the countdown and the quarter speak the phone's language; the translation guard - is extended from one module to all four; -* `8cba40b` — seven findings in the adapters and the plumbing: the diary no longer loses a - lesson's time or an only child; -* `94ea9b5` — a bell schedule is read by its numbers rather than by its row count; four - findings in the shared rules; -* `4f5471d` — the template stopped expanding all summer; a substitution and a pasted day - check the bell; one assignment per subject per day; revisions `0012` and `0013`; -* `3a592c9` — the diary sign-in page stopped blaming the password; `httpx` pinned; the - turnstile, a token made of spaces, a rolled-back transaction in `current_revision`; -* `69bf4ba` — one link, one sign-in; `/bundle` does not fail after losing the race to seed - the terms; the subjects screen does not throw away its own link. - -The fourth pass (four subagents over four non-overlapping zones, every finding re-checked -here by reverting the fix rather than taken on trust): - -* `ea3afc8` — "N skipped, no bell" counts rows rather than numbers; -* `24b4841` — the diary notices a changed response shape instead of an empty week; -* `7712dc7` — `scripts.init_db` stamps `alembic_version`; `requirements.txt` is kept level - with `pyproject.toml` by tests rather than by attentiveness; -* `8bec2ff` — the selected class survived the sweeping of abandoned dialogues; -* `0c99993` — revoked access takes the class's subscriptions with it; -* `8995fa6` — the role in the menu, the time of the first digest, the length of the homework - digest; -* `38e8aec` — a day cannot be hung on a bell schedule with no rows; -* `bf2338d` — signing into the diary with no `DIARY_SECRET` answers 503 rather than 500; -* `591b3a4` — «Выйти» from the diary leaves no second live session behind; -* `7c99652` — every notification has its own press target; the widget does not hide the room - for the sake of a teacher who is not there; -* `cc3935e` — deleting a lesson does not shift its neighbour onto a number with no bell; the - "collect from the timetable" counter stopped counting other classes' rows as its own. - -The fifth pass — what the fourth named but did not do: - -* `a47d58c` — on a failed read the widget does not push you to "enter a class code"; the one - unverifiable minute setting is brought into a range; -* `1676915` — the webhook checks the secret before parsing the body, and the sign-in form's - body ceiling is measured on the way rather than after everything is already in memory; -* `a0fe48b` — one calendar link per class (a conditional `UPDATE` and a read back), and the - digest assembled inside a savepoint, so that one failing class does not take the whole tick - down on Postgres; -* `060f385` — cancelling a lesson that is not in that day is rejected: it used to go into the - log and out to every subscriber, and be drawn nowhere. - -The sixth pass — both of the owner's decisions taken and done: - -* `f0ba014` — a date outside the school year reads as `DayOff(HOLIDAY)` rather than "no - data": in summer the widget says «Каникулы» and shows the homework for 1 September instead - of asking to be pulled down for something that was never coming. A date **inside** the year - with an empty cache stayed `NoData` — there, pulling down is exactly what helps; -* `5b10815` — the client sends `If-None-Match`. The tag sits in DataStore under the request's - signature (class, `start`, `days`), so 1 September and a change of class simply stop - matching and the next sync asks for the whole window. A `304` does not write to Room and - does **not** wake the widget, but it does move "updated N ago": that line is about the - check rather than about the data. - -**Section 3.1 was closed entirely when this was written.** One requested item has been -added since and is open: scrolling the calendar by years, which is a decision rather than -work — see section 7. - -The block below is **the state on the day this section was written**, kept because the -migration order it records is the thing worth reading twice. It is not today's: the -branches, the open pull request and the two test counts have all moved since, and the -paragraph at the very top of this file is the one that is kept current. - -``` -As of PR #51 — not current; see the top of this file -Merged: PR #43, PR #44, PR #45 (six passes, 38 commits, merge 26ad184), - then PR #47, #48, #49 and #50 — main at 22399e9 -Open: PR #51 (dev → main) — the agent configuration, and this translation -Branches: main and dev; dev runs from 22399e9, that is, from the merge of #50 -Gates: ruff clean, mypy clean, 1391 server tests, 605 Android, both assembles -Database: production at 0013, which is the head. 0010–0012 were applied through - the Neon connector BEFORE the merge, 0013 (a UNIQUE) AFTER, as its - shape requires. No separate database action is outstanding -``` - -**A merge to `main` is a deploy.** Vercel builds `main` by itself. The order was mixed this -time, and deliberately so: `0010`–`0012` went into the database in advance, so the window in -which the code knows a column the database does not have never opened for a second, while -`0013` — a constraint that the **old** code breaks against — went on immediately after the -merge. Between them `services/homework.py` behaved exactly as production did before it. One -request checks that it all lines up: - -```bash -curl -s https://<project>.vercel.app/api/v1/warmup # {"status":"ok","schema":"0013"} -``` - -A `"degraded"` here would mean the deploy had not arrived; before `0013` was applied, the -same request honestly called the database behind, because `EXPECTED_REVISION` was already -`0013`. The head is `0017` today — see the top of this file — and the same request reads it -the other way round while a revision waits for its merge: the database is *ahead* of the -code, and `/warmup` says so in as many words, «База впереди кода…». - -**The five dependabot pull requests can now be closed without regret** — their bumps arrived -in `main` together with `dev`. If it managed to recreate them before the merge, they will -turn empty by themselves. +## Sections 1 to 4, and the history -### How to continue - -`dev` remains the working branch, but after a merge it is restarted from `main`: a merged -pull request accepts no new commits. Which pull requests are merged and which one is open -is at the top of this file, not here — this paragraph is about the two commands under it. - -```bash -git fetch origin -git checkout -B dev origin/main # the same dev, a new starting point -``` - -The gates, both halves (`CLAUDE.md` requires running both if you touched both): - -```bash -cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 2024 tests, ~4 min on CI, ~10 on Windows -cd server && python -m mypy # clean, 100 modules -cd android && ./gradlew test # 1459 tests across the five modules -cd android && ./gradlew assembleDebug assembleRelease # both assembles -``` - ---- - -## 2. What has been done - -Bottom up. The details of each are in its commit body and in the description of PR #43; this -is only so that you do not have to go looking. - -| Commit | What it did | -| --- | --- | -| `b7c82d1` | The bottom fade starts where Essentials' does (130 dp) | -| `aacf886` | Three defects found by comparing against Essentials: `CrashReporter`, `AppLocale`, `derivedStateOf` | -| `478861e` | The timetable's horizon is a school year, not a month from Monday | -| `cf01b96` | A class by its number and letter; quarters and half-years; revision `0008` | -| `d2d8d23` | `CLAUDE.md`: migrations are applied through the Neon connector | -| `9b7b907` | The schools registry behind `providers/dadata/`, searchable in the bot and the app | -| `af20180` | A `401` on a class token drops the session and the cache | -| `fc9989f` | The subject dictionary and the timetable are one list | -| `92518c5` | Twelve defects from two audits of fresh code | -| `bd4ce41` | Week parity, the calendar's UIDs, the two alarm chains | -| `ef6e530` | One tick per digest; a shortened day with no bells is refused | -| `c35ebd3` | CI: `setup-android` pinned to `v4.0.1` + `packages: platform-tools` | -| `236b259` | Quoting in the timetable export; a lesson with no bell is not written | -| `e5cc939` | `pyproject.toml` level with `requirements.txt` after the pip bumps | -| `bfa1689` | What compose-bom 2026.09.00 did to the intercepting layer | -| `e55ea2f` | This file, on `dev` rather than on one working branch | -| `a1bbeb5` | This file, brought to the facts: six branches closed, one live pull request | -| `8ec2e31` | Several classes on one phone, and switching between them | -| `569bab8` | Six defects from the audit of `8ec2e31`; a `401` drops one class, not all | -| `ce02348` | Corrections over the diary, with an undo; revision `0009` | -| `c6ba66c` | Fifteen findings from two audits of `ce02348` | -| `59c7a77` | The class's join mode and the personal codes; revisions `0010` and `0011` | -| `98c8018` | The database brought up to `0011` | -| `70b9dcb` | The `429` on the code screen, in minutes rather than "HTTP 429 Too Many Requests" | -| `8aa4ecd` | Three of the app's screens are pressed in the build: Robolectric in `:app` | -| `bf74233` | «🗓 Четверти» crashed in production on every press; the rendering is covered | -| `a58d2be` | The "attribute that does not exist" check across the whole server; `rows_affected` | -| `33deca3` | The bot's cards drawn in tests; eight turned out to be broken | -| `a9be1c4` | Every row of a list is reachable by a button; the alert is cut at 200 | -| `6a1dded` | A forged press gets a refusal; the order of memberships is fixed | -| `f3839c8` | A day offset out of callback data does not overflow the date | -| `c2038e4` | An event's kind and a lesson's number are checked where they are picked | -| `1d84d89` | 422 instead of 500 on a far-away date; NULL into a NOT NULL refused | -| `ae8e3b8` | The countdown and the quarter localised; the translation guard across all modules | -| `8cba40b` | Seven findings in the providers, the config, the FSM and the database URL parsing | -| `94ea9b5` | Bells by number; a slot does not double; a quarter on the diary's clock | -| `4f5471d` | A summer with no lessons; the bell under a substitution and a paste; revisions `0012`/`0013` | -| `3a592c9` | The diary sign-in does not blame the password; `httpx` with an upper bound | -| `69bf4ba` | Two races closed with a conditional UPDATE and a savepoint | -| `ea3afc8` | The import counts dropped rows rather than their numbers | -| `24b4841` | The diary notices a changed response shape instead of answering with an empty week | -| `7712dc7` | The revision stamp after `init_db`; the `requirements.txt` mirror under test | -| `8bec2ff` | The selected class is not swept up along with the dialogues | -| `0c99993` | Revoked access takes the class's subscriptions with it | -| `8995fa6` | The role in the menu, the time of the first digest, the length of the homework digest | -| `38e8aec` | A day is not hung on a bell schedule with no rows | -| `bf2338d` | Signing into the diary with no key is a 503, not a 500 | -| `591b3a4` | «Выйти» from the diary leaves no second session | -| `7c99652` | Each notification has its own press target; the room in the widget | -| `cc3935e` | Deleting a lesson does not shift its neighbour onto a number with no bell | - -**There were thirteen audits on this branch.** Four of the early work (sixteen findings), -four of `8ec2e31` (six), two of `ce02348` (fifteen) and one of `59c7a77` (seven); three -covering Android, the bot and the documentation (`ab488ad`), and the last two, which drew the -bot's cards and found nine defects (`bf74233`, `33deca3`). The heaviest of the lot: week -parity was computed from the ISO week number, which does not alternate in a 53-week year — so -from January 2027 the whole denominator of the **current** school year slid by a week, -simultaneously in the API, the widget, the digests and the calendar. - -**Migrations:** the last revision written is `0017`, and production is at `0017`. -`0007`–`0012` were applied **before** their merge through the Neon connector, `0013` after it -(it adds a `UNIQUE`, and a constraint migrates in the opposite direction from a column), and -`0014` before it again. `0015`, `0016` and `0017`, all written on #140, went on before #140's -merge, in one transaction. `0017` rewrites a key, which on a database holding rows goes on -after the merge; production held none. «Schema» in that batch's section at the top of this -file has what the database said. What each earlier revision did is in `CLAUDE.md` and in section 7, -item 1. - ---- - -## 3. What has NOT been done - -### 3.1. The features that were requested — all of them are done - -**No requested work is left untaken.** The one item that was open here — scrolling the -calendar by years — was a decision rather than work, the owner made it on 21 September -2026 (the windowed sync, not the picker bound to the synced year), and it is done. The -section is kept struck through rather than deleted: it shows what exactly was asked for -and what it turned out to be. - -**One request has come in since, and it is on #140.** On 25 September the owner asked for a -way in through the family's own school's diary, with the password never reaching our server -(#141). It is built — the first run, the diary-only home, the legal line, the catalog and the -directory — and closes when #140 merges; what nobody has verified about it is in section 5. - -~~1. **A pupil choosing their own class.**~~ Done in `8ec2e31`. The phone keeps a list of - memberships, shows one of them and switches instantly; the cache is split by class, so - switching works with no network too. What exactly is unverified is in section 5. -~~2. **Corrections over dnevnik2's data, with a reset.**~~ Done in `ce02348`. Pressing a - lesson or an assignment opens a window where the fields can be rewritten; under each it - says what the diary actually holds. Nothing goes upstream, marks and the turnstile cannot - be corrected, and the bot does not show corrections (section 6). -~~3. **Two modes on invitation, and a reversible switch between them.**~~ The statement was - clarified with the owner: this is the **class's join mode**. Done — `join_mode` on a - class, `open` or `invite`; in `invite` the class code lets nobody in and a phone joins - with a personal one-time code from the bot. The switch is reversible and disconnects not - one already-connected phone. The details are in section 6, "Who lets a phone in". - -### 3.2. What does not exist at all (long-standing gaps, not regressions) - -The same as the "What does not exist at all" section of `README.md`: - -- Attachments to homework: the `attachment_url` field is in the schema, there is no upload. -- A link between a class and a registry record: only the school's name is stored, so a rename - in the company register passes the class unnoticed. -- The widget stays on the system font: Glance passes `fontFamily` as the name of a system - family rather than as a resource. - -And two that #140 left out on purpose, which are issues rather than lines in `README.md`'s -list: - -- A phone that reads only its diary gets nothing from it in the widget, «Сегодня», - «Календарь» or the alerts (#142). -- A diary session opened on the phone is invisible to the bot (#143). - -### 3.3. The typeface's licence — closed, and not the way this said - -**`google_sans_flex.ttf` is under SIL Open Font License 1.1**, Copyright 2015 Google LLC. The -typeface declares that itself, in its `name` table, records 13 and 14. This section and the -comment in `theme/Type.kt` said "MIT, from Essentials" and concluded that the typeface was -non-free and had to be removed before publication; neither held up once the file was finally -opened and read. - -`FontLicenceTest` in `:core:designsystem` holds this: it parses the `name` table of every -font in the tree and requires a notice under `assets/licenses/` with the same copyright and -the same licence, and that it be the text rather than a link. The link between the file and -the notice used to rest on nothing — move one and the build would stay green. - -There is nothing to remove. What was done is what the licence actually requires: the OFL text -is placed next to the font in `assets/licenses/` — so it travels inside the APK, as "a copy -of the licence accompanies a copy of the font" — the licence is named in the app on the -«Лицензии» sheet, and neither the comment nor `docs/design.md` asserts something untrue any -more. No Reserved Font Name is declared, the file is not modified, and the "Google Sans" -trademark stays a trademark: bundling is allowed, naming a product after it is not. - ---- - -## 4. Open defects: none that #140 does not fix, and one fix that waits for a phone - -**The defects open as this is written are the ones #140 fixes.** #136–#138 and #145–#160 are -all fixed on its branch and meant to close with its merge — the table is in that batch's -section at the top of this file. The exception is **#156**: crash reports are now excluded -from every backup path in the rule files and a test reads both, but whether a phone's backup -really leaves them out takes a phone and `bmgr`, so the issue stays open, `needs:device`. -Everything below is the record from before the tracker, and it still holds. - -All sixteen findings of the first four audits are closed, as are all six findings of the four -audits of `8ec2e31` (`569bab8`), the fifteen of `ce02348` (`c6ba66c`), the seven of `59c7a77` -and every finding of the last three audits — Android, the bot and the documentation. And five -of the six defects `docs/design.md` carried under "known and not yet fixed". The sixth — the -screenshot on the main thread — turned out not to be a defect but a platform limitation -(`View.draw` is obliged to run on the UI thread) and was rewritten into "Limitations". - -**Do not file these again as bugs.** If a new session's audit names something from the list -below again, check the code first for whether it is already closed: - -- week parity from the ISO number → now counted from the start of the school year; -- positional UIDs in the calendar → now a row's identifier; -- `setWindow` in the widget's alarms → now `setAndAllowWhileIdle`; -- `SchoolAlerts.fire` with unprotected publishing → every publication in a `runCatching`; -- `mark_sent` after the selection → now `claim`, a conditional `UPDATE`; -- `MAX_INDEX = 20` as a day's ceiling → now a ceiling from the class's bell count; -- the timetable export without escaping commas → quoting, plus the last field taking the - remainder; -- `LARGE` hid the homework → the `LARGE_TALL` threshold lowered from 400 to 300 dp; -- `OverlayLayerTest` "failing" on the intercepting layer → **not a defect**: the test was - rewritten for compose-bom 2026.09.00, which changed Compose's behaviour. It was red exactly - once, at the merge; see section 6. - -The six multi-class findings closed in `569bab8` — do not file those again either: - -- `onTokenRejected` called `signOut` → now `leaveActive`, and a `401` on one class drops only - that one; -- the membership list was decoded as a whole → now per entry, so one broken row does not take - the rest with it; -- `syncNow` with `KEEP` swallowed the sync after a switch → the switch now uses - `APPEND_OR_REPLACE`; -- leaving a class that was **not** on screen cleared the timetable fingerprint → now only - when the active class actually changed; -- a notification from the previous class stayed in the shade → switching removes it; -- an in-flight sync resurrected rows of a class that had been left → `retainOnly` sweeps them - at the start of every sync. - -The findings of the last three audits are closed too, and these are the ones easiest to find -a second time: - -- an enum's `server_default` written through `.value` → now `.name`; the column holds `OPEN`, - and three tests check it (section 6); -- `burn` assigned an attribute → now a conditional `UPDATE`, and `/join` burns the code - before it issues a token; -- the mode button was a toggle → it now carries the mode it wants; -- joining with a personal code was not written to the log → `device.link` is now written in - `/join`; -- revoking a member did not kill their unissued codes → now `drop_for`; -- `session.refresh` after a swallowed rollback stood outside the `try` and could replace a - `401` with `X-Diary-Reauth` → now `_refresh_quietly`, and the same in `api/deps.py`; -- `mint` deleted spent codes along with live ones → now live ones only; -- `_is_iso_date` accepted `20260915` and `2026-W38-1` → now `YYYY-MM-DD` only; -- the `429` on the code screen was drawn as "HTTP 429 Too Many Requests" → now a Russian - sentence with the number of minutes from `Retry-After`; -- `join_error_generic` became unreachable and an English sentence went out in its place → - `JoinError.of` reads the classified refusal rather than the raw one; -- a row with no `target` was pressable and led to a `422` → now `correctable`; -- the correction window could stay over the sign-in form → `applyFailure` closes it together - with any request for a password; -- four comments asserted things the code does not do → rewritten to the facts. - -And nine came not from an audit but from the bot's cards finally being **drawn in a test**. -The first came from production: the owner pressed «🗓 Четверти» and got an error dialog. - -- `_terms_card` printed `term.days`, and `Term` has no such attribute: `days` belonged to - `TermView` — "a flattened copy of a term for a renderer with no session" — which **no code - path ever created**. The line was written against a type that never reaches it, and the - only way to find out was to press the button. `days` moved onto the model, the dead twin - was deleted, and the rendering is covered by tests. - -The other eight are from `33deca3`, and two of them took the whole screen: - -- **the diary escaped nothing** that the external service sent: the subject, the room, the - teacher, the topic, the assignment's text. Telegram refuses **the whole message** on one - angle bracket, so «реши § 4 при a<b» left a parent with no timetable at all; -- **the editor did not escape a subject's name**, while the paste grammar accepts «Алгебра - <7>» whole — one bracket, and the editor does not draw the day it is editing; -- a slot's card showed its own tags to a viewer: `answerCallbackQuery` has no parse mode → - `editor_render.as_alert`; -- `plural` prints the number itself, and three places printed it again («перемена · 10 10 - минут»). One of the three **had a test**, and it passed: «10 минут» is a substring of - «10 10 минут»; -- the import preview put the line about the bells under its own footer, so a paste of nothing - but bells read as "not one day recognised" above a button that was about to replace those - bells; -- the import's result counted what was parsed rather than what was written, and contradicted - itself on adjacent lines; -- `render_bells` silently lost the tail of the list past `LIST_MAX`; -- `_next_day_line` indexed an empty list; -- three list pages out of four drew more rows than there were buttons beneath them: forty - subjects over thirty ✏️, twenty bell schedules over ten, twenty phones over fifteen. The - tail was visible, unreachable and unexplained; «Особые дни» agreed with itself by accident — - both sides said 20. Each page now has one number for both - (`manage_render.SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX`, `LIST_MAX`), and - `test_no_list_page_draws_a_row_the_keyboard_cannot_reach` checks it: it asks the keyboard, - by row id, which of the drawn rows it carries; -- the alert from a lesson's card measured 284 characters on a doubled lesson — - `answerCallbackQuery` returns 400 past 200, that is, an endless spinner; -- `diary_render.student_line` was called by nobody: a dead renderer of the same shape as the - one that crashed «🗓 Четверти». Deleted. - -**The second pass over defects** (four agents over non-overlapping areas plus a slice of my -own; every finding has a test that fails with a real error if the fix is removed): - -- **two role-picking screens caught one press.** The invite-by-number handler stood on - `RolePick.filter()` — on *any* role press while its state was live. An admin who had - started "invite by number" and then pressed a role on an older «Новая роль» card created a - **phone invitation** and got a success message about a number rather than about a person; -- three bare conversions from callback data in `access.py` (`int(target)`, `int(value)`, - `Role(role)`) — the one file of the bot the check that closed this in `manage.py` never - reached. A bare `int()` does not refuse a press, it **escapes the handler**: - `callback.answer()` is never called and the button spins until Telegram gives up; -- `timedelta(days=…)` from callback data in three paging screens (day, week, diary) — an - `OverflowError` rather than a far-away day; -- an event's kind and a lesson's number in `content.py` were stored raw and turned into an - `EventKind` / an `int` three questions later — exactly what the comment a line above in the - same file warns about; -- the order of memberships was undefined while three places read it as meaningful, including - **the order of the «🔀 Сменить класс» buttons**; -- `GET /homework?from=9999-12-31` answered 500 (the window arithmetic ran before the bounds - check); the same in the diary's `_range`; `PATCH /tasks` with `{"title": null}` put NULL - into a NOT NULL column; -- the diary lost **a lesson's time** when the upstream answers in ISO, and **a whole child** - when the first `educations` entry is unreadable; a failed sign-in was reported to the phone - as "the session expired", so the person retyped their password endlessly; -- «МБОУ "СОШ № 197"» was drawn as «МБОУ "Сош № 197"»; a typo in `TIMEZONE` crashed `/start`; - `state.clear()` wrote an empty string to the database (113 such places in the bot); - `describe()` leaked the tail of a password containing an `@`; -- on the phone: the countdown — the largest digits on the home screen — was Russian under an - English caption, the calendar's heading read «October 2026 · 1 четверть», and a `401` in - the diary **crashed the app** if the write to disk failed. -- **the lesson ceiling was counted from the number of bells rather than from their numbers.** - The paste grammar allows a gap, and a class with bells at 1, 2, 4 got both errors at once: - «4. Химия» was rejected with the words "there is no such bell" — about a bell from the same - paste — while the editor would have written a third lesson the class does not ring; -- **a timetable slot could get a second row shadowing the first.** `uq_timetable_cell` does - not forbid "every week" and "numerator" on one lesson, both pass the parity filter, and - `_load` selects with no `ORDER BY` — the database decided what the phone would draw, and - the answer could differ between two reads; -- **a task's reminder was claimed by an attribute rather than by the database.** The digests - obey the rule in the module's docstring, the tasks did not, and two overlapping ticks sent - «⏰ Напоминание» twice; -- the diary's "current quarter" was read on the server's clock rather than the diary's: on - the evening of a quarter's first day the subjects screen arrived empty. - -**Not a finding but an honest caveat.** The order of memberships has no test that fails -before the fix: the tests run on SQLite, which returns insertion order both with and without -an `ORDER BY`. The test left there is a guard, not a reproduction. - -**The third pass — what the owner named, item by item** (`4f5471d`, `3a592c9`): - -- **the template expanded in June, July and August.** `SCHOOL_YEAR_END_MONTH` is 5 and the - comment beside it says the template must not repeat from June — and `_resolve_day` never - read that constant. A summer weekday arrived full on the phone, in the widget, in the - calendar feed and in the morning digest, whose **own** rule about staying silent on an - empty day could never fire: the day was not empty; -- **a substitution could be written onto a number with no bell** — it went into the log and - into a «🔁 Замена … урок №8» notification, and was drawn by nobody. The check is now in both - shells and **against that day's bells** (`rung_indexes_on`), because a shortened day rings - shorter than an ordinary one; -- **the bot's single-day paste went round `apply_timetable`** — the one entrance into the - template without all of its checking. Eight lessons into a class that rings seven gave - "lessons saved — 8" and a list of eight; -- **two people saving one assignment at the same time got two.** Both shells promised "one - assignment per subject per day" in their own docstrings; it is now one - `services/homework.py`; -- **the diary sign-in page blamed the password for any of somebody else's errors** — a person - retyped a correct password until they gave up; -- `httpx` had no upper bound while depending on a deprecated capability; the turnstile read - an unrecognised direction as "exit"; a token made of spaces looked like an exhausted quota; - `current_revision` left the Postgres transaction aborted. - -- **two read-then-write races.** `diary_link.claim` read the ticket, checked it in Python and - then assigned `used_at`: two simultaneous sign-ins got two diary sessions for one account. - And `GET /api/v1/bundle` seeds the terms for a new class — while every phone in the class - polls it on one timer, so "both found the year unseeded" is the ordinary case, and on - Postgres the second got an `IntegrityError`, that is, **a 500 on a read**; -- `GET /api/v1/manage/subjects` linked lessons to the dictionary and **committed only if it - had created something**: for a class with a full dictionary and unlinked lessons the - UPDATEs ran and were thrown away on every read. It was only cured by `/bundle` committing - unconditionally. - -**Where I disagreed with an agent.** It proposed handing the sign-in ticket back on an -"incomprehensible answer" from the diary too. We cannot tell a captcha from a wrong password: -a Yii form answers a wrong password with the same "200 with some HTML". Handing the ticket -back on such an answer would make the link an unlimited oracle for guessing a password from -our address — precisely what spending the ticket in advance is for. The hand-back is narrowed -to "the diary did not answer at all"; the message stopped blaming the password in both cases, -and that was the defect. - -**The three the first real build found** (#79) are closed too, and are worth knowing about -because none of them is the kind an audit finds by reading: a `LazyColumn` key that was -never interpolated, a fixed-height fade inside a view whose height is whatever is left, and -`cameraDistance` multiplied by the density. All three are measurements. All three passed -every test that asked whether the screen was *built*, and all three fail the one that asks -whether its rows are **displayed**. If an agent proposes any of them again, check -`DayRibbonView.kt` first. - -**And the six from the build after it** (#80), which are the same family one step wider — -every one is a layout or a default that nothing in the code reads as wrong: - -- a marquee left on `MarqueeDefaults.Iterations`, so a title stops scrolling after three - passes and sits clipped — per composition, so two rows of one list disagree; -- a screen title sharing a `Row` with four controls under `weight(1f)`, which is the - correct way to share a row and the wrong amount of room; -- a button that appears and disappears without its slot being kept, so everything beside it - moves 48 dp between two presses; -- a container radius picked as a token rather than derived from what is inside it; -- an item that pads itself inside a list that already pads every item; -- `retention-days:` asking for more than the repository allows, which is silently reduced. - -The last one is not an Android defect and is listed with them on purpose: it is the same -shape. **A number written next to the thing that overrides it is a wish, not a setting**, -and three documents had been quoting the wish for months. - -**And one from #81, which is the family's sharpest member**: a test that asserted how its -own build was configured. `AboutCardTest` read `BuildProvenance.current()` and asserted the -badge that a build told nothing about itself draws — so it passed under `ci.yml`, which -sets no build properties, and failed under `apk.yml`, which sets them all. Green on every -pull request; red only in the workflow whose job is to produce an APK. **A test that reads -a global is a test of the environment**, and the environment a test runs in is not the one -the code ships in. - ---- +Sections 1 to 4 — the state as of PR #51, what had been done by then, what had not, and the +defects closed before the tracker existed — are in [docs/history.md](docs/history.md) now, +after the oldest batch. Section 4 is worth reading before an audit files anything: it lists +defects already closed, each with what closed it. The four sections below kept their +numbers, because the documents, the skills and the history refer to them by number. ## 5. What nobody has verified @@ -3644,12 +444,6 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i batch: a drag of ten thousand pixels parks at the end under any density, which is what `ToolbarDragTest` does and what caught it. Anything *between* two slots is still not asked of a composition, and `ToolbarReorderTest` asks it in pixels instead. -- **There was a window of a frame or two after the drag, and it was written here as - inherent. It was not (#180):** between the drag ending and the preferences answering, the - pager's index still names the old order, and the bar read its selection from that index — - so the selected circle hopped for a frame. It reads the tab being kept on now. The - other one — a frame of the pre-drag order at the moment the mode closes — was written down - here as deliberate and is closed by #85. - **Nothing of the year scrolling has been looked at either.** What the tests prove is which year is asked for and when, which one is dropped, and that a request made while another was in flight comes back. What nobody has seen: the year chip, the picker, how @@ -3713,13 +507,6 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i system font now fits the rung it lands on, whether the chips read as seven days, and whether the subject keeps its width beside a long teacher's name. Below API 31 the corner half of this does not arise at all — `cornerRadius` is a no-op there. -- **`/api/v1/warmup` was read on 26 September 2026** through the Vercel connector, which - carries the owner's access — `"schema":"0017"`; see the opening. What follows was true - until then. The deployments are behind Vercel's Deployment - Protection and answer a redirect to a login page, so no `curl` from here can settle - whether the schema — `0017` once #140 has deployed — and the code that needs it - met. It needs the owner's browser or a bypass - token; it has been outstanding since #61 and it is in section 7 for that reason. - **`docker compose up` has never been run.** There is no Docker in this environment, so what #83 proves about the new `migrate` service is that the compose file parses and that its dependency conditions are what they claim — `service_completed_successfully` before @@ -3866,6 +653,15 @@ invisible from anywhere except a real screen. Beyond what is already in `CLAUDE.md`. +Fourteen subsections that stood here until 27 September 2026 are in +[docs/history.md](docs/history.md), «Moved out of section 6». Eleven retold, in older words, +rules `CLAUDE.md` carries — escaping what comes from outside, callback data, two screens on +one press, the translation guard, the order a constraint migrates in, the end of the school +year, a lesson and its bell (twice), a list and its keyboard, `mypy`, a renderer and its +type; one described `.claude/`, which `.claude/README.md` describes; and two narrated batches +that are done — the move into English and the documents' sweep of 19 September. What those +two left alone on purpose is kept below, under «Two things left in Russian on purpose». + ### CI and building the APK `android-actions/setup-android` is **pinned to `v4.0.1`** and is given @@ -3875,14 +671,6 @@ returns a non-zero code for it. Without the pin, every Android run fails before starts. **Do not remove the pin and do not drop `packages` without checking that the action has stopped asking for `tools`.** -The APK's "Run workflow" takes `main` by default, and after the merge that is finally the -right branch. The last build sitting in the artifacts — -[run 34948610365](https://github.com/lumenpearson/lessons/actions/runs/34948610365), the -`lessons-apk` artifact — was made from the former working branch, that is, **without** AGP -9.4.0, Gradle 9.7.1, the new compose-bom and everything described in this file. Build it -again: that combination has gone through on the runner many times, but nobody has held an -APK with it in their hands. - ### The cache is split by class `school_day` carries a `class_id`, and **every read in `TimetableDao` requires it as a @@ -4044,64 +832,6 @@ live during the first run, and where they never do. These are the parts that bre those files; a test that starts reading a document outside its half adds the document there (#159). -### Everything that came from outside is escaped before it is sent - -The bot sends HTML, and on one angle bracket Telegram refuses **the whole message** rather -than spoiling a line. So an unescaped string does not produce a broken layout, it produces -**a blank screen and not one error anybody will see**. - -What comes from outside is: everything from the Petersburg diary (subject, room, teacher, -topic, homework), everything typed into the bot and pasted into the paste grammar (a subject -really can be called «Алгебра <7>»), and everything from the schools registry. `render.py` -always did this; `diary_render.py` and `editor_render.py` never did, and both shipped that -way. - -Two traps of the same kind next door. `plural(n, …)` **already contains the number**, so -`f"{n} {plural(n, …)}"` prints «10 10 минут» — it was in three places, and one had a test -that passed because «10 минут» is a substring. And `answerCallbackQuery` has **no parse -mode**: a card assembled for a message shows its own tags in an alert, which is what -`editor_render.as_alert` is for — it also cuts at 200 characters, because past that Telegram -answers 400 and the press answers with nothing at all. - -### Callback data is whatever the client sent, and this is not caution for its own sake - -A client is free to send any string as callback data. The difference between `int(x)` and -"check and refuse" is not tidiness: a bare `int()` **escapes the handler**, which means -`callback.answer()` is never called and the button spins until Telegram gives up. `manage.py` -and `tasks.py` have `_int_or_none` for this, `calendar.py` and `content.py` have -`_date_or_none`, `access.py` now has `_int_or_none` and `_role_or_none`, and `content.py` also -has `_kind_or_none` and `_index_or_none`. The rule is one: **check where the value is -picked**, not where it is finally read — otherwise it travels through three questions and -fails in front of somebody who has already typed a time and a title. - -The same goes for arithmetic: `shift_days` / `shift_weeks` in `keyboards.py` build the date -and let `date` say whether it is one. `timedelta(days=999999999)` is an `OverflowError`, not -a far-away day. - -### Two screens can catch one press - -Both flows send a `RolePick` — inviting by number and changing a member's role — and the only -thing that tells them apart is that the first leaves `target` empty. While the invite's -filter was simply `RolePick.filter()`, it took both, because it stood higher in the file. If -you add a second screen on an existing payload, **separate the filters by a field** rather -than by registration order; `test_the_two_role_pickers_never_match_the_same_press` holds -this. - -### The translation is guarded in every module that ships strings - -`ResourceTranslationTest` used to read `:app` and nothing else, while there are strings in -`:core:data`, `:core:designsystem` and `:widget` too — including the countdown on the home -screen. It now finds every module with a `values/strings.xml` by itself, names the module in -every error, and a separate test holds the list itself, so that the walk cannot narrow -silently. A `<plurals>`' arguments are counted **per form**: Russian has four and English -two, and over the concatenation they can never agree (it never showed in `:app`, because -everything there is `%1$d` rather than `%d`). - -Russian text hard-coded into Kotlin is not caught by this at all — those words are in neither -folder. Check it this way: `grep -rnP '"[^"]*[\x{0400}-\x{04FF}]'` over `src/main`. Today -what is left is only `@Preview`, the maintainer-facing report bodies, and the timezone list, -where that decision is recorded in the file itself. - ### The correction mode knows about all the text, and two imports hold it The mode's coverage is not a list of places wrapped by hand. `:app` and `:core:designsystem` @@ -4176,28 +906,6 @@ does not confuse `settings_title` with `settings_titles_plural` or with a `<stri the same name. Everything past that — fork, branch, commit, pull request — is written and has never run. -### A constraint migrates in the opposite direction from a column - -The rule "migration before the merge" is about code that knows a column the database does -not. For this chain it is right everywhere but one case: **a `UNIQUE` and a `NOT NULL` break -the old code, not the new.** Before `services/homework.py` reaches `main`, the losing side of -a race does an ordinary INSERT and gets an `IntegrityError` nobody catches — that is, a 500 -where today there is a duplicate. So `0013` is applied **after** the merge, and that is -written in the revision itself; `services/homework.py` is deliberately correct without the -constraint too, so that the window between the merge and the application behaves as things do -today. - -`0012` is the safe shape (eight timestamps that already hold no NULLs) and was applied the -usual way, before the merge. **The database was read before both**, and that paid off: unlike -`0011`, `0012` turned out not to be a no-op — all eight columns in production really were -nullable. - -**The database's state right now:** Neon's head is `0013`, and it agrees with -`EXPECTED_REVISION`. The revision was applied as one transaction through the connector right -after PR #45 was merged, with the stamp last inside it; `homework` was empty, so its -deduplication deleted no rows, and `uq_homework_per_subject_per_day` now stands as exactly -what the model builds. - ### Idempotent is not the same as safe under a race `/api/v1/bundle` is a read, and it writes: it seeds the terms and the subject dictionary for @@ -4220,39 +928,6 @@ dictionary entries were *created*, but it also links the timetable's rows. `GET /api/v1/manage/subjects` committed `if ...:` — and for a class with a full dictionary and unlinked lessons the work was done and thrown away on every read. -### The school year ends, and the template with it - -`SCHOOL_YEAR_END_MONTH` is 5, and the comment beside it explains why the template must not -repeat from June: it "would show lessons nobody is going to". Only `school_year_bounds` read -that constant. `_resolve_day` now asks it too. A day marked by hand keeps its kind and its -note; events and homework are kept either way — it is the lessons that are out of season, not -the day. - -The rule is about a **date** rather than about the quarters. A school that really does teach -in June enters those days as events. - -### A lesson's ceiling is a set of numbers, not a count of them - -The resolver takes a lesson's time from the bell row **with the same number** (`schedule.py`, -`period = bells.get(entry.index)`). So the question "may lesson 4 be written" is "is there a -bell 4", not "how many bells are there in total". The paste grammar allows a gap -(`parse_bells_block` refuses only on `index < 1` and on duplicates), so for a class with bells -at 1, 2, 4 a count is wrong in both directions at once. `timetable_edit.rung_indexes` answers -the right question, `can_ring` asks it, and `rings` stayed a counter because it is printed as -"there are N lessons in the bell schedule". - -Every entrance is closed: a substitution (`api/edit.py`, `bot/handlers/content.py`) and the -single-day paste check the bell, the day paste goes through `apply_timetable`, deleting a -lesson closes the gap in the numbering **only** if every lesson it moves lands on a number -that rings (otherwise a class with bells at 1, 2, 4 lost its fourth lesson by shifting it -onto the third), and a «⏱ Сокращённый день» cannot be hung on a bell schedule with no rows — -neither from the API nor from the bot: such a day draws nothing at all. - -**And count rows, not numbers.** `apply_timetable` returns a `TimetableImport` with (day, -number) pairs: «⚠️ Не добавлены уроки № …» names a number once — that is one thing to fix — -while "N skipped, no bell" and `rejected` in the API count the rows that were dropped, -because one number under two days (or under «чёт»/«нечёт» in one day) is two lessons. - ### A slot is one "every week" row or two halves `uq_timetable_cell` is `(class, day, number, parity)`, and "every week" next to "numerator" @@ -4263,54 +938,6 @@ hold the rule, and all three are needed: `timetable_io._conflicts` on a paste, t handler, and — as of this commit — `timetable_edit.edit_lesson`, that is, the one entrance of the second shell. -### A list's length and its keyboard's length are one number, not two - -`manage_render` declares `SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX` and `LIST_MAX` (special -days), and `manage_keyboards` builds its rows **from those same ones**. While there were two -numbers, three pages of four drew rows nothing could reach, and «… и ещё N» said nothing about -them, because it counted from its own number. Do not "bring them to one value for tidiness": -the numbers differ on purpose — a bell schedule's row carries three buttons and twelve lines -of times, a subject's one of each. The rule is one: what is drawn is what can be pressed, and -`test_no_list_page_draws_a_row_the_keyboard_cannot_reach` holds it. - -The pages **do not paginate** — none of them. Past the cap a row is only a number in -«… и ещё N»; for a class with forty subjects the last ten are unreachable from the bot -entirely. Raising the caps is a wall of buttons; the real fix is pagination, and nobody has -written it. - -### `python -m mypy` answers one question, and that is enough - -Not "type everything" but "does the code reach for an attribute the type does not have". That -is exactly what crashed «🗓 Четверти», and the check reproduces it word for word if the -property is put back. It is configured in `pyproject.toml`, where **every other code is -switched off by name, with a count and a reason** — a check whose output cannot be read is a -check nobody runs. - -It is currently clean across all 78 modules. The one thing that stood between the project and -cleanliness was `Result.rowcount`: `AsyncSession.execute` is typed as returning a -`Result[Any]`, which has no such field, while DML returns a `CursorResult`, which does. -Eleven places wrote `result.rowcount or 0` and meant one thing; that is now -`db.rows_affected`, and the cast lives in one place. - -**It is not in CI.** `CLAUDE.md` asks that the workflows not be edited casually, and adding a -job is the owner's decision, which nobody asked for. Run it by hand before pushing server -code. - -### A renderer is written against the type it will be handed - -«🗓 Четверти» crashed in production on every press, because the card read `term.days`, while -`days` belonged to `TermView` — a dataclass nobody ever constructed. Two types for one entity -is a way to write a renderer against the one that never reaches it; there is no compiler -here, and an `AttributeError` is visible only from the button. - -The moral is not "add type hints" but something more specific: **if a model's "flattened copy -for the renderer" sits beside it, check that somebody creates it.** And remember where the -tests' boundary runs: `tests/test_terms.py` opens with the words "the rules, not the -rendering", and that is an honest split right up to the day nobody checks the rendering. -The terms card is now drawn by a test (`test_the_terms_card_draws`), and it asserts the -numbers rather than only that the call returned: a card with «0 дн.» is as wrong as one that -crashed. - ### The intercepting layer and the compose-bom For two releases `OverlayLayerTest` asserted that a layer swallowing gestures to keep a touch @@ -4351,13 +978,6 @@ the dictionary fills itself from the timetable, so a deleted name came back on t read with no colour and no teacher. The order is: take the lessons out of the timetable first, then the subject out of the dictionary. -### The ceiling on lessons in a day - -Not `MAX_INDEX` but the class's bell count. A lesson with a number that has no row in the -bell schedule cannot be placed by the resolver and used to be dropped silently. On import the -ceiling is computed from what the class will ring **after** the import — a paste with its own -`== Звонки ==` block legitimately brings a ninth bell and a ninth lesson in one message. - ### The timetable paste grammar The last field takes the rest of the line, so a teacher «Иванов И.И., к.п.н.» is written with @@ -4365,76 +985,8 @@ no syntax. A subject or a room containing a comma is wrapped in double quotes, a inside is one literal quote. Quotes are used only where they are needed, so any line already written parses as it did before. ---- - -### The agent configuration lives in `.claude/` +### Two things left in Russian on purpose -There was none at all — no settings, no agents, no skills. There is now, and it is arranged -so as not to retell `CLAUDE.md` but to describe the shape: who owns what, which checks are -real, and which commands are never run from a session. - -``` -.claude/settings.json permissions, two hooks, the marketplace this project knows about -.claude/agents/ eighteen agents by area -.claude/skills/ nine procedures -.claude/commands/ /where-are-we and /pre-push -.claude/hooks/ the one hook too long to live inline -.claude/README.md what is here and what is deliberately absent -AGENTS.md a pointer for agents that read something other than `CLAUDE.md` -.github/copilot-instructions.md a short file: it is read on every request -``` - -Eighteen agents rather than a hundred, because each file exists for a trap that has already -sprung in that area, and carries the fact that would have prevented it. An agent that retells -`CLAUDE.md` would not survive the same review that lets no comment through that retells the -line below it, and a stub agent is worse than no agent: it answers confidently from nothing. -The nine-way split in `skills/audit/SKILL.md` is the one that found thirty-one findings in a -pass; the other nine are areas that have since grown traps of their own. - -Three things in `settings.json` worth knowing: - -* **`deny` compares the start of the command string.** `DATABASE_URL=… .venv/bin/alembic - upgrade head` walks past the `alembic upgrade *` rule. Those are guard rails, not a fence; - the reason not to run it by hand is in `skills/migration/SKILL.md`. -* **There are two hooks and both only print.** On a write to any module's - `values/strings*.xml`, the first mentions the twin in `values-en/`. The second, - `hooks/handover-behind.sh`, runs on `Stop` and speaks only when a merge commit on `HEAD` - **neither carried the close-out nor predates it** — a state that exists only after a pull - request has merged and `dev` has been fast-forwarded onto it, which is exactly when the - close-out is the work that is left. The first half of that condition is the correction: - a close-out written inside its own pull request, which is what the rule asks for while - that pull request is open, is landed *by* the merge and is therefore always older than - it. Comparing timestamps alone called that missing, and did so the first time the rule - was followed properly — on #67. A committed hook runs on the machine of everybody - who cloned the repository, which is why both are this small and why neither can fail: - each exits quietly on anything unexpected. -* **`extraKnownMarketplaces` registers `anthropics/skills`**, but no plugin is enabled: - enabling one is a decision for everybody who clones the repository, not for the session - that added the file. - -**There is deliberately no `.mcp.json`.** The Neon and Vercel connections need credentials, -and secrets do not enter this repository. The Neon project is the one **named `lessons`** -(the account has two), and that is all that can safely be written down. - -### Everything written about the project is English - -The product speaks Russian; everything written *about* the project is English. User-facing -strings stay where they were — `values/` is Russian and is the source, `values-en/` is the -translation, and the reader picks the language in the app — and every string the bot sends is -untouched. What moved: `README.md`, all of `docs/`, this file, the community documents, the -issue and pull request templates, and every comment and docstring under `server/` and -`android/`. - -Where any of those quotes a button, a menu path or an error the reader will see, it quotes it -in Russian, in guillemets, because that is what is on the screen. «🔔 Звонки» is a quotation, -not prose. - -Two things about the edges of that rule: - -* **The pull requests were rewritten on GitHub**, titles, descriptions and the eight - Russian comments under #16, #22, #34, #35 and #47. Those are GitHub objects, not repository - content: nothing in git moved, and no hash changed. The bots' comments are not ours and were - left alone. * **The commit history keeps its Russian, by decision.** Of 242 commits, 41 carry Russian prose outside quoted product strings — about 2,055 characters, mostly in merge-commit bodies. Rewriting them means rewriting every hash from the first affected commit and force @@ -4442,41 +994,6 @@ Two things about the edges of that rule: requests stop resolving, and the release tags move. The owner decided not to. So a `git log` older than this batch reads in two languages, and that is expected rather than missed. -The rule itself is written into `CLAUDE.md`, `AGENTS.md`, `.github/copilot-instructions.md` -and the `.claude/` agents and skills that touch strings or releases. Two of them had been -missed and told the next session to write **this file** in Russian — the `handover` skill -and the `handover-keeper` agent. Both now say English, and quote the README's "Written, -never run" instead of its Russian ancestor. - -### What the documents claimed, and what was actually true - -A number is the part of a document that rots first, so every one of them was re-measured on -19 September 2026 rather than copied forward: - -| Measured | Now | -| --- | --- | -| server tests | 1391, over 38 files | -| Android tests | 605, over 73 classes — `:core:model` 89, `:core:data` 186, `:core:designsystem` 45, `:widget` 45, `:app` 240 | -| modules under `mypy` | 79 | -| commits | 258 | -| schema head | `0013` | - -What was wrong and is now right: - -* `CLAUDE.md` said 1362 tests and 178 commits. -* `docs/architecture.md` gave `schedule.py` fifteen tests (it has twenty-two) and - `:core:model` fourteen (it has eighty-nine), listed eleven of the thirty-eight server - suites as though that were all of them, and ended with "the Android UI and the Glance - widget have no automated coverage yet" — which stopped being true when three screens went - under Robolectric and the size ladder got a test that walks real sizes. -* `CONTRIBUTING.md` said the same thing about screens and the widget. -* `docs/build.md` quoted 1340 tests without saying that was the count at the time of that - measurement, so it read as the current one. - -Everything else was checked and left alone: `README.md`'s "Honest status", `docs/README.md`, -the `0013` head wherever it is named, the twelve rungs, and the eight documents plus an -index. The sweep changed no code and ran no gate — there was nothing to run. - **One thing it found and did not touch.** Five test functions on the server carry a Russian word in their names — `test_a_day_with_one_maximum_length_задание_still_sends` and four like it, in `test_bot_message_limits.py` and `test_bot_manage.py`. The rule says identifiers are @@ -4619,53 +1136,18 @@ turn Preview deployments off in the project's Git settings; nothing here is a we there is nothing for a preview to show. Only the owner can do either — this session can read which keys exist per environment but must not create them. -**Open `/api/v1/warmup` in a browser — it is the one thing that settles whether the schema -and the code that needs it actually met**, and it is outstanding since #61. It cannot be -closed from a session here at any effort: the deployments are behind Vercel's Deployment -Protection and answer a redirect to a login page, so this needs the owner's own browser or a -bypass token. The answer wanted once #140 has merged and deployed is -`{"status":"ok","api_version":1,"schema":"0017"}`; a -`"degraded"` naming two revisions is the honest report of a migration and a deploy that have -not met, and which way round it is, is in the `detail`. - **The APK's own badges are new in #80 and they are worth one press.** The about page now names the server's state, the repository, the ref and the commit the build came from. Two of those cannot be checked from here at all: whether the server badge says the right thing about the real deployment, and whether the commit chip opens the right diff on a phone. Both are a few seconds on the page that already exists. -**One of these stopped being theoretical in #79, and it is the most useful thing that has -happened to this project.** The owner installed an APK, used it, and sent back both the -symptom and the full Android bugreport. That found three defects in a screen with three -passing test suites over it, and settled in one line a question the branch could only -speculate about — whether the crash on rotation was a fourth defect. It was not. -**Every batch that changes a screen is worth an APK and five minutes of the owner's -thumb**, and the bugreport is worth more than the description, because the description -cannot contain `not-handles={}`. - -**The calendar year-scroll was a decision and it has been made.** The owner chose (b), the -windowed sync, on 21 September 2026, over (a), a picker bound to the year already synced — -which would have scrolled to a year with no days in it. It is done, in #78. What is left of -it for the owner is one number: the cache keeps three school years per class, which is a -guess rather than a measurement, and nobody has watched what four costs on a real phone. - **The hour ruler is gone.** «Календарь → День» is the ribbon now, and a reader who preferred reading the day by position — a gap as a height rather than as a row — has lost that. It was a deliberate replacement rather than an addition, because two views of one day is how the bot's two timetable editors nearly drifted apart; if it turns out to be missed, the ruler is in the history at `f5a8172^`. -**The milestones were the newest of these, and that one is done.** Milestones 1 to 6 and 8 -cover versions that are finished, and the owner has closed all seven. Three stay open on -purpose: number 9, `v0.8.0 — On-device checks, 89-region e-diary survey`, whose device work -is still to do; number 10, `v0.9.0 — NetSchool e-diary, onboarding via the school's -diary`, which #140 is on; and number 7, `Dependencies — dependabot bumps`, which takes every -future bump. The ten titles, and what each was called before the owner renamed them on -25 September, are in the table under «And before that: nothing on a screen is cut off». The -reason a new one has to be asked for stands for next time: no tool in a session here changes -a milestone's state or creates one — `issue_write` only assigns an existing one by number — -and there is no `gh` CLI. - **The first press of two network paths should be the owner's.** Neither the translation pull request from #64 nor the guide's fetch from #67 has ever run against GitHub, and both are written to be pressed by a reader. Opening the documentation once on a real phone, with @@ -4708,22 +1190,11 @@ cheaper one that cannot misfire is an age check on `last_used_at` in `find_sessi clock over our own facts. **Today there is no bound at all except the row's own lifecycle**, and that is the thing to decide rather than the ttl. -~~1. **Decide the fate of PR #43.**~~ Merged. The order was kept: `0010` (the join mode and - the personal-codes table) and `0011` (two timestamps in `diary_overrides` brought to `NOT - NULL`) were applied through the Neon connector **before** the merge. Neither destroyed - anything: `0010` added a column with a default preserving the current behaviour, plus an - empty table; `0011` changed nothing at all on this database — the columns were already - `NOT NULL`, because the DDL for `0009` came from the model rather than from the revision's - text. Verified afterwards: head `0011`, the single class reads `OPEN`, `device_invites` - matches the model column for column, three indexes. -~~1a. **Apply `0013` after PR #45 is merged.**~~ Applied: head `0013`, the constraint in - place, zero rows deleted (`homework` had none). -1b. **Open `/api/v1/warmup` and make sure the deploy arrived** — once #140 has merged and - deployed that is `{"status":"ok","schema":"0017"}` — and then send the bot `/start`: the - very first message goes through the middleware that reads a class, and that is the fastest - check that the schema and the code agree. That is all that is left of item 1; it needs a - live service, and since the deployments sit behind Deployment Protection it needs a browser - or a bypass token rather than a `curl` from a session. +Items 1, 1a and 1b of this list are done — the last of them, reading `/api/v1/warmup` and +sending the bot `/start`, on 26 September 2026 — and so is item 5, the correction mode's walk, +which #186 made on an emulator (#115). All four are in [docs/history.md](docs/history.md), +«Moved out of section 7», with four paragraphs this section no longer needs. + 2. **Build the APK from `main` and install it on a phone.** See section 5 — it is the only way to check what nothing currently checks, and doubly so after three build-chain bumps. Three things have been added to this: connect the phone to two classes and walk between @@ -4738,13 +1209,6 @@ and that is the thing to decide rather than the ttl. 4. **Open «Настройки → О приложении → Лицензии» in the app** and look at the eighth row — Google Sans Flex. It is built and it compiles, but nobody has seen it with their eyes: what is of interest is how an eighth shade sits in a palette of six. -5. **Switch on «Настройки → Перевод → Режим исправления» and walk the screens.** What is - being checked is what a JVM test cannot see: that the outline appears around labels rather - than around subject names; that a long press on a settings row opens the editor rather - than toggling the row (the gesture is read on `PointerEventPass.Initial` precisely for - this); that pressing a sentence with a number in it — «12,4 МБ» under updates — shows the - pattern `%1$s МБ` in the editor rather than the sum; and that inside the editor itself a - long press does nothing. --- @@ -4770,3 +1234,24 @@ The order that paid off here: whether it looks right. Both defects in the pull request flow were found that way, in code written an hour earlier in the same session, and neither would have failed a test — there was no test that could have run. + +### How to continue + +`dev` remains the working branch, but after a merge it is restarted from `main`: a merged +pull request accepts no new commits. Which pull requests are merged and which one is open +is at the top of this file, not here — this paragraph is about the two commands under it. + +```bash +git fetch origin +git checkout -B dev origin/main # the same dev, a new starting point +``` + +The gates, both halves (`CLAUDE.md` requires running both if you touched both): + +```bash +cd server && ruff check app tests scripts migrations # clean +cd server && pytest -q -n auto # 2024 tests, ~4 min on CI, ~10 on Windows +cd server && python -m mypy # clean, 100 modules +cd android && ./gradlew test # 1459 tests across the five modules +cd android && ./gradlew assembleDebug assembleRelease # both assembles +``` diff --git a/docs/README.md b/docs/README.md index df158ab2..898e0e44 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,8 @@ # Documentation -Nine documents, the reference pages one of them keeps in a folder of its own, and two folders -the app itself reads. Each answers its own question, and none retells a neighbour — if the -answer is not here it is in the code, and there is usually a link to it. +Nine documents, a history, the reference pages one of them keeps in a folder of its own, and +two folders the app itself reads. Each answers its own question, and none retells a +neighbour — if the answer is not here it is in the code, and there is usually a link to it. ## Where to start @@ -16,6 +16,7 @@ answer is not here it is in the code, and there is usually a link to it. | are writing code | [architecture.md](architecture.md), then [CLAUDE.md](../CLAUDE.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) | | are writing a client for the API | [api.md](api.md) | | want to connect a diary other than Петербург's | [diaries.md](diaries.md) | +| are picking up the work | [HANDOVER.md](../HANDOVER.md), then [history.md](history.md) for every batch before its last two | ## Every document @@ -30,6 +31,7 @@ answer is not here it is in the code, and there is usually a link to it. | [architecture.md](architecture.md) | why the bot is the backend, the timetable resolution model, the five Android modules, the three homes a phone can have and the first run's state, the service layer, the diary on both sides — the server's providers and the phone's sign-in, `diary.db` and import — the tests | | [design.md](design.md) | the design system: what was taken from Essentials, what was fixed, and the reasoning behind every visible decision in the interface | | [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from — except for one section, the region catalog the server and the app read, which is generated from this survey | +| [history.md](history.md) | **not a reference — the record.** Every batch [HANDOVER.md](../HANDOVER.md) no longer carries, newest first, in the words of its close-out, and what `HANDOVER.md`'s numbered sections no longer need. True of the commit each section names and never brought up to date, so it is the one document here that is not checked against today's code | | [diaries/](diaries/) | **the reference pages of [diaries.md](diaries.md)**: one page per platform with its hosts, sign-in flows, headers and the full route table read out of the open-source clients, and one page with the evidence for every region. Nothing in them has been tried against a live diary | | [legal/](legal/) | **not a document — the terms of use and the privacy policy the app links and bundles.** `*.ru.md` is the source, `*.en.md` the translation, `legal.json` names the edition and the date it applies from. They describe what this code does, and a fork that runs its own server rewrites the passages marked `FORK` — [build.md](build.md#the-terms-and-the-privacy-policy-the-app-links) | | [app/](app/) | **not a document — the guide the app draws.** `guide.ru.md` is the source, `guide.en.md` the translation, `manifest.json` says which version they are and which app version they describe. The app fetches these files from this repository and falls back to the copy built into the APK | @@ -89,7 +91,9 @@ the user will actually see, it quotes it in Russian, because that is what is on A document that lies is worse than a missing one. So: -- a statement is checked against the code before it lands here; +- a statement is checked against the code before it lands here — except in + [history.md](history.md), which records what was true at a named commit and is never + rewritten to today's; - a change that made a document wrong fixes it in the same batch of work — [bot.md](bot.md) and [widget.md](widget.md) have each been rewritten over drifting away from the code, and that is more expensive than keeping up; diff --git a/docs/history.md b/docs/history.md new file mode 100644 index 00000000..f40d5590 --- /dev/null +++ b/docs/history.md @@ -0,0 +1,3611 @@ +# History + +What each batch of work on this project added, as its close-out in `HANDOVER.md` described +it, newest first. [`HANDOVER.md`](../HANDOVER.md) at the root says where the work stands — the +opening, the two most recent batches, the milestones, what nobody has verified, what not to +break, what is left to the owner — and links here. When a close-out puts a new batch on top +of it, the batch that falls off the last two moves to the top of this file, under this +introduction. + +**This is a record, not a reference.** Nothing here is checked against today's code or +brought up to date: a section is true of the commit and the date it names, and a number in +it is a record of that commit rather than a claim about this one. Where a later batch +overtook a sentence, the later batch says so, and it is higher up. That is also why this +file is left out of the test that every document naming the schema head names the current +one: it holds every head there has been. + +The text was moved verbatim out of `HANDOVER.md` on 27 September 2026 (#211), so it keeps +the conventions of the file it was written in: + +- «this file» and «this document» mean `HANDOVER.md` as it was when the sentence was + written; +- sections 5 to 8 are `HANDOVER.md`'s, which kept their numbers; sections 1 to 4 are here, + after the oldest batch; +- the last three sections hold what was taken out of `HANDOVER.md`'s sections 5, 6 and 7 the + same day, because it narrated work that is done or retold a rule `CLAUDE.md` carries. + +--- + +## What the batch before added: the first walk of the app on a device, and the twelve defects it found + +Merged as `c26eace`. **What #186 moved.** Android: the widget picker's preview draws again +(#167); the widget follows a class switch made inside a live Glance session (#168); a look at +another school year no longer takes the current year's terms away (#169); a server that +cannot be reached is worded by the app, not by OkHttp (#177); «Схема unknown» is gone from +the about card (#172); the one-line widget sizes say «Ничего не задано» rather than «0 +предметов» (#173); a toolbar tab's highlight is a circle (#179); a dropped tab is drawn where +the finger left it (#180); the long press that opens the arranging mode also picks the tab up +(#181); a touch anywhere but the bar closes the mode and reaches nothing underneath (#182); a +scrolled section goes under the pill's round end (#183); segments in a picker's tray are as +far apart as they are from its edge (#184); the build scripts use `directories` rather than +the deprecated `srcDirs` (#185). Server: `tzdata` for Windows (#170). Tests: three that failed +on a Windows checkout pass there (#178). Project: shared Gradle run configurations in `.run/`. + +**The first batch made on a machine with an emulator (#109).** On 26 September 2026 the owner +handed the session Android Studio, an emulator and the live Telegram bot, and asked for every +«nobody has looked at this» to be looked at. It was walked on the AVD `Pixel_10_Pro_XL` +(API 37, `google_apis_playstore`, x86_64, 1344×2992 at 480 dpi, the emulator's GPU through the +host's RTX 3070), against a local server (`seed_demo`, «9А», plus a second class «10Б» in +Asia/Yekaterinburg) and against production, whose «11А» was driven from the bot in the +owner's own chat. Two builds were used side by side: the debug build from this branch, and +the release build the APK workflow made from `bd7c816`, already installed and joined to +«11А». + +### What was seen, by issue + +- **#156, crash reports and the backup — confirmed.** A real crash (`am crash`) wrote + `crash_reports/crash_…_00.log`; `bmgr backupnow` through the local transport, the files + deleted, `bmgr restore`: a probe file in `files/` and one in the `external` domain came back, + the report did not. Again with the transport flagged `is_device_transfer=true`: the same. + The Google transport was put back afterwards. The issue closes on this. +- **#119, warmup and `/start` — read.** See the opening paragraph. Closes. +- **#114, arranging the tabs.** The long press opens the mode (labels fold, the icons wobble); + a second touch dragging «Задания» to the first slot lands there; the reader stays on + «Календарь», which moves with its tab; back leaves the mode, not the app; the order + survives a force-stop. That was the build before #181; since it, the long press carries on + into the drag, and a recording of one injected touch shows the mode opening and the same + touch carrying «Календарь» a slot. **Not answerable on an emulator:** whether half a slot + is right under a thumb, and whether the haptic lands with the mode. +- **#115, the correction mode.** Outlines sit on the app's labels and never on subjects, + times or rooms; a long press on a row with a switch opens «Исправить строку» and leaves the + switch as it was; «Установлена v0.1.0» opens as `Установлена %1$s`; a long press inside the + editor does nothing. The editor lists two keys where two rows share one Russian text + (`settings_debug`, `debug_reports_open`) — by design, not filed. +- **#116, two classes and the join modes.** Joined, listed with «Показывается сейчас», both + ways out named. The widget follows a switch — and did **not** follow a second switch made + inside a live Glance session (#168, fixed). The production class «11А» turned out to be + invite-only already; its class code gets `403` «Этот класс принимает только по личному + приглашению из бота», the release phone that joined it earlier still syncs, and the app + words the refusal as «Этот класс подключает телефоны только по личному приглашению…». A + personal code from the live bot's «📱 Подключить телефон» (a spoiler, fifteen minutes, one + phone) linked the release build: «Телефон привязан · Роль: Владелец · можно + редактировать»; replaying the spent code answered `404`. The `429` was seen for the first + time: «Слишком много попыток. Попробуйте через 15 минут.» (`Retry-After: 866`). +- **#117, the upgrade path.** A debug build of `fa4fe0c` (before #140) was set up — old first + run, «9А», tabs rearranged — and `bd7c816` installed over it with `install -r`: the class + stayed, the first run did not come back, the tab order held, and the first sync was a + `304`. A later install over a build with a widget on the home screen kept the widget + drawing without re-adding it. The same APK re-signed with a fresh debug keystore was + refused with `INSTALL_FAILED_UPDATE_INCOMPATIBLE: … signatures do not match newer version`, + and the installed app was untouched — which is the sentence `docs/build.md` asserts. Both + builds were signed with this machine's debug key: the release keystore lives in CI. +- **#113, the widget's sizes.** Four launcher sizes, not twelve rungs, because the launcher + resizes by cells and the home screen had neighbours: 2×1 «ДЗ на послезавтра · 3 предмета»; + 2×2, about 195×226 dp, which lands on LARGE and cuts «Алгебра в 08:…»; 4×1; 4×2. At font + scale 2.0 the 4×1 still fits and the 2×1 reads «Д… 3 предмета» (#174). The picker's + preview was broken on every launcher from API 31 (#167, fixed). Stays open for the other + rungs and for the corner radii on a real launcher. +- **#111, the ribbon's cost — relative only.** Twelve flings of Monday's ribbon, `gfxinfo`: + debug SHADER p50 200 ms / NONE 250 ms; release SHADER 150 / NONE 200; the system Settings + app scrolled the same way at p50 150 ms, 88 % janky. The shader adds nothing measurable + above this emulator's floor; the floor itself is the emulator. With no lesson running the + ribbon renders one frame in ten seconds, so nothing redraws per frame when idle. Stays open + for a phone. +- **The first run, both ways in.** All five steps in Russian and in English; the legal links + online (GitHub, the English terms) and offline (the bundled «Privacy policy, Edition 1 of + September 25, 2026»). The diary way: the region list; Алтайский край's Госуслуги-only hand-off + to `netschool.edu22.info`; Амурская область's school search, which asked that region's live + «Сетевой город» server over TLS **from the phone** and got its real schools back — + kindergartens included; the «Моя школа» hand-off to `gosuslugi.ru/school`; the password form + with its host and the `http://` warning. No password was typed anywhere. +- **The calendar.** Week, month, the day's ribbon and list, «Подробно», the year picker, and + 2025/26 fetched on demand with «Загружаю год». The ribbon did not crash (#79's defect). +- **Offline and the server badge.** The cache stays on screen when the server goes away; the + about card's badge met a real server for the first time («Сервер: база и код разошлись» + on a `create_all` database, correctly). +- **Studio's Logcat**, read on the owner's request: the release build's periodic + `SyncWorker` ran eleven seconds against production, cold start included; WorkManager's + «onNetworkChanged() not implemented in … SystemJobService» on API 37 is the library's, not + ours; «Davey! duration=1046ms» opening a lesson sheet is a debug build's JIT on this + emulator's floor. + +### The defects, each filed before its fix + +| # | What was wrong | What it does now | +| --- | --- | --- | +| #167 | The picker's preview was «Couldn't add widget.»: a plain `<View>` in `widget_preview.xml` | `FrameLayout`; `RemoteViewsLayoutTest` refuses any class RemoteViews will not inflate | +| #168 | Two redraws inside one Glance session drew the first snapshot: the widget stayed on the class just left | `WidgetRedraws` counts redraws, and a live composition re-reads when it moves | +| #169 | A sync of another year replaced the class row's terms; a `304` never put them back | `replaceWindow` keeps other years' terms and takes the window's own | +| #170 | The server did not start on Windows: no time-zone database | `tzdata` declared for Windows only, and left out of the bundle on purpose | +| #172 | «Схема unknown» on the about card | the server's sentinel is no revision, and draws no chip | +| #173 | «0 предметов» on the one-line widget sizes | «Ничего не задано», from the one place that words the count | +| #177 | OkHttp's English inside «Не удалось подключиться: …» and «Не удалось обновить: …» | the app's own sentences; `SyncMessage.Failed` carries no detail | +| #178 | Three tests failed on a Windows checkout (paths with `/`, a blank line without `\r`) | normalised; `JoinErrorTest` no longer asserts the #177 defect as correct | +| #179 | (the owner's request) a tab's press and focus highlight was a square | drawn inside the tab's `CircleShape`; the press still takes the whole box | +| #180 | (the owner's report) a dropped tab was drawn for a frame in the wrong place: tabs composed by position, and the selection read from the pager's index | tabs keyed by label and animated by where they are; the selection read from the tab being kept on | +| #181 | (the owner's request) picking a tab up took a second touch after the long press | one detector on the initial pass opens the mode and carries the tab; the long press stays a TalkBack action | +| #182 | (the owner's request) a tap outside the bar did not close the mode, and reached the page | `ArrangingDismissLayer` between the page and the bar | +| #183 | (the owner's report) a scrolled section was cut by a straight edge 8 dp inside the pill | Material's side padding moved inside the rows, so the pill's own round clip is what cuts | +| #184 | (the owner's report) segments in a tray 2 dp apart, 4 dp from its edge | the gap is the tray's inset; bare pickers keep Material's connected 2 dp | +| #185 | (the owner's screenshot of a sync) six warnings that `srcDirs` is deprecated in AGP 9.4 | `directories +=` with the same paths; `LegalBuildPropertyTest` matches the new line | + +Left open, with their reasons in the issue: **#171** (a join fetches the year twice, three +times once; seen on the build before #140 too), **#174** (small widget sizes), **#175** +(a repeated sentence on the sign-in form), **#176** (a stale join error that did not +reproduce the second time). + +Every fix was checked again on the emulator it was found on, except #173's wording, which +the widget at its current size does not draw (`SubjectCountTest` holds it), and #180–#184 — +see the next section. + +### The owner's toolbar, checked on the emulator while the owner used it + +#180–#184 came in one at a time over the evening and the night, each as a sentence and +most with a screenshot. Each has a Robolectric test that fails on the code before it: the +drop is read on its first frame (horizontal centres, to a dp and a half — the scale and the +jiggle both turn about the centre), the one-touch gesture is driven with the long-press wait +on the composition's clock, the layer is asked with the real bar on top of a page that counts +its own taps, and the two gaps are read as geometry. `ToolbarShellCallerTest` puts the bar +under a caller shaped like `LessonsApp` — the list latched, the order written and read back +some frames later — and asks for one commit and a row that stays where it was dropped. + +On the emulator, the check was a screen recording of one injected touch, cut into frames +with `ffmpeg`. It showed the one-touch pickup working, the round end of the pill clipping a +tab that slid out, and **two defects in this branch's own unmerged code**, fixed before the +merge and so not filed: the label that folds as the mode opens was on the bar's bouncy +spring, and with the drag already under way its dip below nothing carried a neighbour out +under the pill's edge for a third of a second (it now folds on `toolbarSettleSpring`); and +keying the tabs had taken the gap after each tab along with it, so a drop that moved the last +tab into the middle landed the tab behind it 8 dp short (the gap is `ToolbarGap` now, owned by +the slot). + +It also showed what could not be settled there: **the owner was using the emulator at the +same time.** The injected touch was once cancelled by the system for another device's +(«Canceling pointers for device 4»), the tab order changed between two screenshots with no +command of this session's in between, the guide was open where the calendar had been, and +Google Calendar came to the front mid-check. The final order that recording left in storage +was one no single drag of the injected touch could produce, and the same arrangement in the +JVM gives exactly one commit — so the device run is not evidence either way, and the session +stopped driving the emulator rather than fight for it. **Not seen on the device:** the drop +without its flash (#180), a tap outside closing the mode (#182), and #184. + +### The machine, and what it cost + +- **The emulator image's SystemUI crash-looped** on `SecurityException: Need + android.permission.BLUETOOTH_CONNECT` — its runtime permissions had been revoked — which is + also the Bluetooth crash in the owner's note to the bot. `pm grant` for every denied + permission fixed the running session; **the Quick Boot snapshot still held the revoked + state**, so every quick boot brought the crash back, and the long press on the launcher + stayed dead until a reboot. Saving a new snapshot with `adb emu avd snapshot save` froze + the emulator — it stalled writing `textures.bin` — and the stuck process had to be stopped; + the next start was a cold boot and came up healthy, with the grants in place. That freeze + briefly blocked the owner's own «Run» from Studio. +- **The Quick Boot revert.** A restart of the emulator mid-session quick-booted from a + snapshot taken before this session, which took back the debug app, its data, the widgets and + the permission grants: a build installed afterwards met a fresh first run. The release build + predates that snapshot and kept «11А», probably without the personal-code link made later. +- **C: had about 2 GB free**, which is why the emulator refused to start once («Your device + does not have enough disk space to run avd»). The AVD alone is 12 GB, 8.5 GB of it the + Quick Boot RAM image; `./gradlew clean` in this worktree gave back what its builds took. +- **Android Studio is set up** (none of it in this repository, all of it the owner's + machine): the repository root opened with `android/` linked as a Gradle project on JDK 21 + (`android/.gradle/config.properties`), `.claude/worktrees`, the venvs and the caches + excluded from indexing, a `server/.venv` for the Python plugin, local run configurations + for uvicorn, the seed, pytest as CI runs it (no source roots on `sys.path`), ruff and mypy, + Logcat favourites for this project, Kotlin auto-import, a project dictionary, and a 4 GB + heap (`studio64.exe.vmoptions` in the config directory). **Waiting for the next restart of + the IDE:** registering `server/.venv` as the Python SDK, turning the root module into a + Python one (which quiets «Unsupported Modules Detected»), and disabling the third-party + «Python Portable» plugin that fails to load on every start — the IDE rewrites those files + on exit, and the owner was using it. +- **The release keystore** (a folder on the owner's machine, handed over during the session) is PKCS12 + and came without its passwords, so nothing was signed with it and its certificate was not + compared with the build on the emulator. Before it replaces the key CI signs with: an APK + signed by a different key does not install over the one already on a phone (above, #117). + +### Gates + +At this branch's last commit before the close-out: `ruff check app tests scripts migrations` +clean; `pytest -q -n auto` **2024** passed (9 min 56 s here, against CI's four); +`python -m mypy` clean, 100 modules; `./gradlew test` **1438** (`:core:model` 125, +`:core:data` 537, `:core:designsystem` 112, `:widget` 113, `:app` 551); `assembleDebug` and +`assembleRelease` build, and a sync prints no deprecation. + +### What nobody has verified in this batch + +Everything in the list above that says «emulator» and is a question about a hand: the +threshold under a thumb, the haptics, TalkBack, a real GPU's frame times, Doze on a school +morning, the widget's other eight rungs. No diary was signed in to. Nothing was signed with +the release key. The Python SDK and the plugin change in the IDE wait for a restart. The +owner's toolbar requests are held by JVM tests and, on the device, only as far as the section +above says: #180, #182 and #184 were not seen there. + +## What the batch before added: «Сетевой город» on the server, and a way in through your own school's diary + +Open as PR #140, from `claude/school-diary-api-routes-cc4o1n`, on milestone 10 +(`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`). Twenty-two commits on +`fa4fe0c` when this was written, `4c34cb5` to `8bad211`, then the fixes of the review that +was running on the branch and this close-out. It is two batches on one branch, and both +halves of the project moved. + +The second part was planned in design documents and a decision record that stayed in the +session's scratch space, as #134's generator did. What they settled is in the commit bodies, +in #141 and in `docs/architecture.md`, so nothing needs them; but a session that goes looking +for a design document in the repository will not find one. + +### Part one: «Сетевой город» on the server (#139) + +Seven commits, `4c34cb5` to `9ceef0c`, and their documentation, `42fdf0a`. The project read +one diary, Петербург's, wired straight into `services/diary.py` and `/diary/signin`. This +part puts a seam between the service and the provider, adds a second provider behind it, and +reads either from the same bot and API. + +- **A provider-neutral diary seam** lives under `server/app/providers/diary/`: the shared + models, a `DiaryError` family (`PetersburgError` re-exported as an alias so nothing that + caught it breaks), a `DiaryProvider` / `DiaryConnection` `Protocol` contract, and a + `registry.py` whose `binding()` is the single resolver of a class's diary binding. + Петербург goes behind it **byte-for-byte unchanged**. +- **«Сетевой город»** (`server/app/providers/netschool/`) — ИРТех NetSchool, the main diary + of about twenty regions, one route set for all. It carries a region **allow-list** (the + only origins ever contacted — the SSRF guard), windows-1251 salted-MD5 password sign-in, + the weekly diary mapped onto the existing models (homework is assignment type 3), + keep-alive, and school search for binding. +- **The service dispatches by provider.** `POST /api/v1/diary/login` accepts optional + `provider` / `region` / `school_id`, and `services/diary_keepalive.py` keeps every live + «Сетевой город» session alive from `GET /api/v1/cron/tick` with `GET /webapi/context`, + within a batch cap and a time budget, never touching `last_used_at`. `TickOut` gained + `diary_sessions_kept_alive`, `diary_sessions_lost` and `diary_keepalive_failed`. +- **The bot binds and reads either diary.** An admin binds a class to «Сетевой город» through + a provider chooser → region → school-name search; the read path (`bot/handlers/diary.py`) + is provider-neutral, and the sign-in card names the bound diary in the genitive. +- **Three diary defects fixed (#136, #137, #138).** Revoking a member drops their diary + sessions and links, not just invites and subscriptions; `/diary/signin` re-checks the + class binding at submit and refuses **before** spending the ticket if the diary was unbound + or rebound after the ticket was issued; four false diary comments corrected and two dead + type names removed. + +Its gates at `9ceef0c`, a record of that commit: `pytest -q -n auto` 1668, `python -m mypy` +clean across 97 modules; Android was not touched. + +### Part two: a way in through your own school's diary (#141) + +Fourteen commits, `17c0473` to `8bad211`: four on the server, five on the phone, one for CI +and four of documents. + +- **The first run has two ways in.** After «Продолжить», the introduction and the + permissions, a family picks the class code, as before, or its own school's diary: the + region — all 89, found on every keystroke in Russian or English, by nickname, city, code, + the wrong keyboard layout or transliteration, or by typing a school's name — then the + school, searched on the region's own «Сетевой город» server, then the region's systems + with the recommended one highlighted and «Почему?» beside it, then the sign-in, then the + import under a wavy progress bar, then a summary. The path is a saved list of steps, + `OnboardingFlow`, in `android/app/.../ui/onboarding/`. +- **On that path the password never reaches our server.** The phone signs in to Петербург or + «Сетевой город» itself — over https, only to an origin in the bundled catalog, with no + redirects and no cookie jar (`core/data/.../upstream/`) — and hands the session to + `POST /api/v1/diary/session`, which reads once with it from its own address, seals it with + Fernet and answers with our diary bearer. A `password` key in that body is a `422`. The app + no longer calls `POST /api/v1/diary/login`; the endpoint stays for older APKs, and + `docs/api.md` and the bot's `/diary/signin` page now say plainly that on those two routes + the password passes through this server. +- **The phone knows what the server can do before a password is typed** + (`GET /api/v1/diary/capabilities`), every diary `503` says why in `X-Diary-Unavailable` + (`disabled`, `address-refused`, `upstream`), and a session the diary refuses from our + address is a `409` rather than `/login`'s `401`, because asking for the password again + would loop. `JoinResponse.diary` hands a joining phone its class's binding. +- **A phone that reads only its diary has a home of its own.** `ShellMode` is none, class or + diary: a phone in no class with a diary session opens on the diary, whose settings keep + «Дневник» and «Выйти из дневника» (#151), and periodic class sync is armed only in class + mode (#152). Every diary failure has its own words through `DiarySignInProblem` and + `DiaryProblemText` (#153). +- **The phone keeps what it reads.** `diary.db` is a second Room database, written only by + successful reads; `DiaryImport` fetches pupils, terms, timetable, homework and marks with + weighted progress and resumes from the phase that failed. The one unprompted read is a + refresh when the app comes to the foreground and the copy is older than 30 minutes; + `SyncWorkerSourceTest` fails if the worker or the widget ever names the diary. +- **The widget says which way in a phone took**: a diary-only phone is told «Дневник — в + приложении» rather than asked for a class code, and a phone with neither is offered both + ways. +- **The terms and the privacy policy exist and are linked.** «Продолжая, вы принимаете + Условия использования и Политику конфиденциальности» is always drawn under «Продолжить»; + `docs/legal/{terms,privacy}.{ru,en}.md` and `legal.json` are bundled in the APK, opened in + the browser when online and from the bundle otherwise, and also from «О приложении». + `LESSONS_LEGAL_BASE_URL` / `lessons.legal.baseUrl` becomes `BuildConfig.LEGAL_BASE_URL`, + https only, one per fork; `apk.yml` derives it from the repository it runs in unless the + repository variable of that name overrides it. +- **A catalog of all 89 regions** — `server/app/catalog/data/regions.json`, generated by + `scripts/region_catalog.py` from `docs/diaries/regions.md` and a hand overlay + (`scripts/region_catalog.toml`): each region's systems, which one is recommended and the + reason codes for it, and the allow-list's «Сетевой город» origins byte for byte. The phone + bundles the same file in place as its only source of a diary host, and `--check` and a + test fail when the survey or the allow-list changes without a regeneration. +- **An anonymous school directory.** `GET /api/v1/directory/school-regions?q=` answers which + regions a school may be in, from DaData; a name that exists everywhere («Школа № 5») is + answered `generic` without calling DaData. It is throttled at 20 calls per 15 minutes per + caller and capped at 4,000 of DaData's 10,000 daily requests, counted per Moscow day in + `usage_counters` (`services/quota.py`, migration `0016`), so onboarding cannot spend the + search the bot's create-class step depends on. +- **Known-answer vectors both halves run.** `server/tests/vectors/diary_protocol.json` pins + both sign-in protocols, the login cleaning and the parsing of raw answers; the Python tests + and the Kotlin port run every case, so the two implementations cannot drift apart silently. + That proves they agree, not that either is right. +- **Each CI job runs whenever a file its tests read changes** (#159), not only its own + folder — `docs/deploy.md`, `docs/build.md`, `docs/diaries*`, `docs/legal/`, the catalog + and the vectors included. + +### The defects, each filed before its fix + +Twenty-one, on top of part one's three (#136–#138): + +| Issue | What was wrong | Fixed in | +| --- | --- | --- | +| #145 | «📒 Мой дневник» kept reading the «Сетевой город» region a class had been rebound away from | `6fa1c6e` | +| #146 | the keep-alive could overwrite a credential a diary read had rotated while the ping was in flight | `6fa1c6e` | +| #147 | a sign-in without `cacheVer` sent the word `None` upstream as `ver` | `6fa1c6e` | +| #148 | malformed «Сетевой город» sign-in answers escaped the diary errors as `500`s | `6fa1c6e` | +| #149 | the school search kept a result whose id was JSON `true` and bound the class to school 1 or 0 | `6fa1c6e` | +| #150 | comments and documents described a CA bundle, a breaker, a region order and a password route that do not exist, and the bot told families their password went «прямо в дневник» | `6fa1c6e`, `0a9a188`, `6281dea`, `5efca54` | +| #151 | a phone that left its last class kept its diary sign-in but could neither open «Дневник» nor sign out of it | `b19e6b2`, `c032ff2` | +| #152 | a phone in no class had its periodic sync re-armed on every cold start | `b19e6b2`, `c032ff2` | +| #153 | the diary said «HTTP 429», «Дневник не отвечает» for a switched-off diary, and a raw «HTTP 504» | `6fa1c6e`, `b19e6b2`, `c032ff2` | +| #154 | the join screen, settings and the guide promised a default server the APK does not have | `c032ff2`, `5efca54` | +| #155 | the design credit ran into the word before it, «по мотивамEssentials» | `ce9c749` | +| #156 | crash reports went into the cloud backup although the first run says they stay on the phone | `ce9c749` — **stays open** until a phone confirms it | +| #157 | comments and `docs/design.md` described a four-screen first run and a six-character class code | `c032ff2`, `5efca54` | +| #158 | the bot's sign-in page sent a «Сетевой город» family to Петербург's diary on an unreadable answer | `0a9a188` | +| #159 | CI skipped the server tests that read `docs/deploy.md` and `docs/build.md` when only those changed | `ba9170c` | +| #160 | contributor and agent documents quoted a stale test command, stale counts, wrong secret names and milestone facts | `8bad211` | +| #161 | a join whose screen was gone before it landed left its result behind; the next «Добавить класс» sheet closed on it, and the first run could skip the class's diary sign-in | `061a716` | +| #162 | Dependabot and the issue templates applied labels the project does not have, so bumps arrived bare and reports outside `type:` and `status:` | `f31e5ed` | +| #163 | the join and diary sign-in throttles counted before they recorded, so a burst went past them (24 wrong passwords against a limit of 10) | `6b0878f` | +| #164 | the server's checks assumed SQLAlchemy 2.0 while every fresh install resolves 2.1: one test compared SQL without casts, and mypy failed on `main` | `d208251` | +| #165 | a session registered from a phone names its own login, unchecked, and that login keys another family's corrections | `e01443d` — corrections are now the child's, by the owner's decision | + +Twelve more, from an adversarial review of the new Android data layer, were fixed in +`9c797a2`, each with a test that failed before its fix. They are listed in that commit's +body and have no issues of their own: they were in code this branch adds, and none of it +had reached `main`. The same holds for the thirty findings of the second review of the +screens (`061a716`, 31 in all, one of them #161) and for twenty of the audit of the server +half (`6b0878f`, 22 in all: #163 fixed there, #165 in `e01443d`). The change for #165 had a +review of its own: five lenses, two refuters per finding, 17 of 23 findings confirmed. All 17 +are fixed in the same commit, and its body lists them. + +**One commit body is wrong, and the code is right.** `6fa1c6e` says rebinding a class to +another *school* expires its diary sessions. `services/diary.expire_off_binding` expires them +when the provider or the region changes and keeps them for another school in the same region, +because a «Сетевой город» session is an account on the region's server rather than on one +school. The documents follow the code. + +### Schema + +`EXPECTED_REVISION` is `0017`. Production was at `0014`, three revisions behind, until the +transaction below: + +- **`0015`** (`0015_diary_provider_columns.py`) adds five nullable columns to + `diary_sessions` — `provider`, `region`, `kept_alive_at`, `keepalive_attempted_at`, + `upstream_ok_at` — and three to `classes` — `diary_region`, `diary_school_id`, + `diary_school_name`. A `NULL` provider means Петербург, the only diary before the column. + Its downgrade expires every non-Petersburg session before dropping the columns that tell + one apart. +- **`0016`** (`0016_usage_counters.py`) creates `usage_counters` and nothing else. +- **`0017`** (`0017_corrections_per_child.py`) is data only (#165). It rewrites + `diary_overrides.login` from a login to the child's scope: `CHILD:petersburg`, or + `CHILD:netschool:` and the regional server's host. It deletes the branch-only + «Сетевой город» hash-keyed rows, which could no longer be read. Where two rows corrected + one field of one child, it keeps the newest. On PostgreSQL it takes a lock first. It is a + third shape, «a rewrite of a key»: free where there are no rows, and **after** the merge + where there are, for the reasons its docstring and `docs/deploy.md` give. + +`0015` and `0016` are additive, and rewrite and destroy no row. `0017` would destroy rows +only where there are corrections, and production had none. So all three went on **before** +the merge, together, through the Neon connector. The DDL was taken from the revisions +rendered offline for PostgreSQL, and it matched the models' own DDL statement for statement. +The database's state was read first, and `alembic_version` was stamped in the same +transaction, last. + +**Applied on 26 September 2026 at 12:26 UTC, before the merge, as one transaction through +the Neon connector.** The owner had allowed the migrations on one condition: that the code +they serve has no known defect. That was met once #165 was decided and fixed in `e01443d`, +and CI went green on that commit. The database was read twice first, at 11:22 and at 12:25 +UTC. Both reads showed head `0014`, none of the eight columns, no `usage_counters`, **0** +rows in `diary_overrides` (0 of them legacy «Сетевой город» keys), **0** diary sessions and +**1** class. The transaction ran the eight `ADD COLUMN`s of `0015` and the `CREATE TABLE` of +`0016`. Then `0017` ran its lock, its two deletes and its rewrite, and last came the stamp +`UPDATE alembic_version SET version_num = '0017' WHERE version_num = '0014'`. Every +statement was taken from the revisions rendered offline for PostgreSQL, which matched the +models' DDL. Read back afterwards: head `0017`, one stamp, all eight columns nullable with +the declared types and widths (`VARCHAR(32)`, `BIGINT`, `VARCHAR(300)`, `TIMESTAMP WITHOUT +TIME ZONE`), and `usage_counters` with primary key `(scope, day)`. There were still 0 +corrections, 0 sessions and 1 class, so nothing was rewritten and nothing was destroyed. +Until #140 merges and deploys, the running code is older than the database, and +`/api/v1/warmup` answers «База впереди кода…»: the window the correct order creates. The one +thing the window could lose is a correction typed through the old `/diary/login` before the +deploy, which would be filed under a login. No diary session existed to type one. + +### What was deliberately left alone + +- **No Госуслуги (ЕСИА) sign-in, no WebView and no cookie capture, anywhere.** A Госуслуги + session is a session to the person's whole state-services account. ТОР «Моя школа» and the + three Госуслуги-only «Сетевой город» regions (`altai-krai`, `primorye`, `tula`) hand off to + the official site instead, and a generator test refuses any catalog field for an in-page + sign-in. This is the code's answer to #135's second and third questions; the issue stays + open for the owner to close. +- **A diary-only phone's widget, «Сегодня», «Календарь» and alerts show nothing from the + diary** — + #142, `status:next`, no milestone. Feeding them would mean a background read, which would + count as the family's activity and keep a session alive with nobody behind it. +- **A diary session opened on the phone is invisible to the bot** — #143, `status:someday`, + no milestone. Phone-registered rows carry no Telegram account and no class. +- **A fresh install has no default server** — #144, a decision for the owner, no milestone. + The address is asked for where it is first needed; there is no + `LESSONS_DEFAULT_SERVER_URL`. +- **The class's binding reaches the phone in `JoinResponse.diary` only**; `ClassOut` does not + carry it. +- **The password routes stay.** The bot's `/diary/signin` and `POST /api/v1/diary/login` + still pass a password through this server, for the bot and for older APKs, and the texts + now say so. +- **The phone does not refuse a login longer than the server's 200 characters**; the server + answers `422` at registration, which the phone reads as an app bug. +- **Left from part one:** the refresh-token grant (LoginType 9) is in the client and + unverified live, and SignalR reports — final marks, attendance letters — are not read. +- **The older sections of this file quote the milestones' old titles** where that is what + they were called at the time; the table maps each to its new one. + +### Gates + +Run, not quoted. The server was run on the branch at `e01443d`, against **SQLAlchemy +2.1.1**, which is what CI and Vercel install now (#164): `ruff check app tests scripts +migrations` clean; `pytest -q -n auto` **2024** passed (1634 on `main`); `python -m mypy` +**Success** across **100** modules (84 on `main`). The alembic chain from nothing lands on +`0017`. The Android tests were run at `061a716`, +and Gradle found every test task up to date against the sources at `f31e5ed`: `./gradlew +test` **1408** (968 on `main`), with `:app` 548, `:core:data` 532, `:core:designsystem` 99, +`:core:model` 125 and `:widget` 104; they were rerun with `--rerun` after the texts of +#165's fix changed, with the same counts. `assembleDebug` and `assembleRelease` were last run +locally at `061a716`, and CI builds both on every push. A checkout set up before 2.1 was +published keeps SQLAlchemy 2.0.54 until it is upgraded. The suite passes on both, and a +mypy run on 2.0 does not see what 2.1's typing sees. `b19e6b2` and `c032ff2` report the +grep for Russian in Kotlin finding nothing new but `UpstreamMarkers.kt`, the diaries' own +words matched in their answers. It was not re-run for this close-out, and no Kotlin has +changed since `061a716`. + +### What nobody has verified in this batch + +Section 5 carries each of these with the reason it is unverifiable. In short: + +- **Nothing has met a live diary.** «Сетевой город» has never been signed in to for real, on + the server or through the phone's port, and Петербург never through the phone. +- **Whether a session opened on a phone is accepted when our Frankfurt server replays it** is + open for both diaries. A `409` is the designed failure; the owner's first live session + decides it. +- **Nothing has run on a device**: the first run, the swap between the three homes, the + handoffs to the browser, the backup exclusion (#156), TLS against the regional servers, + Android's own windows-1251, `diary.db` on a real phone, the widget's new sentence on a + launcher. +- **DaData**: whether its company rows carry `region_kladr_id`, the codes of the four regions + admitted in 2022, and whether its day turns at Moscow midnight. +- **The legal texts have never been read by a lawyer.** +- **The throttles' record-then-count (#163) is proven on SQLite only.** On PostgreSQL it + rests on READ COMMITTED showing each statement every commit before it, and it has not run + against a live database. Neither has `alembic upgrade head` on an empty PostgreSQL. The + permission system refused a local server, so `0015`'s guard for a database that `0001` + built is proven offline and on SQLite. + +## What the batch before added: the electronic diary of every Russian region, and the routes each platform exposes + +Merged as PR #134 (`fa4fe0c`), from `claude/school-diary-api-routes-cc4o1n`, in the milestone +then called `v0.8.0 — On a device`; it closed #130. **Documentation only.** No file under +`server/`, `android/` or `.github/` changed, and there is no migration. + +The project reads one diary, Петербург's. Until this batch nothing in it said what a school +anywhere else keeps its marks in, how a client signs in there, or which routes it exposes. +So the question #127 names, «что делать, если у нас не Петербург», could not even be scoped. + +- **`docs/diaries.md`** maps all 89 federal subjects to the platform their schools use in + September 2026. It gives what each region left behind and where it is moving, and a table + of the platforms: how a client signs in today and which open client to read first. It + describes the sign-in pattern across the country, what the survey means for this project, + and what it does not cover. The mandatory regions are marked and had a deep check of their + own: Санкт-Петербург, Москва and the eleven of the «Моя Школа» region picker. +- **`docs/diaries/`** holds one page per platform, nineteen in all, with 1916 routes + between them. Each row gives the method, path, authentication, parameters and response, + the client it was read from, and whether it is *current*, *legacy* or *uncertain*. + `regions.md` beside them carries the quoted, dated evidence for every region. +- **The index, `CLAUDE.md`, `README.md`, `docs/architecture.md` and the `docs-keeper` + agent** now count nine documents and link the survey. + +### How it was made, and how far it can be trusted + +It is the method `providers/petersburg/` was written by, at the scale of the country: + +- **Routes.** Every open client found on GitHub, GitLab, Codeberg, PyPI and npm was cloned + and read. A second reader grepped each route back to its source, and a third dated it. +- **Regions.** Every region was researched, then re-checked by an independent pass told to + refute the first. A completeness critique listed what both passes had missed, and a second + round went after that list. +- **Official apps.** Two platforms were read from their official apps: ТОР «Моя школа» from + «Госуслуги Моя школа» 5.0.0.454, and ЭПОС.Школа from «ЭПОС» 1.53. ТОР has no open client; + ЭПОС.Школа's only one dates from 2022. + +**Nothing was tried against a live diary.** Every diary host refuses a connection from a +cloud session. So a route in these pages is what a client's code sends, never what a +server was seen to answer. #121 records the same caveat for the one provider that exists, +and each page dates its clients for this reason. + +**The generator is not in the repository.** The pages were rendered from the research data +by scripts that stayed in the session's scratch space, because they read agent transcripts +that exist nowhere else. A later correction is an edit to the Markdown. + +**Other people's credentials were redacted.** Several public clients hard-code the OAuth +`client_id` / `client_secret` pairs of Дневник.ру and «Сетевой город». Every one is +`<redacted>` in the pages, and the assembly refused to write a page that still held one. + +### What it found that decides the next provider + +- **A password is now the exception.** `/diary/signin` is built around Петербург's email + and password, and that is unusual. In most regions Госуслуги is the only door, and the + clients that last keep a token a person brought from a browser. A second provider cannot + reuse `/diary/signin` as it stands. +- **Twenty regions moved to ТОР «Моя школа» on 1 September 2026**, by the official list of + its first wave. They share one API, and one batched call carries the whole diary. But + the sign-in is Госуслуги's own and its `client_secret` is signed on Госуслуги's side. + Nobody outside has got in except through a person signing in inside a WebView. Whether + that is acceptable under Госуслуги's terms was not reviewed. +- **«Сетевой город» is the largest group that still takes a password.** It is one route set + on each region's own server, and it is the main diary of 20 regions, though + some of them allow Госуслуги only. It is the obvious first candidate, and the МЭШ family + comes after it. + +### What was deliberately left alone + +- **Provider code.** #130 asked for the map and nothing else. Which provider comes second, + and how it signs in, is the owner's decision. It is filed as #135 and set out in + section 7. +- **The teacher's side, and a parent with several children.** The open clients barely touch + either, and the overview says so rather than guessing. +- **The generator**, for the reason above. + +### Gates + +No file the gates read changed, so `ruff`, `pytest` and `./gradlew test` were not re-run. +CI's path filter skipped the Server and Android jobs on every head, and «What changed» +passed. What was checked instead, on the final head: + +- every relative link and anchor in the new and touched documents resolves; +- every table row has its header's column count; +- the redaction scan finds no credential. + +## What the batch before added: the tracker (#128), its rule (#129), and their close-out (#133) + +Merged as #128 (`3c3b728`), #129 (`a43c6e8`) and #133 (`5a77d14`). Documentation and agent +configuration only. No model, endpoint, screen or test changed, so the gates stood exactly +where #85 measured them. + +- **#128** opened the issue tracker: forty-two issues, #86–#108 closed and #109–#127 open, + labelled `type:`, `area:`, `status:` and `needs:`. It also moved the work to a local + machine with an emulator and a phone, and wrote down what that unlocks and what it still + cannot do. That is the section «Where the work happens from here» above. +- **#129** made it a standing rule that a found defect becomes an issue before it becomes a + fix, with one issue per finding, `Closes #NN` in the pull request and both numbers in the + release notes. The rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` + skills. The owner created the ninth milestone, `v0.8.0 — On a device`, and #129 put its + number into the tables. +- **#130** was opened by the owner on 23 September: map every region's diary platform and + the API its open clients use, as a document in `docs/`, with no code. It is `status:now` + and needs no device, so it is the natural first task for a session that has none; #134 + is that task. +- **#133**, the close-out, fixes two defects that were found while writing it, and each got + its issue first. **#131**: #129 left the milestone table's `Dependencies` row stranded below + two paragraphs, so GitHub drew a table without it. **#132**: `CLAUDE.md` still quoted 1610 + server tests, while the other three places say 1634. `CLAUDE.md` is not on the `handover` + skill's list of places where the count lives, which is how it drifted. The list is left as + it is: the `Commands` line is the only count in `CLAUDE.md`, and one more place to remember + is what this issue now records. + +**Nothing new has been verified.** Everything in sections 5 and 7 still stands, and both +already point at their issues. `/api/v1/warmup` has still not been read since #61 (#119). + +## What the batch before added: the gesture #84 shipped did nothing, and the variables nobody could find + +Merged as PR #85 (`ef07739`), in the milestone `v0.7.0 — Оптимизация`. It is one defect, and +it is the defect that the feature merged an hour earlier did not work: **a tab dragged to +another slot went back where it came from and the order was never stored.** On the screen it +looked right the whole way — the icons slid, the row opened a gap, the neighbours moved — +because all of that is recomputed every frame. Only the drop was wrong, and the drop is the +part that is remembered. + +### Why it survived #84's tests + +`Modifier.pointerInput` keyed on `Unit` starts its coroutine once and never restarts it, and +its element compares equal on the key alone — so the node is never even handed a newer +lambda. Whatever `detectHorizontalDragGestures` closed over on the composition that opened +the mode is what it still calls minutes later. `held` and `dragPx` survived that, being +state reads through a delegate; **the landing slot did not**, being a plain `val` computed +in the caller's composition. Every drop therefore asked where the tab had been *before* the +finger moved, which is no slot at all: `moveItem` refused the out-of-range index, the order +came back unchanged, and the preferences were written with the order they already held. + +Nothing in #84 could see it. `ToolbarReorderTest` asks the arithmetic in pixels with no +composition, and it was right; `ToolbarReorderModeTest` asks which callback a press raises, +and those were right too. **Between the two sat the one question neither asked — whether +the number the gesture computes is the number the gesture reports.** #84 wrote down that the +drag was driven from no test, and gave a good reason (a synthetic swipe of «half a slot» +measures Robolectric's densities rather than the gesture). The reason was sound and the +conclusion was not: a drag of ten thousand pixels lands on the last slot under *any* +density, because `dropIndex` parks a finger that has left the bar at the end. That is what +`ToolbarDragTest` does. Two of its first three went red on the shipped code straight away; +the third passed, and passed for the wrong reason — see the trap below — which is worth more +than the two that failed, because a test that is right by accident is how a defect survives +a batch in the first place. + +The fix is `rememberUpdatedState` on the four gesture callbacks — the same pattern +`Corrections.kt` in this module already uses for exactly this reason, which is the part that +stings. Restarting the coroutine instead, by keying `pointerInput` on something that +changes, would cancel the gesture under the finger every time the drag moved a pixel. + +### And the frame #84 left deliberately is closed + +That close-out recorded a one-frame flicker at the end of the gesture and said the proper +fix — the component dropping its permutation by the identity of what it is handed rather +than by the mode closing — risked silently double-applying a drag. It does the opposite: +`working` is now keyed on the order of the labels it permutes, so a list swapped under a +live permutation replaces both in one step instead of two. A caller that hands the committed +order straight back is now drawn correctly, which is the case that would have double-applied +before, and the shell's latch is no longer load-bearing for that — it stays because it keeps +two drags of one session describing permutations of the same list. + +The test for it hands the bar its own reported order mid-mode. On the code without the fix it +drew «Задания, Сегодня, Календарь» for a drag that asked for «Календарь, Задания, Сегодня» — +the permutation applied twice, which is what the comment in #84 predicted and priced as too +risky to close. + +One trap in the test itself is worth carrying: `translationX` here is a `graphicsLayer`, and +`positionInRoot` — which every bounds assertion goes through — counts that layer in. Read six +frames after the finger lifts, a tab that had not moved at all sorts into the place the drag +had merely carried it, and the assertion passes against the very defect it was written for. +The springs are given 120 frames now. + +### The configuration nobody could find in one place + +Two questions came out of a screenshot of the Vercel variables, and the answer to the first +was «yes, in `docs/deploy.md`», which is only two thirds of an answer. **`server/.env.example` +— the file every set of instructions says to copy — was missing three of the eleven**: +`WEBHOOK_SECRET`, `CRON_SECRET` and `BOT_USERNAME`. Two of those three are ones a deployment +refuses to start without, so the cost of each was a deploy to find out. It was also missing +`TRUSTED_PROXY_HOPS` and `WEBHOOK_PATH`, which are real knobs nothing outside `config.py` +mentioned. It now carries all fifteen settings the code reads, each with what empty means, +and says in prose why the sixteenth — `VERCEL` — is deliberately not a line in it. + +Nothing could have caught that. **A missing variable is not a missing field:** every setting +has a default, which is the whole reason the refusal-to-start check exists, so the server +runs perfectly well against an example file half a year behind. `tests/test_env_example.py` +is the guard — four tests, pinning the file to `Settings` in both directions, pinning the +prose about `VERCEL`, and pinning that every secret a workflow reads is named in +`docs/build.md`. Each was watched going red: the first against the file as it was this +morning, the last against a ninth secret added to a workflow. + +Two documents grew rather than one, because the configuration lives in three places and no +page said so. `docs/build.md` opens with **«From a clone to a working pair»** — four steps, +each one saying how much of `.env` it needs, from «the API alone, no Telegram account at +all» to the school search — and then **«The other place variables live»**, a table of the +eight secrets GitHub Actions holds with what reads each and what happens without it. The +three facts worth more than that table: `ci.yml` reads no secret at all, which is why a +fork's pull request runs the whole gate; `CRON_SECRET` is one value in two places and +**nothing checks that they match**, so a mistype is a `403` on a schedule with both halves +looking configured; and `DIARY_SECRET` is deliberately *not* an Actions secret, because +nothing there imports the server's code. `docs/README.md` gained the row that sends a reader +to the right one of the three. + +### Gates, measured on this branch + +`./gradlew test` **968** (was 964) and both assembles. The four new Android tests are +`ToolbarDragTest`: what a drag reports, where the row is drawn afterwards, what a second drag +reports, and what happens when the list is swapped under a live permutation. On the server, +`ruff` clean, `python -m mypy` clean across 84 modules, `pytest -q -n auto` **1634** (was +1630) — the four are `test_env_example.py`. Database at `0014`. + +### What nobody has verified in this batch + +**Nothing of the configuration work is proved against a real deployment.** The example file +and the two document sections are checked against `config.py` and against the workflows by +tests, which is the half that can be checked; that the eleven on Vercel are the eleven that +should be there, and that `CRON_SECRET` matches what the external cron sends, is the half +nothing here can see. + +**Still nothing on a phone.** The drag now reports the right slot in a JVM test with +Robolectric's densities and the clock held by hand; whether half a slot is the right +threshold under a real thumb, and whether the wobble is plausible, are the same two +questions #84 left open and neither has been asked of a device. The APK for #84 was built +against the code that did not work, so it is worth nobody's time — the first useful install +is the one built after this merges. + +## What the batch before added: the home screen's tabs, arranged by the person using them + +Merged as PR #84 (`1b32623`), in the milestone `v0.7.0 — Оптимизация`, three commits — +`bf80a9d` the two halves, `14f5374` the shell wiring, `05e0c47` the close-out. **Read the +batch above before trusting anything here**: the drag it describes did not report what it +computed, and the section that follows was written believing it did. Asked for +in one sentence: «сделай так, чтобы при зажатии кнопки вкладки на главной, можно было +переставить, включался режим перестановки и кнопки потрясывало как иконки на ios». +Long-press a tab on the home screen; it and its neighbours wobble; any of them can be dragged +somewhere else; the order is the reader's from then on and it is remembered. **Nothing +outside `android/` was touched**, which is why CI's server job is skipped rather than green. + +### The risky half was not the gesture + +**Everything downstream stopped holding a position and started holding a tab.** The pager's +index used to mean one destination for the life of an install; it now means whichever tab is +in that slot today, and every place that had quietly relied on the old meaning had to be +found. The scroll-offset holders are keyed by tab rather than by index — an index-keyed one +hands an arriving screen the fade depth of the one that left. The pager carries a key per +tab, so each keeps its own saved scroll instead of inheriting whatever had been filed under +«page 1». And the default tab is latched as a **tab** rather than as an index, which after a +reorder would have sent predictive-back home to a screen nobody chose. + +The shell's four back handlers became one rule in one function (`navigation/ShellBack.kt`), +which is what makes «a back press leaves the arranging mode» a thing a test can ask at all; +without it the press would have been taken by the predictive gesture and left the app. + +The bar is handed a **latched** copy of the order for the life of the mode. It was thought +load-bearing — that feeding the committed order back mid-gesture would apply the drag a +second time — and #85 made that false: the component now drops its permutation when the list +it permutes changes. The latch stays for the other reason, which is that both drags of one +session then describe permutations of the same list. + +### Two deliberate departures from iOS, each a decision rather than a shortfall + +- **The long press does not flow into the drag.** One gesture would mean a tap detector and + a long-press-drag detector on one node, and which of them sees an event turns on which + claims the press — behaviour that cannot be settled by reading, and that nothing in this + module can exercise, there being no instrumentation here. +- **A tap inside the mode closes it** rather than navigating. There is no wallpaper under a + floating bar to tap instead. + +### Three things the tests found and the code did not + +- **`IconButton` cannot carry a long press.** Material's has no `onLongClick`, and a + detector added to the modifier handed to it never fires, because it applies its own + `clickable` *after* that modifier and the press is claimed before anything passed in can + see it. It was written with an `IconButton` first, the long press simply never arrived, and + a test said so. The tab is a `Surface` with one `combinedClickable` now. +- **The drag threshold was asymmetric by a pixel.** `roundToInt` breaks a tie towards + positive infinity, so exactly half a slot rightwards rounded to one slot and exactly half a + slot leftwards to none. `dropIndex` rounds away from zero. +- **The lesson of #83's floor test decided the shape of this one.** That replacement test + kept its own copy of the arithmetic and stayed green against the very mutation it was + written for, so the drag's arithmetic is a file of its own here — + `component/ToolbarReorder.kt`, pure, pixel-facing, knowing nothing about a pointer — and + the tests call the production expression rather than a second copy of it. + +### The jiggle runs only when it is allowed to + +It runs **only while the mode is open** and **only when the reader has animation on**. The +first is not a nicety: an infinite animation means Compose's clock is never idle, so every +test that composed the bar would hang rather than fail — the trap this project has now paid +for twice. The second is that somebody who turned animation off said that about their phone, +not about this bar. Each icon is out of phase with its neighbours, because a row rotating in +lockstep reads as the bar itself flexing rather than as several things each loose in its own +right. + +### Also, and deliberately + +- **The settings default-tab picker lists the tabs in the reader's own order.** It is a + picture of the bar it is about, and two orders on one screen is a mapping exercise to + answer one question. +- **A stored order repairs itself rather than being trusted.** It is a list of member names, + and every way it can be wrong has an answer: an unknown name is dropped, a member the + string does not mention is appended in declaration order, a duplicate collapses, whitespace + is ignored, and nothing stored at all is the declared order. The appending is the clause + that matters — the day a fourth tab is added, every installed phone holds a three-name + string, and the new tab has to appear rather than the bar quietly losing it. +- **`SELF_STUDY` keeping its lessons, and the other non-decisions from #83, still stand** — + the lookahead row, `DayKindName`'s four kinds against `/bundle`'s six, the missing rule + against a composable reading `BuildConfig`, and `CONTRIBUTING.md`'s `python -m pytest`. + None of them was touched here and none of them has moved. + +### Gates, measured on this branch + +`./gradlew test` **964** (was 929) and both assembles — and see #85, which found that four +of those tests covered every part of the gesture except the one that was broken. The +thirty-five new tests are 10 on +the drag arithmetic, 5 on the reorder mode's contract, 8 on the stored order's repair, 11 on +the shell's index arithmetic and its back rule, and one pinning the default order — the bar +somebody who has never opened the setting sees, which is also what every screen gets while +the preferences file is still being read. The server half was not touched at all and +its gates stand at #83: `ruff` clean, `pytest -q -n auto` **1630**, `python -m mypy` clean +across 84 modules. The database stays at `0014`. + +The count is corrected in all three places it lives — this file's cheat-sheet, the README's +«Honest status» table and `docs/architecture.md`. + +### What nobody has verified in this batch + +**Nothing here has been seen on a phone.** Whether the wobble is plausible, whether half a +slot is the right threshold under a real thumb, and whether the two-step gesture reads as +deliberate are all unmeasured — and none of the three is a question a JVM test can be asked. +**The drag is driven from no test at all**: Robolectric reports its own densities, so a +synthetic swipe of «half a slot» would measure the environment rather than the gesture, which +is exactly why `ToolbarReorderTest` asks the arithmetic directly, in pixels, with no +composition in it. — That paragraph is the one #85 came out of. The reason is still true and +the conclusion was wrong: a drag does not have to be «half a slot» to be worth driving, and +the one that goes clean off the end of the bar answers the same under any density. + +~~**One frame at the end of the gesture can draw the pre-drag order.**~~ Closed by #85, and +by exactly the fix this paragraph priced as too risky: the component now keys its permutation +to the order it permutes, which replaces both in one step. The risk named here — silently +double-applying a drag — is the thing the key *prevents*, and there is a test that showed the +old code doing it. + +There is a second window of a frame or two, and it is inherent rather than a defect: the new +order goes out through the preferences and comes back later, so between the drag ending and +the preferences answering the pager's index still names the old order. A `LaunchedEffect` on +the arrived order closes it by putting the pager back — without an animation, which here +would be a page visibly sliding to a place it never left. + +## And before that: an audit of nine areas, and the twenty-four defects it found + +Merged as PR #83 (`3a4a924`), in the milestone `v0.7.0 — Оптимизация`, eight commits. +Eleven read-only passes first — the nine areas of `.claude/skills/audit/SKILL.md` plus +strings, documentation and a security sweep — and then the fixes. **Every one of the +twenty-four was re-verified by hand here before it was fixed, and every one is closed by +a test that was watched going red** on the code without the fix. Nothing in it is a model +change, so there is no revision and the database stays at `0014`. + +### Three a user would have hit + +**A substitution could be written onto a date that draws nothing.** The write check asked +`school_year_bounds` and the resolver asked the class's own terms, its holidays and the gaps +between them, so three kinds of date passed the check and resolved empty: past the date the +class's own «🗓 Четверти» ends on, inside the holidays between two terms, and on a public +holiday. The bot answered «Готово», the audit log recorded it, every subscriber with +`notify_changes` was told, and the row appeared on no phone, in no widget, in no calendar +feed and in no digest. **The second copy of the rule *was* the defect**, so the fix is not a +third: `off_reason_for` is module-level now and the resolver and the write check both ask +it, and the refusal names which of the three it is, because the way out differs — move a +date in «🗓 Четверти», or put an event on the day instead. + +**«🌿 Отгул» was a label with no behaviour.** It printed the word and then listed all six +lessons under it, everywhere. `DAY_OFF` clears the day exactly as `HOLIDAY` does now — the +same early return, so the kind, the note, the events and the homework stay and only the +lessons go. Three of the auditors found this independently. + +**`/find` with a long query answered nothing at all.** The needle was escaped and never cut +and the «ничего не нашлось» branch had no budget, so about four thousand characters made a +message Telegram refuses whole — and `cmd_find` is a `Message` handler, with no callback to +apologise on. With hits it was worse in a quieter way: `clamp` cuts from the end and the +oversized heading is line 0, so a search that found fifteen assignments rendered as «… и ещё +17 строк» and showed none of them. The realistic way in is the obvious one — pasting an +assignment back into `/find` to locate it. The school-search prompt had the same shape. + +### The widget, from three photographs + +**The ladder measures in dp and its type sizes are in sp**, which at the system's largest +font are about twice apart. The box still measured its full size, so the largest rung was +still chosen, and the widget drew eight timeline rows, a week strip, two homework blocks and +the next school day into the room for about half of that: «ПЕРЕ…» for the state word, chips +over a third of the surface, the last rows off the bottom edge. `of()` divides by the font +scale now — **the height, and only the height**, because height is what larger type spends +and spends in proportion, while the ladder uses width for structure. Dividing the width as +well was written first and the tests rejected it: a four-cell widget at the largest font +fell past the narrow column onto a rung with no timeline at all, so a reader who asked for +bigger type lost the rest of their school day. + +**The trailing detail starved the subject to zero width.** A `LinearLayout` measures its +unweighted children first and hands the remainder to the weighted ones, so a room number or +a teacher's name took what it wanted and the subject, which carries the weight, got what was +left. One row drew «10:50 Надежда Петро.» with no lesson on it. Two weights split the +remainder now, with the detail end-aligned in its own share. + +**The week strip's chips had no gaps, and the code said they did.** `padding` before +`background` is margin in Compose and nothing of the sort in Glance: `applyModifiers` folds +every padding in a modifier chain into one `setViewPadding` on the view the background lands +on and throws the order away, so the 1 dp meant to separate the seven days was drawn inside +their own colour and they read as one grey bar. The gap is an outer box. A `Spacer` between +them is the Compose answer and the wrong one here — seven chips and six spacers is thirteen +children of a container that keeps ten, so Saturday and Sunday would have gone missing in +silence. + +Two smaller ones from the same pass: `ellipsize` collapses whitespace before it counts, +because a Glance `Text` at one line hard-clips at the first newline and an event title typed +on two lines in Telegram reached the home screen cut with no «…» to show for it; and the +launcher's placeholder layout rounded at 20 dp against a live surface of 24, a visible step +on a cold start its own comment says can take most of a minute. + +### Three of this project's own guards did not hold what they claimed + +This is the half worth carrying forward, and one of the three was written by the batch +below. + +- **`test_test_imports.py` matched one of two spellings.** It refused `from tests.x import + …` and not the bare `from x import …`; six live test modules used the bare one and the + guard stayed green. They pass today only because pytest's default import mode puts + `tests/` on `sys.path` — under the mode pytest now recommends, three of them die at + collection with the exact error the guard exists to prevent. The shared fakes have moved + into `conftest.py`, which is where the guard's own docstring said they belonged. +- **`DeviceClockTest` listed module paths and filtered them by `isDirectory`**, so a + renamed or moved module drops out of the scan in silence while the test stays green on the + rest. Its own KDoc records that `:core:designsystem` was left out by accident once, that + it is the module where the last clock-shaped defect landed, and that + `ResourceTranslationTest` had the same hole for the same module — and the recurrence was + unguarded by the very `filter` that would do the dropping. It discovers modules now. +- **`NarrowLabelBudgetTest` allowed two characters more than the column holds**, with no + derivation, and `+ 2` was exactly the current data: «Homework today» is fourteen against a + budget of twelve, on the ceiling with nothing to spare, under a comment saying the title + should be *shorter* than the column. Glance cannot ellipsize, which is that file's whole + premise. The English string is what moved — a test tightened onto a string that does not + fit is a test reporting the defect it was written to prevent. +- **`test_the_entry_point_exists_where_vercel_json_says_it_does` never read `vercel.json`.** + It checked a hardcoded path, so the file going missing was caught and the two drifting + apart was not, which would silently drop `maxDuration: 30` under a name promising + otherwise. +- **And my own floor test from #82 was wrong twice over.** The 6 dp floor is unreachable + from any rung, so walking the ladder cannot tell the floored expression from the unfloored + one — and the first replacement kept its own copy of the arithmetic and stayed green + against the very mutation it was written for. `innerCornerFor` exists so a test can call + the production expression with a padding the enum does not have. + +**Plus the guard that did not exist.** `MarqueeText` runs `Int.MAX_VALUE` iterations, so +Compose's clock is never idle and a test that composes an overflowing line **hangs rather +than fails**, taking the whole Gradle run with it. Twenty-two of twenty-five Compose test +classes compose a component that can draw one, and the rule was held by a KDoc. They pass +today only because Robolectric lays text out without fonts at about a pixel a glyph, so +nothing overflows; the day a label grows, CI stops for forty-five minutes and says nothing. +`MarqueeClockTest` walks every file that calls `createComposeRule`, and each of the thirteen +that neither holds the clock nor could overflow says in its own words why not — per file, +because an exemption in bulk is a KDoc again. + +### The rest of the server half, and the sync layer's three false promises + +Four more on the server. **One superscript digit could take down the whole «Дневник» +screen**: `mapper.number()` did a bare `int()` on a string it had only checked with +`isdigit()`, and a `ValueError` is not a `PetersburgError`, so it walked past the guard that +exists to drop one unreadable row and the phone got a bare 500 while the bot's button spun +for ever. **The schools registry could not say its own shape had moved** — an unreadable +suggestion was logged at `debug` against a logger at `info`, so a DaData restructure looks +exactly like a school that is genuinely not in ЕГРЮЛ. And two comments in applied revisions +were wrong about the library rather than about this project: `sa.Enum(native_enum=False)` +emits no CHECK on SQLAlchemy 2.0, so the lower-case value lists in `0003` and `0008` are +inert and could never have rejected the upper-case names the ORM writes. **No DDL changed.** + +In `:core:data`, three of the four findings are a written claim that stopped being true +rather than a wrong screen — nothing was broken for a user today and a reader of the code +would have been told the wrong thing four times. **A bundle `ETag` outlived the class it +described** (`forget` had one caller, eviction, so leaving a class dropped its rows and kept +its tags for the life of the install), fixed structurally: `SessionRepositoryImpl` no longer +holds the DAO, it takes a narrow `TimetableCache` implemented by the repository that owns +the tag store, so joining, leaving, signing out and the worker's sweep all go through the +one object that can drop rows and tags together. **`syncedAtEpochMillis`'s KDoc named it as +the eviction rule** while eviction sorts by distance from the current year — two documents +in one repository giving opposite rules for one decision. And **`deleteLookaheadOf` was the +one delete in the DAO leaning on `PRAGMA foreign_keys`**, against a file whose `clear` says +in so many words that the wipe must not, with the in-memory fake *more* thorough than the +real query so no unit test could see it; a source-reading test now parses every `DELETE FROM +school_day` out of the DAO and demands the matching child statements. + +### The calendar, and the deployment that could not create its own schema + +Four findings in `:app`. **«День» → «Список» blamed a filter nobody had set**: on a year this +phone has not fetched it said «Ничего не подходит», with no chip selected, and said the same +thing while the year was still arriving — the exact distinction `synced_window` exists for, +and the other three surfaces of that tab already made it. **The list scrolled something +nothing reported**, so switching modes left the status-bar blur wearing the ribbon's stale +value over a list at its top. **The period arrows announced «неделя» in four of the five +modes** — the header text was right and only the content descriptions were left behind, so +TalkBack said «Следующая неделя» over a button that steps a day, or a month; +`ScheduleView.stepOf(dayMode)` is one answer now, and the test pins the moved date and the +spoken unit *separately*, because a test that only asked whether they agree would stay green +for ever once they share a function. And **«О приложении» drew the schema and not the +expectation**, so «база отстала» and «база впереди кода» — opposite mistakes with opposite +fixes, in the type's own words — looked identical. Both chips now; `detail` stays undrawn on +purpose, because it is the server's Russian sentence and that card is read in two languages. + +**`docker compose up -d --build` brought up a Postgres with nothing in it.** It is three +commands in `docs/deploy.md`; `app.main` calls `create_all` only for SQLite, the image +carried neither `migrations/` nor `alembic.ini`, and the one in-image alternative, +`python -m scripts.init_db`, refuses a non-local URL by design. What the reader saw was +worse than a failure to start: the container came up, `/api/v1/health` answered green +because it opens no connection, and the first ORM read failed — which for the bot is the +middleware, so every update died at once. The revisions ship in the image now and a one-shot +`migrate` service runs `alembic upgrade head` before the server is allowed to start: a +service rather than a line in the server's command, so a failed migration stops the stack +instead of being buried in the API's log and `docker compose run --rm migrate` is something +a person can do by hand. It takes only `DATABASE_URL`. + +One more that cost several thousand untracked files: **`.gitignore` spelled the virtualenv +`.venv/` exactly**, so an audit pass building `.venv_audit` beside it offered the lot for +commit. This repository is public and an environment committed by accident is expensive to +take back out of the history. + +### The documents, brought level + +Fourteen files, every number re-measured rather than copied. The Android total was 849 +against a real 929, `:core:designsystem` 74 against 80, `:widget` 74 against 90, `:app` 305 +against 357, `:core:model` «ninety-four tests in eight classes» against 117 in ten, and the +server count was quoted as 1559 in one document and 1610 in two others while it is 1630. +Two documents disagreed with themselves: `docs/build.md` said at the top that no workflow +asks for an artifact retention and thirty lines later that «artifacts live a week» — the +fourth place to quote the wish rather than the setting, in the file already corrected once — +and `architecture.md` gave `:core:model` two different test counts nine lines apart. The +descriptions that had gone false: «День» and «Лента» are one tab, and four documents still +described «Лента» as a separate view, one of them the guide the app itself serves. Two rules +had been written in code comments and nowhere else, and both span three modules, so +`docs/design.md` is where they now live: the concentric-rounding rule with the four places +it deliberately does not apply, and the day's two readings with the arrows stepping a day in +one and a month in the other. + +### What was deliberately left alone, and each is a decision rather than an oversight + +- **`SELF_STUDY` keeps its lessons.** «Эти уроки, но дома» is a reading nobody has ruled + out, so `DAY_OFF` was brought into line with `HOLIDAY` and self-study was not — and a test + records that as a decision, so the next person has to change a test that explains why + rather than a line that looks like an omission. +- **The lookahead row is neither fixed nor removed.** The server resolves `next_school_day` + at most 21 days past the last lesson *inside the window asked for*, and since the window + became a whole school year that lands in June — out of season for every class, so the + field comes back null on every bundle this app asks for. Making it work means resolving + from the window's end and about a hundred days of lookahead, paid by every phone on every + sync, for a row that matters in the last days of May; removing it means a Room version + bump under `fallbackToDestructiveMigration`, which wipes the cache on every installed + phone. All five places that described it now say so, and what answers «what is next» + across a gap is `firstTeachingDayAfter` over the cached year. +- **`DayKindName` accepts four day kinds while `/bundle` can return six**, so a phone cannot + write back the value the server just sent it. Found, verified and written into + `docs/api.md` out loud; not fixed, because widening the accepted set is a contract change + and belongs with whoever decides what a phone may set a day to. +- **Four composables read `BuildConfig` directly and nothing stops a fifth**, which is + exactly how #81 happened. The guard is a source-reading test and belongs with the rest of + the meta-tests; this batch added the marquee one and stopped there. +- **`CONTRIBUTING.md` still recommends `python -m pytest -q`**, which `CLAUDE.md` warns + against by name — the `-m` form puts the current directory on `sys.path` and is the reason + a `from tests.… import` passed locally and failed at collection on CI. Its numbers were + corrected in this batch and its command was not, because that line is a contributor-facing + choice rather than a stale fact. +- Also left: the day sheet ignoring `isFetched`, and a widget day-tap landing on a month + when the stored mode is «Список». + +### Gates, measured on this branch + +`ruff check` clean, `python -m mypy` clean across 84 modules, `pytest -q -n auto` **1630 +passed** (was 1610), `./gradlew test` **929** (was 896) — `:core:model` 117, +`:core:designsystem` 80, `:core:data` 285, `:widget` 90, `:app` 357 — and both assembles. +CI was green on `3c7a2f5`; the two commits after it are the documents and this close-out. +The database stays at `0014`: **no migration was needed and none was applied.** + +### What nobody has verified in this batch + +**Nothing of the widget's fixes has been seen on a launcher**, and that is the surface this +batch changed most — the tests reproduce the arithmetic and the budgets, not the rendering, +and the two claims about what Glance does with a modifier chain come from reading its +translator rather than from pixels. **No Compose test was actually made to hang**, so +`MarqueeClockTest` is reasoned from the marquee's iteration count and the call-site list. +**`docker compose up` has never been run** — there is no Docker here — so the compose file +is parsed and its dependency conditions asserted rather than watched. **`/api/v1/warmup` is +unreadable from here**, because the deployments answer a redirect to a Vercel login page. +The diary has still never been opened for real, so the mapper fix is proved against a +fixture rather than against the upstream that would send such a row; and the tag sweep's +prefix arithmetic is written and not run, because `LessonsPreferences` needs a `Context` and +`:core:data` has no Robolectric. + +## What the batch before added: the rounding rule, applied everywhere it is actually true + +Merged as PR #82 (`c7767c8`), in the milestone `v0.7.0 — Оптимизация`. One sentence of a +request — «"Подложка вкладок — зазор скруглений одинаковый по периметру." — исправь все +подложки по приложению» — and most of the work was deciding where it does *not* apply. + +**The rule.** Two nested rounded rectangles look right for exactly one pair of radii: the +inner radius plus the padding equals the outer one. Any other pair leaves the gap wider at +the corner than along the edge, which reads as a wonky corner rather than as a wrong +radius — easy to see, hard to name. #80 applied it to the segmented picker and stopped +there. + +**Where it applies is narrower than «все подложки».** It needs two rounded rectangles +nesting *with a gap*. Every shape in `:app` and `:core:designsystem` was read against that +test and exactly one more place in the product qualifies — and it is the one where the rule +matters most, because there the gap is not one number. + +### The widget was wrong by a different amount on every phone + +`WidgetCard` was a flat `18.dp` and the pill behind the current lesson a flat `12.dp`, both +drawn straight onto a surface of `24.dp`. What separates them is `WidgetSizeClass.paddingDp`, +which runs from 8 dp on the smallest rung of the twelve-rung ladder to 16 dp on the largest. +So the gap was even at **no size at all**, and worst where the widget is biggest: at 16 dp of +padding a concentric block wants 8 dp and it drew 18, more than twice as round as the +surface around it can carry. + +`WidgetSizeClass.innerCorner()` derives it per size class now, with a 6 dp floor. The floor +is the interesting half: square is the *honest* answer for a rectangle inset past the curve, +and wrong here, because the rows beside it are rounded and one square corner among them +reads as a rendering fault rather than as a decision. `WidgetSurfaceCorner` moved in beside +it — two numbers that have to agree belong in one place. Glance takes a `Dp` and nothing +else, so this is `concentricCorner`, the arithmetic form, next to `ConcentricShape`, which is +the same rule deferred to draw time when the inner radius is a percentage of a height nobody +has measured yet. + +### What was deliberately left alone, and it is most of the survey + +Each carries its reason in the file, because the next reader will ask exactly this. + +- **The seven weekday chips.** The strip sits in the middle of the layout, so its corners + are next to other rows rather than in the surface's rounding: no corner nested in a + corner. A chip is also about as tall as the radius the rule would hand it, which is a + pill, not a chip. +- **`RoundedCardContainer` and its rows.** The rows are *clipped* by the container rather + than padded inside it. No gap, no rule — and that flush clip is exactly what makes a group + read as one slab instead of a pile of cards. +- **The hero card's tile and every `Pill`.** `RoundedCornerShape(percent = 50)` is a circle, + not a nested rectangle. +- **«О приложении».** It opens and closes with centred text, so nothing it holds has a + corner in a corner — and its horizontal and vertical paddings differ on purpose, while a + concentric corner is only defined for one gap. + +**Verified, and not.** `./gradlew test` **896 tests**, up from 891, and both assembles. +`WidgetInnerCornerTest` is five, and two were shown red against the old flat 18 dp before +being trusted. One of those two was written `<=` at first and passed against the very +constant it was meant to catch; it asserts a **strict** inequality now, between every +adjacent pair of size classes whose paddings actually differ — and that the ladder really +carries more than one padding is itself a test. **Nothing here has been seen on a launcher**: +the tests reproduce the arithmetic, not the rendering, and `cornerRadius` is a no-op below +API 31 in any case. + +## What the batch before added: a test that asserted its own build's configuration + +Merged as PR #81 (`28f6ea3`), in the milestone `v0.7.0 — Оптимизация`. One defect, found +the way this kind is always found — by the thing it broke rather than by anything reading +the diff. + +**The APK workflow could not build an APK.** The first `apk.yml` run after #80 merged died +at `:app:testDebugUnitTest`, on a test #80 had added: `AboutCardTest > a build that was +told nothing about itself says that rather than nothing`. It read +`BuildProvenance.current()`, which answers with whatever *this* build was told — so it +asserted a property of the build configuration rather than of the card. + +It passed everywhere it was run and failed exactly where it mattered. `ci.yml` sets none of +the five `LESSONS_BUILD_*` properties, so `current()` came back empty, the card drew +«Собрано вручную» and the assertion held — on every pull request, including the one that +introduced it. `apk.yml` sets all five, because naming the commit an APK came from is what +they are *for*, so the badge the test demanded was correctly absent. + +**The workflow whose entire job is to produce an APK was the only thing that could see it, +and it saw it as a failing string on a settings page.** + +The provenance is a parameter now, defaulted to `current()` at the single call site, and +`AboutCard` is `internal` with it. The ordinary fix — and it buys what the old shape could +not: the badges are testable at all. Three tests replace one, including the contradiction +that was previously unreachable (a card claiming both a commit and «собрано вручную»). + +**Deliberately left alone, and it is the part worth carrying forward.** Nothing enforces +this shape. Another composable reading `BuildConfig` directly would reintroduce exactly +this, would again be green on every pull request, and would again be red only in the +workflow nobody runs on a pull request. A rule forbidding `BuildConfig` outside a +provenance type would be the real guard; it is not written, and writing it was not worth +widening a one-defect batch. The gap in the gate is structural: **`ci.yml` cannot catch +this class and should not try** — it does not build an APK anybody installs, so the +difference only exists in a workflow run by hand. + +**Verified, and not.** `./gradlew test` **891 tests** in *both* environments — with the +five properties exported and without them, because only running both tells them apart — +and both assembles. The red case was reproduced before the fix and shown green after. + +## What the batch before added: six things that drifted on a real screen + +Merged as PR #80 (`9b8eba7`), in the milestone `v0.7.0 — Оптимизация`. Six reports from one build on a +phone, plus a lie the previous batch's own CI log had been printing all along and nobody +had read. + +### The retention was wrong in four places at once + +The repository's artifact retention is **one day**. `apk.yml` asked for ninety, `ci.yml` for +a week, `docs/build.md` promised both numbers and `CLAUDE.md` a third. Every run reduced +them and said so — `##[warning]Retention days cannot be greater than the maximum allowed +retention set within the repository. Using 1 instead.` — in a job nobody opens when it is +green, in a sentence that reads like a build problem. + +No workflow asks for a number any more: the repository setting is the only thing that +decides, so there is nothing left for a workflow to disagree with, and the summary says +where to raise it. Worth keeping as a shape: **a wish written next to the thing that +overrides it is not a setting**, and three documents had been quoting the wish. + +### A marquee that stopped after three passes + +Reported as «на некоторых лейблах не двигается, а на некоторых двигается, даже на одном +экране», and the diagnosis that invites is wrong. The line *is* a marquee — it is clipped +mid-glyph with no «…», which is `TextOverflow.Clip`, which this component only sets when it +has decided to scroll. It had simply spent `MarqueeDefaults.Iterations`, three, and parked +itself back at the start. The budget is per composition, so a row just scrolled into view +moves and a row that has been there a while does not. + +**The cost of fixing it is a perpetual animation, and that is not free in tests.** Compose's +clock is then never idle, so `waitForIdle` — which every assertion calls into — hangs rather +than fails. It is the same trap `runTest` against `WeekViewModel`'s clock cost a whole +Gradle run for. Three suites now hold the clock and advance it by hand; a new test that +composes an overflowing line and forgets to will hang, and the note is in `MarqueeText` and +in each of them. + +### «Календарь» wrapped after «Календар» + +The title shared one `Row` with a year chip and three icon buttons under `weight(1f)` — +about eight characters at 411 dp — so the «ь» went to a second line and the subtitle to a +third. Nothing about it looks wrong in the code: `weight(1f)` is the correct way to share a +row, and the row was asked to hold more than it has. Title on its own row now, controls on +theirs. + +The second half was movement rather than wrapping: «сегодня» is offered only when it would +do something, and while the *button* was what appeared, both arrows slid 48 dp sideways +every time the reader stepped into or out of the current week. The slot is kept whether or +not the button is in it. + +### The picker's tray was rounded by a token rather than by its buttons + +24 dp — `LessonsShapeTokens.Group`, the radius of a group of *rows* — around Material's +connected button shapes with 4 dp of padding. Three numbers chosen in three places, so the +gap between the two curves was wider at the corners than along the edges, which reads as a +wonky corner rather than as a wrong radius. `ConcentricShape` computes it: inner radius plus +padding, the one outer radius that keeps the gap even. A `Shape` rather than a computed +`RoundedCornerShape`, because Material's connected corners are a percentage of the button's +own height and the answer is only known once the tray has been measured — which also makes +it a pure function of a size and a density, and therefore testable. + +### «День» and «Лента» are one tab + +Asked for, and asked about first: the literal reading of the request removed the immersive +ribbon entirely, which is a feature the owner had commissioned in detail two batches +earlier, so it was worth one question. The answer was to merge rather than replace. + +They were never two views — both answer «что идёт», one for the day in front of you and one +for the month around it — and four four-letter labels across a 360 dp phone was most of what +the picker's marquee was doing its work for. `DayMode` switches them on the screen itself +and is stored like the ribbon's other three settings. **The two modes cover different +spans on purpose**: the ribbon is one date, because it draws the breaks between lessons; the +list is the month, because «в какой день больше всего» is a question about a stretch. So the +arrows step a day in one and a month in the other, which is what each mode already implies. + +### The about card, and where a build came from + +It was padded twice — once by the settings list's `contentPadding`, once by itself — so it +came out 32 dp narrower on each side than every group above it, and its two link buttons +broke «Essentials» into «Essent / ials». Full width now, one button per row. + +The badges say two things nothing else in the app can. **How the bound server answered**, +including the state that is invisible from everywhere else: API up, database at a different +Alembic revision, which is the window between a merge deploying itself and the migration +being applied by hand — `/health` is green all through it. And **which repository, ref and +commit this APK came from**, with the commit chip opening that exact diff. + +That needed five build properties, because **a build keeps no memory of its own checkout**: +an APK cannot work out its repository, branch or commit unless whatever ran the build says +so. `apk.yml` fills them from the runner's own `github.*` rather than from repository +settings, so a build of a fork describes itself honestly. `BuildPropertyReachTest` already +existed for exactly this class of mistake and earned its keep in the same hour: it caught +`LESSONS_BUILD_TIME` being `export`ed inside the run script, where nothing outside the step +can see it. + +**Deliberately left alone.** Material's three iterations exist so a screen is not in +perpetual motion, and this batch chose readability over stillness for lines that cannot be +read any other way. That is a trade rather than a fix, and if a list of long titles turns +out to be unpleasant the answer is probably to shorten the titles. + +**Verified, and not.** `./gradlew test` **889 tests**, both assembles. The card, the header +and both link buttons are asserted **displayed** rather than merely composed, which is the +lesson of the batch before. The server half was not touched; its gates were last green at +#77 — `ruff` clean, `pytest -q -n auto` 1610, `python -m mypy` clean across 84 modules. +**Nothing here has been seen on a screen**: whether the concentric corner looks concentric, +and whether a marquee that never stops is pleasant, is unmeasured. **The server badge has +never been drawn against a real server** — `ServerStatus` is exercised from a fake and no +test opens a socket. + +One note for whoever writes the next Compose test here: **`performScrollTo` drives the +scrollable's animation.** With the clock held for the marquees it moves nothing, and every +node below the fold reports «not displayed» — which is indistinguishable from the element +being absent, and cost two rounds here. Give the test a tall window instead. + +## What the batch before added: the three defects the first real build had in it + +Merged as PR #79 (`a1f2392`), in the milestone `v0.7.0 — Оптимизация`. Not a feature. #77 +shipped a screen +that crashed on opening, and this is the batch that reads the report and closes it — all +three defects are mine, all in `DayRibbonView.kt`, all introduced in #77. **None of them +would have fixed itself**: #78 changed the cache and the calendar and never touched that +view, which is what the report assumed it would. + +### A key that was never interpolated + +`RibbonEntry.identity()` read `"lesson/${'$'}startsAt/${'$'}{lesson.index}"` — Kotlin's +escape for a *literal* dollar — so every lesson row carried the same constant string, every +event row another, every break row a third. `LazyColumn` throws the moment it measures the +second row of a kind, which is every school day there has ever been. The line was written +through a shell heredoc that escaped the dollars, and nothing ever read the result back. + +### The rows were unreadable because the fade was sized for a screen + +The ribbon is handed the height left under the header and the picker, and it put a fixed +48 dp `progressiveBlur` fade at each end of it — on a phone held sideways, 96 dp of about +150. Worse, `progressiveBlur` paints a 65 % wash of the surface colour under each fade and +**the shell already does exactly that to the whole page**, so the ribbon stacked a second +one inside the first. The fade is a share of *this* view now (`ribbonEdgeHeight`, 12 %, +capped at 48 dp) and carries no tint of its own. «Ничего не было видно, из-за соотношения» +is precisely the shape of that bug: the shorter the view, the more of it was curtain. + +### And the camera distance was multiplied by the density + +Which is the trap `SchoolBell.kt` already carries a paragraph about: the unit goes straight +to `RenderNode` and is density-independent, so scaling it put the camera several times +further away than the default and flattened the tilt by a different amount on every phone. +A second use written without reading the first — the one thing `CLAUDE.md` asks for by name. + +### What the logs settled + +The owner installed the APK of #77 (`versionCode` 24, Room at v4) and sent back a full +Android bugreport — **the first time any of this code has been looked at running on a phone +rather than on a runner**. It is worth knowing what it did and did not contain. + +Six fatal exceptions are in it. Three are SwiftKey's; the other three are ours, and all +three are the same `IllegalArgumentException: Key "lesson/$startsAt/${lesson.index}" was +already used` — the platform quoting the defect back with the dollars still in it. Two on +opening the day, and **the third is the rotation**: `WindowManager` logs +`changed={CONFIG_ORIENTATION}, not-handles={}`, so `MainActivity` handled the change +without being recreated, and what rotation did was re-measure at the new height — the same +duplicate key, at the same place. That closes the question #79's body left open: rotation +is not a fourth defect, it is the third occurrence of the first one. + +Nothing else of ours is in it. No ANR, no exception out of `:core:data`, no SQLite or network +error, and no crash dialog of our own — «снова предлагало сбросить кэш» is the platform's +prompt after a crash, not a screen this app has. The `SQLiteOpenHelper: DB version upgrading +from 3 to 4` line is the cache being dropped and refilled, which is what +`fallbackToDestructiveMigration(dropAllTables = true)` is there for. + +**One thing in it is unexplained and is written down rather than guessed at.** Eighteen +times over seven minutes the app logged `AdrenoVK-0: Shader compilation failed for +shaderType: 4` followed by `Pipeline create failed`, on the render thread, spread across +screens rather than clustered on the ribbon — and **no other app on that device logs it**. +At Android's `I` level, with no shader source and no reason attached, and with nothing the +owner reported that maps to it, there is no fix to write from here; it is a real signal and +it is unclosed. Whoever looks next should start by asking whether the AGSL sheen is the +source at all, since a failure in `RuntimeShader` would normally throw in-process instead. + +### The test that was missing, and the two screens nobody had drawn + +`DayRibbonLayoutTest` composes the ribbon for real, inside the `Column` with a `weight(1f)` +that `RibbonPage` puts it in, at a portrait height, at a landscape one, and at one shorter +than the fades themselves — and asserts the rows are **displayed**, not merely that nothing +threw. It fails on the first run against the shipped code, which is the only reason to +believe it. + +That distinction is the lesson of this batch. The day ribbon shipped with three test suites, +all passing, and **not one of them ever drew it**: `DayRibbonTest` covers its arithmetic, +`RibbonFocusTest` where the focus button lands, `RibbonDepthLevelTest` which devices get the +shader. A screen that is built and shows nothing passes every test that only asks whether it +was built. So the other two screens of that batch are drawn here too, before somebody else +has to find them — the **year picker** and the ribbon's **settings sheet**. Both turn out to +be fine, which is worth writing down rather than assuming. + +**Deliberately left alone.** The 12 % share is a judgement and not a measurement: it keeps +both fades under a quarter of the view at every height, which is the rule that was missing, +but nobody has looked at whether 48 dp is still the right maximum on a tall screen. + +**Verified, and not.** `./gradlew test` **863 tests**, both assembles; two of the three +fixes proved red first — restoring the constant key fails `DayRibbonLayoutTest`, restoring +the fixed 48 dp fade fails two of `RibbonEdgeHeightTest`. **The camera distance has no +test**, and that is not an oversight to close later: what it changes is how deep the tilt +looks, `cameraDistance` is written straight onto a `RenderNode`, and nothing on this side +can read it back. It is held by the comment in both places that set it, which is a weaker +guard than a test and is the honest description of it. The server half was not touched and its gates were +last green at #77: `ruff` clean, `pytest -q -n auto` 1610, `python -m mypy` clean across 84 +modules. **What the fixes look like is still unseen** — the log proves the crash was what +this batch says it was, and proves nothing about the tilt, the blur or the shader. The next +APK is also the first to carry a Room schema of 5, so its first run on that phone drops the +cache and re-syncs a year. + +One note for whoever writes the next Robolectric test against a screen in a `weight(1f)`: +compose it **inside the box the real page gives it**, not at `fillMaxSize()`. Every defect +in this batch is a measurement, and a test that hands the view the whole window reproduces +none of them. + +## What the batch before added: a cache that holds more than one school year + +Merged as PR #78 (`559b306`), in the milestone `v0.7.0 — Оптимизация`. One item, and it is +the one #77 wrote down as a decision the owner had to make: **scrolling the calendar by +years**. They +chose the honest option — a sync windowed on demand — over binding a picker to the year +already synced, which would have scrolled to a year with no days in it. + +### The invariant that had to go + +The cache held exactly one window per class, and `replaceAll` wiped that class's rows on +every sync. So scrolling into another school year could not work at all: arriving would +have destroyed the year being left, and coming back would have destroyed the one just +fetched. Every date outside the one window read «Нет данных» — on screen the same thing as +a week with no lessons in it. + +A window is a school year now, named by the year it opens in, and `replaceWindow` replaces +one of them. `synced_window` is a table rather than something counted off the days present, +because **a year fetched and genuinely empty has to be tellable from one never fetched** — +a class made in March has no rows before it either way, and counting would leave the +calendar on a spinner that never stops. + +**The server needed nothing.** `/api/v1/bundle` has always taken an arbitrary `start` and +up to 280 days, and a school year is 274. The whole batch is Android. + +### What fell out rather than being added + +The Monday anchor is gone with the whole-class wipe that was its only reason, and its +summer bug with it: applied in July it reached back far enough to ask for some 320 days, +past what the server accepts, and the window came back silently clipped in April. +`refresh` lost its `days` — a parameter nothing could honour, threaded through +WorkManager's input data to be ignored. And the `ETag` store keeps a tag per window, +bounded by the cache's own cap rather than a second rule. + +### Three defects the tests found and the code did not + +1. **Eviction by fetch time was not a rule.** It is not «least recently used» — a year + revisited and unchanged answers `304`, which touches the class row rather than the + window's — and it ties, so four years fetched inside one millisecond left the order to + the query, which returns the newest year first, so the year just asked for was thrown + away. It goes by distance from the year holding today now, which is clock-independent. +2. **A year asked for while another was in flight was dropped and never retried**, because + the period had not changed since. It works because the collector *awaits* each fetch: + one coroutine, so a request in flight parks the collector, and a `StateFlow` conflates, + so what it resumes on is where the reader ended up. Launching each fetch instead is the + obvious-looking change, and it is what the test now fails on. +3. **An «already in flight» guard that could never fire**, for the same reason — removed + rather than left as a claim about the code that stops being true silently. That is the + second unreachable guard this session found; the first was in the day ribbon. + +### On screen + +A «2026/27» chip in the header opens a picker of five school years, each marked «загружен» +or «не загружен». Nothing has to be pressed: the calendar fetches the year it is scrolled +into, whether it was stepped to, tapped to, picked or opened from the widget — one +collector watching the period actually drawn, both ends of it, because a week can straddle +31 May. And a day now says which kind of empty it is: «нет уроков», «загружаю год» and +«год не загружен» were one sentence before. + +**Deliberately left alone.** Three years per class, which is a number rather than a +measurement: the question a calendar is asked reaches about one year either side of the +one it is in. Nobody has watched what four or five costs on a phone, and the constant is +one line (`MAX_YEARS`). + +**Verified, and not.** `./gradlew test` **849 tests**, both assembles, and every guard +proved red first — the old whole-class wipe fails two, letting any year write the lookahead +fails a third, dropping the lookahead exclusion fails a fourth. The server half was not +touched and its gates were last green at #77: `ruff` clean, `pytest -q -n auto` 1610, +`python -m mypy` clean across 84 modules. **Nothing has been seen on a screen** — not the +chip, not the picker, not what a school year takes to arrive over a school's wifi, and not +what three years of rows cost a `LazyColumn` that re-reads them on every write. + +One note for whoever writes the next test against `WeekViewModel`: **do not use `runTest`.** +It shares its scheduler with `Dispatchers.Main` when Main is a test dispatcher and then +drains every pending delay by advancing virtual time, which against this view model never +finishes — its clock is `while (true) { emit(now); delay(30s) }`. It hung a whole Gradle +run once. + +## What the batch before added: the school's own dates, the calendar, and a day you can scroll + +Merged as PR #77 (`ddfd305`), in the milestone `v0.7.0 — Оптимизация`, eighteen commits. Three parts: a +defect reported from a real class, the calendar the owner asked for on top of it, and the +day screen that calendar leads to. + +### The dates an admin typed decided a term's name and nothing else + +«2 полугодие» was given an end of 28 May 2027 in «🗓 Четверти». The phone, scrolled to May +2027, still drew a full day of lessons on the 29th, the 30th and the 31st — after a manual +refresh, and after leaving the class and re-joining it with a fresh code. Neither could have +helped: **the server was sending exactly what it meant to.** `_resolve_day` asked +`school_year_bounds`, which is `SCHOOL_YEAR_END_MONTH` — 31 May, and always will be. + +It was mis-diagnosed twice here before it was found, and the way it was found is worth +keeping: the transport was proved correct end to end (the bot's write, the `ETag`, the +phone's `replaceAll`, the flow) and the app turned out to have **no screen that draws a term's +dates at all**. Only the owner's answer — «судя по трём точкам, прокрутив календарь до мая +2027» — said what was actually being looked at. The two round-trip tests written during the +wrong diagnosis are kept as regression guards and labelled as guards rather than as the fix. + +The horizon now comes from the class's own `Term` rows, and the gaps **between** terms are +out of season by the same rule — which is how the autumn holidays are described by moving +two dates rather than by marking nine days. + +### The calendar + +`services/holidays.py` holds fourteen statutory non-working days and twenty-five +observances, apart because they behave differently: a statutory day stops the lessons, +«День учителя» is a full Wednesday with a badge. **The yearly transfers are deliberately +absent** — they are set by decree each December, and a wrong non-working day removes a real +day of teaching while looking exactly like a correct one. + +Every day carries `off_reason` (`out_of_year`, `between_terms`, `public_holiday`, or +nothing) **beside** `kind` rather than inside it, so an older client draws what it drew +before. The month grid gives each reason its own accent, joins consecutive days of one +reason into a single band, and writes «Летние каникулы» across a month with no teaching in +it. A range can be marked self-study, remote or a day off, not only as holidays. The +calendar filters and the order are in both shells — the chips and «по загруженности» in the +app, the same narrowing in the bot's list of marked days — and the month can be read as a +list, which is the one view an order can apply to at all. + +### «Календарь → День» is a ribbon now + +The hour ruler is **gone**, not kept beside it. It drew the day by position, so a forty-minute +break was forty minutes of blank screen: nothing to read, nothing to press, two clocks to +subtract. The day is flattened into a `Ribbon` in `:core:model` — lessons, events, and the +gaps as rows of their own — and every row says when it runs, how long for, and where the +clock is inside it. The widget's `remainingTimeline` is that ribbon filtered now rather than +a second copy of the merge and its tie-break, which nothing had ever tested. + +The view owns the page's height instead of adding to its length, which is what the magnetism +and the tilt both need: a list can only snap, and a card can only lean away from the middle +of the screen, if the list *is* the viewport. Three settings are the reader's, stored rather +than remembered — which way the progress runs, whether the scroll settles on a whole row, +whether the cards have depth — and they live in a sheet on the screen itself because all +three show what they do the moment they are pressed. + +The depth is a ladder of three: AGSL lights the running row where its clock has got to on +Android 13 and above, everything from `minSdk` 26 up to Android 12 keeps the gradient and +the perspective tilt, and off is off at every version. `ribbonDepthLevel` is a function of +the API level rather than an `if` at the call site, so all ten versions this app installs on +are checked by a test instead of whichever one the runner emulates. + +### What CI caught that the local gate could not + +`CLAUDE.md` documented the server gate as `python -m pytest`; **CI runs the bare `pytest`.** +The `-m` form puts the current directory on `sys.path` and the bare one does not, so +`from tests.test_api import _token` passed here and failed at *collection* on CI. Fixed in +three layers: the import is gone, a test now refuses any test module importing another, and +the documented command is the one CI runs. + +**Deliberately left alone.** Scrolling the calendar **by years** is not in this batch and is +not a refusal — it is blocked on a decision only the owner can make. The phone's cache holds +**one school year** by construction: `SchoolYear.boundsAt(today)` picks the window, +`TimetableDao.replaceAll` wipes the class's rows on every sync, and the server caps a bundle +at `MAX_BUNDLE_DAYS = 280`. So either the year picker is bound to the synced year (cheap, +and very nearly useless — it would scroll to a year with no days in it), or the sync becomes +windowed on demand, which breaks the one-window-per-class invariant and touches `replaceAll`, +the Room schema and the `ETag` signature. The second is a batch of its own and the wrong +thing to start without being asked. + +**Verified, and not.** Both halves of the gates are green: `ruff` clean, `pytest -q -n auto` +**1610 passed**, `python -m mypy` clean across 84 modules, `./gradlew test` **830 tests**, +both assembles. Every fix was proved red first by mutating the implementation. **Nothing in +the calendar or the day screen has been seen on a screen** — not the four accents beside one +another, not the summer's tint across sixty cells, not the tilt, and not the shader, whose +cost on a mid-range phone is unmeasured. The new day kinds have not been pressed in a real +Telegram. The Vercel preview is behind SSO, so nothing could be checked against a running +server either. + +## What the batch before added: an audit of the whole project, and a typeface that can draw it + +Merged as PR #76 (`01f7a30`), in the milestone `v0.7.0 — Оптимизация`. Twelve agents swept the +nine areas of `.claude/skills/audit/SKILL.md` plus documentation, strings and access, +read-only; every finding below was then re-verified by hand here and closed by a test proved +red without its fix. What was found is larger than what is fixed, and the rest is listed at +the end rather than quietly dropped. + +### The app shipped a typeface that cannot draw Russian + +**Google Sans Flex has no Cyrillic. Not a dropped subset — none.** Its coverage metadata on +Google Fonts lists latin, latin-ext, vietnamese, math, symbols and five scripts nobody here +writes, and zero code points in U+0400–U+04FF; `&subset=cyrillic` returns an empty answer. +This app's product language is Russian. So every Russian word was drawn by the device's +fallback face while the digits and Latin beside it came from the bundled file — two +typefaces in one row, at different x-heights — and «системный шрифт» was close to a no-op +for the only language on the screen. It had been that way since the design system was taken +from Essentials, which is an English app and had no way to notice. Nothing failed and +nothing was logged. + +**The app now bundles both faces and chains them by coverage.** Google Sans Flex draws +Latin and digits, Onest (193 056 bytes, 162 Cyrillic code points) draws Cyrillic, and +`FallbackTypeface.kt` puts them in one `Typeface.CustomFallbackBuilder` — Latin, then +Cyrillic, then the system — handed to Compose through `AndroidFont`, one chain per weight. +That construction is the only one that chooses by coverage: a Compose `FontFamily` picks by +weight and style, and so does a font-family XML. **`CustomFallbackBuilder` is API 29 and +this app's floor is 26**, so Android 8.0 and 9.0 are set in Onest alone — correct, and +merely less like itself. + +Google Sans Flex is committed frozen from six axes to `wght` alone, 3.81 MB to 0.26 MB; the +command that produced it is in `docs/build.md`. Both files now carry one axis and the app +varies it, so **the build-time instancer from the batch before is gone**: there is nothing +left to freeze, and `./gradlew` needs no Python again. The guard stayed where the fix was — +`FontAxisTest` fails if the pair cannot draw the Russian alphabet, if either file carries an +axis `Type.kt` never varies, or if a bundled file is named by nothing, and each was proved +red by breaking it. + +`GoogleSansFlexRounded` went too. It had three callers asking it for SemiBold and Bold, and +it was registered at one weight, so Compose synthesised what they asked for rather than the +font drawing it — and neither file now has a rounded axis to offer instead. + +### Two rules that existed in one shell and not the other + +**«🔔 Звонки» in the editor silenced lessons and told nobody.** It wrote the bell rows by +hand instead of going through `structure.write_bell_periods`, which is the half that answers +«which lessons stop ringing». A five-row paste took lessons 6 and 7 off every phone, out of +the widget, the calendar feed and the digests, under «✅ Звонки сохранены: 5 уроков» and not +a word more — while the *same* paste through «⚙️ Класс» warned properly. Two of the twelve +agents found this independently. It now goes through the service, the warning sentence lives +once in `render.silenced_lessons` so the two editors cannot drift again, and the handler's +private copy of `BELL_LINE` is gone in favour of the shared grammar. + +**A substitution could be written on a day the resolver never draws.** `_resolve_day` +returns before the override loop out of the school year and on a day marked «выходной»; +`api/edit.py` had refused both since it was written, and the bot had neither check. It was +believed safe because its lesson picker offers nothing on such a day — true of the picker, +not of the flow, because the bot's calendar bounds the year 1 September to 1 August under +the same function name as `schedule.school_year_bounds`, which means something else. So June +is two taps away, and the row was stored, logged and pushed to every subscriber. The rule +and its three sentences now live in `services/timetable_edit.why_no_lesson_can_be_drawn` and +both shells call it. + +Also: «✅ Звонки сохранены: 1 уроков» and «Расписание создано: 1 уроков» now count in Russian. + +### Gates + +`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` +**1565 passed** (was 1559). `./gradlew test assembleDebug assembleRelease` green: **770 tests +across 106 classes**. The release APK is **3 852 053 bytes** — 80 KB more than the 3 771 298 +it started the day at, which is the second typeface bought with the alphabet. No model changed, so no migration: the database stays at `0013`. + +### Found and not fixed — the list is the deliverable + +None of these is closed; all are verified enough to act on. + +- **Cleartext HTTP is permitted for every host** (`network_security_config.xml`), and the + comment justifying it says «No credentials, no personal data». That stopped being true + when the app grew its own diary sign-in: `DiaryApi.login` posts a dnevnik2 password + through the same OkHttp client at whatever address the reader typed. Nothing checks the + scheme. +- **`POST /api/v1/diary/login` counts only a 401 against its limiter.** A 200 of HTML from + the upstream becomes a 502 and costs nothing, which `api/diary_web.py` already decided the + other way at length for the same exception type. +- **419 of `:app`'s 779 strings can never be corrected**: the translation pull request writes + to `values/strings.xml` only, and `:app` splits its resources across eight files. +- **Twelve callback handlers have no fallback**, so a press on a card whose FSM state is gone + answers nothing and the button spins — reachable through the command breakout. +- **«Мои задачи» draws up to forty rows over ten buttons**; the tail cannot be ticked or + deleted. +- **`DATABASE_URL` set to blank or with a leading space** walks past `deployment_problems()`. +- Four rotation defects in `:app` (correction editor, diary correction sheet), the widget's + narrow-column labels, `docs/widget.md`'s size ladder disagreeing with `docs/design.md`, + stale counts in `docs/architecture.md` and sections 1, 5 and 7 of this file, `docs/app/` + missing from the CI path filter, and a dozen string findings — three names for the app, + two Russian names for `VIEWER`, a nominative weekday where the sentence needs accusative. + +### Where the seam actually falls + +Traced after the pull request was opened, against both files' `cmap` rather than +guessed. The chain resolves per character, and the base wins every code point it +covers — **464 of them are in both files**, so on API 29+ Onest never draws Latin, +digits or punctuation even though it can. + +| | drawn by | +| --- | --- | +| `Algebra`, `08:30–09:15`, `«»`, `—`, `…`, `·` | Google Sans Flex | +| `Алгебра`, `ё`, and **`№`** | Onest | +| `каб. 214` | `каб` Onest, `. 214` Google Sans Flex | +| `9А` | `9` Google Sans Flex, `А` Onest | +| emoji | the system, third in the chain | + +`№` is the one worth knowing: Google Sans Flex does not cover it, so «Урок №3» +breaks between the `№` and the `3` rather than between the word and the number. +That and «каб. 214» are the two most frequent mixed strings in the app, and they +are where to look first for a visible seam. + +### What nobody has verified + +Onest has not been drawn on a device: what is checked is that it declares the axis the app +varies, covers the Russian alphabet, carries its own OFL notice, and renders under +Robolectric. The twelve agents' reports are in this session's transcript, not in the +repository. + +## What the batch before added: the typeface is compressed by the build + +Four commits in `dev`, merged as PR #75 (`01a69fc`), in the milestone `v0.7.0 — Оптимизация` +(number 8), which the owner created for this batch because none of the seven fitted. Its +number was not handed over and nothing here lists a milestone, so it was assigned as 8 — the +next after the seven — and then **read back off the pull request** rather than assumed, which +is the only check available and is what the `github-pr` skill means by reading a number back. + +Its title is Russian where the other seven are English, which is the one place the project's +own rule — Russian on the screen, English in everything written about the project — is not +kept today. It is the owner's milestone and theirs to rename; nothing here touched it. + +**The instanced font was committed, and that was the arrangement that could not survive an +update.** The batch below took the file from 3.81 MB to 0.29 MB with `fonttools` and +committed the result. It works exactly until somebody updates the typeface, because the +obvious way to update a font is to download it again — and the download is the six-axis +file, so two megabytes come back into the APK with nothing failing. `FontAxisTest` would +have caught it; the point is that it should not have to. + +So the font is a **source** now. `core/designsystem/fonts/google_sans_flex.ttf` is the file +as it was downloaded, and `instance<Variant>Font` writes the compressed copy into the +variant's generated resources on every build. What is in the repository is the thing you +would download. + +**The compression is a setting, which is what was actually asked for.** +`-Plessons.font.axes` takes a list of axes to keep, or `all`. Measured on one tree, three +builds: + +| `lessons.font.axes` | the font | release APK | needs | +| --- | --- | --- | --- | +| `wght,ROND` — the default | 0.29 MB | 3.60 MB | Python 3.10+ with `fonttools` | +| `wght` | 0.27 MB | 3.58 MB | the same | +| `all` | 3.81 MB | 5.71 MB | nothing | + +`wght` is not the default although it is smaller: it bakes `ROND` in at 100 and the code +goes on asking for an axis that is gone, which Android answers by drawing the default and +logging nothing. Fifteen kilobytes is not worth that. `all` is the escape hatch for a +machine with no Python, and it is a correct build — the file that ships is the file that was +downloaded, to the byte. + +**The cost is that Gradle now needs Python.** Without `fonttools` every Android task stops, +with a message naming `-Plessons.font.axes=all` rather than a stack trace out of a missing +module — proved by pointing the task at interpreters that do not exist. Both Android +workflows install `fonttools==4.65.0`, pinned because that is the one the sizes above were +measured with. + +**Two things AGP 9 decides for you here.** `sourceSets["main"].res.srcDir(provider)` is +refused outright — a static directory carries no task dependency, so the font would be +merged before it was written — and the supported way, `addGeneratedSourceDirectory`, is +per variant and chooses the output path itself. Hence one task per variant (the second is a +build-cache hit) and the tests being handed the path rather than guessing it. + +**`FontAxisTest` was rewritten around the setting**, and every guard was proved red on its +own side: an axis the app asks for that the shipped font neither declares nor freezes; an +axis the shipped font carries that the build was not told to keep (reproduced by building +`all` and running the tests at the default); a `fontAxisPins` value that disagrees with +`Type.kt`; and the file not actually shrinking. `instance.py` refuses a pin for an axis the +font does not declare, because that is the one hole a test cannot see — the tag would still +be in the build file's map and the test would pass while nothing had been frozen. + +**The licence claim was wrong and is now right.** `Type.kt`, `docs/design.md` and the OFL +notice inside the APK all said the file is not modified here. It is: freezing an axis +rewrites the outlines. The OFL permits it outright, and its rename requirement applies only +to a Reserved Font Name, which this typeface declares none of; the `name` table is left +alone, so the copyright and the licence entry in the shipped file are the downloaded file's +own and `FontLicenceTest` still reads them out of what ships. + +### Gates + +`./gradlew test assembleDebug assembleRelease` green: **770 tests across 106 classes** (was +768 across 106). The server was not touched, so its gates were not re-run — `ruff`, `mypy` +and the 1559 tests were last green on the batch below. No model changed, so no migration: +the database stays at `0013`. + +### What nobody has verified + +Nothing in this batch has been drawn on a device; what is checked is that the shipped font +declares what the code asks for, that it is smaller than the source, and that it renders +under Robolectric like any other resource. The `all` setting is exercised here by hand and +**not in CI** — CI builds the default, because a CI run exists to build what ships. + +The Android workflows' `pip install fonttools==4.65.0` **has** now run on a GitHub runner, +which was the one thing the local gates could not answer: CI was green on `b6f0869` and +again on `3126597`, and neither job could have built at the default setting without the +instancer. + +What it costs, read off the job log rather than off the job totals: **4.2 s** for the pip +install, and 0.1 s for `setup-python`, because 3.12 is already on the runner image. The two +`instance<Variant>Font` tasks span 2.4 s inside a two-and-a-half-minute Gradle build, beside +everything else it is doing. The three Android jobs came in at 4 min 14 s without any of +this, 5 min 43 s with it and 3 min 09 s with it again — that spread is Gradle's cache being +cold or warm, and nothing about this step can be read off it. + +## What the batch before added: a signed build, two megabytes off it, and the documents + +Three commits in `dev`, merged as PR #74 (`9920a9a`), in the milestone `v0.6.0`. This batch +is different from the ones below it: most of it came out of the owner configuring the +release keystore and the two optional secrets **for the first time**, which turned up what +the documents did not say and what the workflow did not tell you. + +### The APK is signed now, and the first one cost three attempts + +All four keystore secrets and both optional ones are set, and run #21 produced a release APK +signed with the owner's own key — the first this repository has ever made. What it cost is +the useful part. The first attempt died at «Decode keystore» with `base64: invalid input`, +which names neither the secret nor this project; the value had lost its last two characters +to a selection in a phone terminal that stopped one gesture early. PR #73 replaced that +message: it reports the value's length **modulo four**, because base64 always comes in +groups of four and the remainder is the whole diagnosis, and `keytool` now opens the rebuilt +file before the build starts rather than letting a wrong password surface eight minutes +later inside Gradle. + +**The next install is an uninstall.** The build on the owner's phone is debug-signed; this +one is not, and Android compares certificates before versions. It takes the classes, the +device token, the diary session and the corrections with it. It is the last time. + +### Two megabytes, and not one of them was a dependency + +The release APK was **5 989 554 bytes** and is **3 771 086** — `res/fU.ttf` was 2296 KB of +it, 40% of everything shipped and more than all the code. + +Nothing about dependencies was the problem, and the batch is worth reading for that as much +as for the saving. The debug APK is 27 MB against the release's 5.7, so R8 already removes +about eighty per cent; `material-icons-extended` declares thousands of icons, 112 are used, +and the rest were gone already. Compose with Material3 is a couple of megabytes of dex on +its own and no pruning reaches it. + +The font was all of it, for a reason that is not about character coverage. It ships with six +variation axes, and a variable font pays for an axis in `gvar` — outline deltas per axis per +glyph — which was **3411 KB of a 3811 KB file** while the outlines themselves were 31 KB. +The app touches two: it varies `wght` and sets `ROND` to 100. The four that never move are +frozen now; all 657 glyphs are kept and the file is 0.29 MB. `ROND` stays a real axis rather +than being baked in, which costs 0.02 MB and keeps the code's request meaning something. + +`FontAxisTest` holds both directions, each proved red on its own side: an axis the code asks +for and the font does not declare (Android ignores it silently and draws the default), and an +axis the font carries that nothing asks for — which is the saving coming back through the +obvious way to update a typeface. The `name` table is untouched, so `FontLicenceTest` passes +and the OFL travels with the file. + +### The documents were read end to end, and sixteen things were wrong + +Not stale — wrong. `docs/widget.md` said alarms go through `setWindow`, which was removed +because Doze held it, and that `SCHEDULE_EXACT_ALARM` is not requested, while the manifest +declares it and `USE_EXACT_ALARM`. `docs/api.md` described refusals `PUT /overrides` no +longer makes, gave `POST /diary/login` no throttle although it finally has one that works, +named `reminders.yml` as the cron's caller against what `deploy.md` and `CLAUDE.md` say, and +put the FSM sweep at a day where `STALE_AFTER` is two. `docs/bot.md`'s `/find` was wrong +twice. `docs/design.md` gained the section the `MarqueeText` crash deserved. The index, +`docs/README.md`, was accurate end to end and was left alone. + +`docs/build.md` gained what the first configuration turned up: the OAuth App registration as +a table over the form's own fields, and **«Expire user access tokens» must be unticked** — +`AccessTokenDto` has no `refresh_token` field anywhere in `:core:data`, so with that box +ticked the token dies after eight hours, `/user` answers 401, the app forgets it, and the +reader is back at «Войти через GitHub» every day with nothing logged. + +### Gates + +`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` +**1559 passed**. `./gradlew test assembleDebug assembleRelease` green: **768 tests across 106 +classes** (was 765 across 105). No model changed, so no migration: the database stays at +`0013`. + +### What nobody has verified + +The instanced font has not been drawn on a device — what is checked is that it declares what +the code asks for and renders under Robolectric like any other resource. Nothing in the +GitHub sign-in has run against live GitHub either; the secrets are set and the button is in +the build, and the first press will be the owner's. + +## What the batch before added: the two loose ends + +One commit in `dev`, merged as PR #72 (`cb20b45`), in the milestone `v0.6.0`. Both were named +by the batch below as found-and-not-taken, and both are now taken. + +**A command the bot does not have answers.** Telegram stays silent on one, and for a bot with +a single screen that is fine — but once a command started breaking out of a half-finished +form, silence became misleading: «/wek», a typo for «/week», dropped what somebody was +filling in, said so, and then nothing happened. It says «🤔 Не знаю такой команды. Наберите +/help, чтобы увидеть список.» + +The handler is a router included **last** in `build_router()`, because it matches any command +at all and so everything that answers one has to be asked first. That contract is invisible, +so a test walks the whole `COMMANDS` list — the one BotFather shows — and fails if any of +them reaches the catch-all, turning a comment that had stood over that list since it was +written into something checked. Proved red both ways: unregistering the router fails the two +unknown-command tests, and moving it to the front fails all twenty-four menu commands. +Private chats only, because in a group Telegram hands «/start@otherbot» to every bot that can +see it. + +**«Отладка» keeps the report being read when the phone is turned.** It is the screen where a +rotation costs most — the report is open while its important line is being copied into a +message to whoever can fix it — and a rotation dropped the reader back to five +identical-looking timestamps. The name is saved rather than the file, and the file is looked +up in the list again, the same shape as the calendar's lesson sheet. + +**One thing a test here does not prove, and says so in its own words.** The second case, a +report whose file has gone, does not discriminate between looking the name up in the list and +building a `File` from it blind: the body is read with `runCatching`, so a deleted file is an +empty string either way and the test passes against both. That was checked by running the +second implementation, not assumed. The lookup is still right for a reason no test here +reaches — the name comes out of a bundle another build wrote, and the lookup can only ever +yield a file this app listed. + +### Gates + +`ruff check` clean, `python -m mypy` clean across 83 modules, `python -m pytest -q -n auto` +**1559 passed** (was 1533). `./gradlew test assembleDebug assembleRelease` green: **765 tests +across 105 classes** (was 763 across 104). No model changed, so no migration: the database +stays at `0013`. `docs/bot.md` gained the unknown-command rule beside the refusal it already +described, and the test counts moved in all four places. + +### What is left + +Nothing here has run on a device or against a live Telegram, as with everything above it. +**What only the owner can do** is unchanged and still outstanding: register an OAuth App with +**Enable Device Flow** ticked, put its client id in the repository secret +`LESSONS_GITHUB_CLIENT_ID` and an address in `LESSONS_CONTACT_EMAIL`. Until then «Войти через +GitHub» is in no build and the APK run summary says «off». + +## What the batch before added: the four things the sweep would not decide + +Three commits in `dev`, merged as PR #71 (`0cdd7f1`), in the milestone `v0.6.0`. The batch +below found these four and deliberately left every one of them, because each is a decision +rather than a correction. The owner took all four; what follows is what each decision *was*, +because the code is the easy half. + +**A command wins over a half-finished form.** `/week` typed at «Теперь пришлите текст +задания:» was committed as an assignment whose text was «/week», audited, and pushed to every +subscriber — and which commands escaped was an accident of which router was included first. +The decision could have gone the other way (refuse the command, keep the form); it did not, +because somebody who types a command mid-form wants to be somewhere else. So the state is +dropped, the bot says «✖️ Форма отменена: вы отправили команду.» and the command runs as +though the form had never been open. + +The mechanism matters more than the behaviour. It is **one outer middleware on the message +observer**, not a check in each step: the state has to be *cleared*, which no filter can do — +a filter would let the command run and leave the form sitting there to eat the next plain +message — and clearing `raw_state` with it means no state-filtered handler can match a +command, whoever writes the twenty-sixth step. The rule-holder test is parametrised over every +`State` discovered in the two state modules, so a new form step is a new case with nothing to +remember. Unregistering the middleware fails 45 of its 48 tests and reproduces the production +defect exactly; the three that stay green are the three that must be green both ways. + +**`request_approve` has one home.** Forty lines carried twice, in `api/manage.py` and +`bot/handlers/manage.py`. `services/access.py` holds them; both shells find the request, call +it, translate the refusal into a 403 or a Russian alert, commit and notify. The API keeps its +extra freedom to name a different role in the body, which `can_grant` still gates inside the +service. An anti-drift test watches both shells call it. + +**A class that moves from 9 to 10 stops being called «9А».** Moving `grade` or `letter` +recomposes the name — **unless the same request also sets `name`**, because an admin who names +the class has said what they want. The audit line is written only when the name actually +changed. The bot has no grade editor, so there is no twin to keep in step today; if «⚙️ Класс» +ever grows one, the rule belongs in `services/terms.py` rather than in the endpoint. + +**The calendar's two sheets survive a rotation.** `Lesson` cannot be saved — it comes from +`:core:model`, which is pure JVM and must stay that way — so what is saved is what the sheet +is *about*: the date and the lesson's number, which name one lesson, because the server +resolves a date into at most one lesson per number and nothing between there and the screen +adds a row. The lesson is looked up in the week on every composition, and one that is no +longer there opens no sheet. That lookup closed a second defect the rotation only made +visible: the sheet held the object it was handed, so withdrawing a substitution while its +sheet was open left the room, the teacher and the homework of a lesson that had stopped +existing on screen, with no rotation needed. + +### Gates + +`ruff check` clean, `python -m mypy` clean across 82 modules, `python -m pytest -q -n auto` +**1533 passed** (was 1474). `./gradlew test assembleDebug assembleRelease` green: **763 tests +across 104 classes** (was 760 across 103). No model changed, so no migration: the database +stays at `0013`. `docs/bot.md` gained the command rule beside its FSM paragraph, and the test +counts moved in all four places that carry them — `CLAUDE.md`'s was two batches stale. + +### What is left, and what nobody has verified + +Nothing here has run on a device or against a live Telegram. Two loose ends were found and +not taken: «/notacommand» now gets the «Форма отменена» line and then silence, because this +bot has no unknown-command handler — a separate card if it is wanted; and «Отладка» holds the +crash report it is reading in a plain `remember`, so a rotation drops the reader back to the +list. That one is a file name and saves cheaply. + +**What only the owner can do** is unchanged from the batch below and still outstanding: +register an OAuth App with **Enable Device Flow** ticked and put its client id in the +repository secret `LESSONS_GITHUB_CLIENT_ID`, and an address in `LESSONS_CONTACT_EMAIL`. +Until then «Войти через GitHub» is in no build, and the APK run summary says «off». + +## What the batch before added: the crash, the button that was never built, and twelve defects + +Seven commits in `dev`, merged as PR #70 (`7bde4f7`), in the milestone `v0.6.0`. Three parts: +the crash the batch below could not explain, a feature that was missing from every APK ever +built, and a five-agent sweep of the whole tree. + +### The crash after the link, which was a line of layout + +It closes the report the batch below could not answer — «приложение вылетает через несколько +секунд после привязки Telegram», and then «предлагает очистить кэш» — and **it was not the +link.** + +The bug report the owner sent from the phone carries the fatal exception, on the main +thread, once at 14:36 and then in a loop for seventy seconds: + +``` +java.lang.IllegalStateException: Asking for intrinsic measurements of SubcomposeLayout +layouts is not supported. This includes components that are built on top of +SubcomposeLayout, such as lazy lists, BoxWithConstraints, TabRow, etc. +``` + +The stack is R8-obfuscated and names neither a file of ours nor a caller of one. What it did +not have to name: **the app contained exactly one `SubcomposeLayout`**, the +`BoxWithConstraints` inside `MarqueeText`, and that component is drawn at two dozen call +sites — every group row, every lesson row, every section header, the toolbar, the pickers. +A `SubcomposeLayout` cannot answer «how tall would you be at this width», and nothing in this +repository spells `IntrinsicSize`, which is exactly why it looked safe: Material spells it +inside its own rows, so the question arrives at a call site that never mentions it. **Which +Material component asked was not identified and did not need to be** — the component that +could not answer now can, wherever it is placed. + +It came in with #62 and has been in every build since, including the one the owner is +running. The link had nothing to do with it beyond redrawing the screen. + +The fix is the width without the subcomposition: `Modifier.onSizeChanged`, outermost of the +three modifiers so that it reports the window rather than the string the marquee scrolls +through it. The price is one frame — until the line has been measured once its width is +`Constraints.Infinity`, nothing can overflow it, and a line that will scroll is drawn still, +which is what the first frame of a marquee looks like anyway. + +Three things about the tests are worth carrying forward: + +* **The reproduction is one line.** `Row(Modifier.height(IntrinsicSize.Min))` is the + question, and it throws that exact exception on the old component. +* **Three of the component's own tests were named for a line that scrolls and never reached + one.** Robolectric lays text out with no fonts — every glyph costs about a pixel — so + «По этому предмету ничего не задано» measures 35 px and sits inside a 120 dp box with room + to spare. They use a string twenty times as long now. One of them, «stays inside its box», + was also reading a number that says nothing: a scrolling line's text node really *is* as + wide as the string. What holds is that the row is not pushed apart, so what the test looks + at is a neighbour placed after it. +* **`NoSubcomposedLeafTest` holds the rule rather than review.** It reads + `:core:designsystem`'s source and fails on a `BoxWithConstraints`, a `SubcomposeLayout`, a + `TabRow` or a lazy list, with the same `//`-above opt-out `NoEllipsisedLineTest` uses. + `:app` and `:widget` are outside it for a reason and not for convenience: a lazy list on a + screen is the root of its own layout and nothing above it asks it to predict a size — seven + screens hold one on those terms. The rule is for a component written to be placed inside a + layout it does not own. + +Each of the three guards was proven red first — the intrinsic query against the old +component, the scrolling test with the width feed cut, and the source rule with the word put +back into a component. + +### «Войти через GitHub» has never been in an APK + +The row is shown only when the client id is non-empty, `app/build.gradle.kts` reads it from +`LESSONS_GITHUB_CLIENT_ID`, and **`apk.yml` passed that property on no day of its life**. So +every build the workflow ever made had it blank: the row hidden, and with it the only way to +file a bug report from inside the app and the only way to send a correction as a pull +request. `LESSONS_CONTACT_EMAIL` was the same story one button along, which is «Отправить +письмом». Nothing failed and nothing warned — an unset property is an empty string, and +downstream that is a feature switched off. + +Hiding the row stays: a row that opens a sheet saying «не настроено» is a row about the build +rather than about the reader, and that is written down in `docs/design.md`. What it costs is +that the whole weight then rests on the build actually passing the property, so the run +summary reports each one as on or off. `BuildPropertyReachTest` reads the build script and +the workflow together and fails on a property that is read and never assigned; its first +version passed on the name appearing in a comment, and was caught by breaking the wire on +purpose. Both files are declared inputs of the test task — without that, editing the workflow +left the task `UP-TO-DATE` and the check unrun. + +### Twelve defects, from five agents, each closed with a test proven red + +On the server: **the diary sign-in throttle did not exist and a wrong password answered +500** — `JoinAttempt.client_key` is `VARCHAR(64)`, a SHA-256 digest fills it exactly, and the +diary's key was that digest with «diary:» in front, so the insert raised out of the `except` +that was re-raising the 401; SQLite ignores a `VARCHAR` width, which is why the test named +after that limit passed all along. **A substitution could be stripped of the subject that +made it visible** — the guard ran only on create, and the row is reachable in two writes. +In the bot: a typed year one digit too long left the handler through `OverflowError`; «²» +passes `isdigit()` and `int()` refuses it, in two callback handlers as well as the date +parser; a lesson edit whose slot had gone was audited as though it had happened; the canteen +could be marked on a break the bells no longer ring. + +On the phone: **the widget's loading layout drew its message white on near-white for Android +8 to 12** — `DeviceDefault` below API 29 is the dark variant and the surface comes from +`values/`, so the layout drew exactly the blank rectangle it exists to prevent. **The guide +froze in one language for ever once refreshed in the other** — one manifest version for two +files, recorded under language-less keys. **One dropped request ended a GitHub sign-in that +GitHub had already granted.** **The edge wash was drawn on every phone below Android 13 while +the only switch that names it said it was off and could not be pressed** — the blur is gated +on API 33, the gradient tint is not, and the row gated the whole switch on shaders. **Turning +the phone re-opened a pull request already opened** — a `LaunchedEffect` key survives a +recomposition, not a configuration change. + +**Reported and deliberately not fixed**, because each is a decision rather than a correction: +a command typed into an open bot form is saved as the answer, so «/week» at «пришлите текст +задания» becomes homework called «/week» and goes to every subscriber, and which commands +escape is an accident of router order; `request_approve` is forty duplicated lines across the +API and the bot; `PATCH /manage/class` can move a class from 9 to 10 without its name ceasing +to say «9А»; `WeekScreen`'s two sheets close on a rotation, and `Lesson` cannot be made +parcelable without breaking `:core:model`'s purity. + +### Gates + +`ruff check` clean, `python -m mypy` clean across 81 modules, `python -m pytest -q -n auto` +**1474 passed** (was 1465). `./gradlew test assembleDebug assembleRelease` green: **760 tests +across 103 classes** (was 738 across 96). No model changed, so no migration: the database +stays at `0013`. + +**What only the owner can do.** Register an OAuth App — Settings → Developer settings → OAuth +Apps → New OAuth App, with **Enable Device Flow** ticked — and put its client id in the +repository secret `LESSONS_GITHUB_CLIENT_ID`, and an address in `LESSONS_CONTACT_EMAIL`. +There is no client secret to register. Until then the run summary says «off», which is the +honest answer rather than a silent one. And install a build carrying all of this and link a +phone again: none of it has run on a device, and the uninstall-first caveat below still +applies to a debug-signed APK. + +## What the batch before added: a crash report that its own phone can read + +One commit in `dev`, merged as PR #69 (`cbb81e8`), in the milestone `v0.6.0`. It is the answer +to a question that could not be answered: **«приложение вылетает через несколько секунд после +привязки Telegram» — and there was no way to get the stack trace off the phone.** + +The switch that records crash reports has always been on «О приложении», where everybody can +reach it. The two ways to *read* one were the administrator's — the bug button beside the +toolbar's pill and the management page's own row. So anybody who is not an administrator +could turn the feature on, crash, and then have nothing: the file is in the app's external +files directory, which Android 11 stopped file managers from opening, and no screen they +could reach would show it. On a Samsung, with no computer, that is a dead end. + +The row is now directly under the switch that writes the reports — the same row the +management page had, moved to `ui/debug/DebugRow.kt` and shared rather than copied, with its +strings losing the `admin_` prefix along with the gate. Two tests: one composes the row, +presses it and asserts the sheet opens; the other reads `SettingsScreen.kt` and fails if the +«О приложении» group stops calling it or starts gating it on the role, because a composition +test cannot ask whether a row is on the page everybody has. Proven red against the code +without the fix. + +**The crash itself was not fixed by this batch — the one above does that**, and it was none +of the things ruled out here. What was ruled out, by reading and +by one throwaway Robolectric reproduction: the account section's composition survives the +link landing under it (`Ready(unlinked)` → `Loading` → `Ready(linked, ADMIN)` → +`isRefreshing` both ways); the exact-alarm path catches its `SecurityException` and asks +`canScheduleExactAlarms()` first; nothing polls `/me`; and linking triggers no sync at all — +`syncNow` has two callers, `SessionEffects` and the widget. So the sync whose state updates +in the report is the periodic one, landing near the link by coincidence rather than because +of it. The next step needs the stack trace this batch makes reachable. + +`./gradlew test assembleDebug assembleRelease` green: **738 tests across 96 classes**, up +from 736 across 95. + +**What only the owner can do.** Install a build carrying this row — which on the current +debug-signed APK means uninstalling first, and that takes the device's classes, token, diary +session and corrections with it. And the reports stay off until the switch is on, by the +earlier deliberate decision about what may land on disk: this batch changes who can read what +is written, not when it is written. + +--- + +## What the batch before added: the guide is fetched, and a debug-signed APK explained + +Four commits in `dev`, merged as PR #67 (`0957628`), in the milestone `v0.6.0`. Two +unrelated things that arrived in one batch because the first was a question about the +second's build. + +**Installing 0.6.0 over an older build failed, and the repository was wrong about why.** +«Приложение не установлено», after offering to update, with the version raised. The cause is +that **the debug keystore is generated on the machine that builds and thrown away with it**: +the alias and both passwords are constants, the key pair is not, a runner is a fresh machine +every run, and the Gradle cache covers `~/.gradle` rather than `~/.android`. So every APK run +signs with a certificate that has never existed before, and Android compares the certificate +before it looks at any version. Measured rather than reasoned — the APK from run 15 carries +`CN=Android Debug` with `validFrom` two minutes into that run's own build step. + +Two statements in this repository said otherwise. `docs/build.md` said the debug key "is the +same for everybody"; `apk.yml` said twice it is "the same certificate on every machine on +Earth, so anybody could then build an update Android would accept". **Nobody can** — the key +is gone, which is the real cost, because that includes whoever published it. The second real +cost is authorship: `CN=Android Debug` is what every debug build says. The gate that refuses +to publish an unsigned release is unchanged; only its reason is. `docs/build.md` now has the +section a reader meets this in, including that the only cures are an uninstall — which takes +the device's classes, token, diary session and corrections with it — or the four secrets. + +**`apk.yml` also discarded any `versionCode` it was given**, overriding it with the run +number and offering no input for it. There is a `version_code` input now; blank still means +the run number, and it is validated before anything else runs — empty, `0`, `-3`, `1.2`, +`abc`, `"12 34"` and a command substitution are all refused rather than evaluated. + +**The in-app guide stopped being 103 string resources.** It is two markdown files in +`docs/app/` — `guide.ru.md`, the source, `guide.en.md`, its translation — plus a manifest +naming the documentation's version and the app version it describes. The app fetches them +from `raw.githubusercontent.com`, stores them in its own files, and falls back to the copy in +its assets; `docs/app/` **is** `:core:data`'s asset folder rather than a copy of it, so the +bytes in the APK are the bytes in the repository. Verified by listing the assets of both +built APKs. + +The format is a deliberately small subset — `##` a page with its metadata comment, `-` a +list, `1.` with a bold lead a step, `>` an aside, and `**bold**`, `` `code` ``, `[text](url)` +inside a line. **The parser never throws**: an HTML error page, a JSON body or a truncated +file parses to no pages, and the repository keeps what it already had rather than replacing a +working guide with an empty screen. + +**Every page now states which documentation it is** — version, date, and the app version it +was written for — and adds a second line only when there is something to say about the copy: +no network, an answer that was not a guide, or the copy the app shipped with. + +**The sections stopped being screens.** They are peers, so they are a `HorizontalPager` +swiped like the three home tabs, and the toolbar scrolls it rather than pushing a screen. +Back therefore has one meaning here, which is what the arrow beside the pill does: leave the +documentation. `DocsHistory`, the page enum and the depth-per-section that existed to animate +pushes between peers are gone. Pull to refresh uses `LessonsPullToRefreshBox`, the same +expressive loader the two other refreshing screens use, and it shows while the automatic +check runs as the guide opens. + +**One defect found by re-reading the diff rather than by a test.** `storedOrBundled` +preferred a fetched copy over the bundled one unconditionally, so a phone that fetched +version 3 a year ago and then installed an APK carrying version 5 would have been shown the +**older** guide — offline, for as long as the network stayed down, which is exactly the case +the fallback exists for. The rule is a named function of two numbers now, `preferStoredCopy`, +and it is tested; proven red against the code without the fix. + +**What it gives up, and it is a real cost.** The guide's text is no longer a resource, so +correction mode cannot touch it and `ResourceTranslationTest` no longer guards it. A wrong +sentence in the documentation is now a pull request against `docs/app/` — the same place the +app reads it from. `DocsGuideParityTest` took over what could be kept: both languages parse to +the same pages, in the same order, with the same ids, from the same blocks, with no list of +one point, no step numbered out of sequence and no paragraph written twice. It reads the +shipped files rather than a fixture. + +`./gradlew test assembleDebug assembleRelease` green: **736 tests across 95 classes**, up +from 725 across 93. The README, `docs/architecture.md` and this file's cheat-sheet carry that +number; `architecture.md` gained the section describing the pipeline and `design.md`'s line +about the documentation's longest page is corrected. + +**What nothing has verified.** Not one line of the fetch has run against GitHub — the parser, +the parity of the two files and the choice between two stored copies are tested, the network +path is written and never executed, exactly like the translation flow in #64. Nothing has +been pressed on a device: the pager, the loader, the banner and the arrow are laid out by +code and seen by nobody. The bundled assets are proven only by the APK's contents, because +`:core:data`'s tests have no `Context`. And the new `version_code` input has never been run. + +**The chain of close-outs stops by rule now, and merging no longer waits for a sentence.** +Every batch ends in a close-out, whose own merge is then a thing no close-out describes — +and writing one for that needs another, for ever. The rule: a close-out rides inside its +batch's own pull request while that pull request is open, it names itself as the only thing +open, and **the SHA of its own merge is written by the next batch** rather than by a pull +request about it. Separately, the owner asked for a green pull request of this session's own +work to be merged without being asked each time; that is recorded in the `github-pr` skill +as their standing instruction, with the five things to check first and the cases it does not +cover — an unsettled migration, somebody else's pull request, and «I want to look at this +one». + +**And the hook added in #65 was wrong, in the one case the rule prefers.** It fired after +#67 merged, saying the close-out was missing — while `HANDOVER.md` had described that batch +since `6caca07`, inside the pull request, which is exactly what the rule asks for. A +close-out written that way is landed **by** the merge commit, so it is always older than it, +and a hook comparing only timestamps calls it missing every time the rule is followed +properly. It now asks first whether the merge's own diff touched `HANDOVER.md`; the +timestamp is the fallback for a close-out committed after a merge instead. Tested in all +three directions in a throwaway repository — carried by the merge, not carried, committed +afterwards — and silent on this tree, where it had just spoken. + +--- + +## What the batch before added: a correction goes out as a pull request + +Three commits in `dev`, merged as PR #64 (`e4361a0`), in the milestone `v0.6.0`. Before them, +PR #63 (`ec0d976`) carried the previous batch's close-out in this file and nothing else, and +went into `main` on the owner's instruction. + +**Correction mode used to end in a fragment somebody else had to paste.** It produced a +`<string>` element, and that was the whole delivery: the reader copied it, or shared it, and +the work reached the project only if a second person carried it. The session sheet now also +offers to open a pull request, and it is opened **from the account the reader signed in +with**, not from the project's. + +**The sign-in row moved to where it is needed.** It sat in the group about GitHub under +«О приложении»; it now sits directly above the correction-mode switch, which is where +somebody looking for it will be. Signing out stays in the old group beside the bug report +the account is otherwise for — two rows on one page showing the same account state is one +row too many. **Signing in is not required to make corrections:** the mode, the editor and +the session are local and work offline, so only the button that *sends* them goes dark +without an account. The anonymous update check was left alone for the same reason — it needs +no token, and a sign-in wall there would break something that works. + +**Putting a corrected string back is its own file, with its own test.** `StringsDocument` +replaces one element's body and leaves every other byte of `strings.xml` where it was. Seven +tests hold the parts that would go wrong quietly: `name="settings_title"` must not match +`settings_titles_plural`, a `<string-array>` of that name is a different resource, an +attribute written before `name` must not hide the element, a `>` inside a value must not cut +the body short, and a key the file does not declare is refused rather than appended. + +**What was taken from Essentials, and what was not.** Taken: where the row sits, the shape +of the flow, the two states of the account row. Not taken, because each is a defect rather +than a decision — their submit button is enabled while signed out and bounces the press to a +prompt; they clear the session on a *posted comment*, which is not a delivered correction, so +if the workflow behind it fails the reader's work is gone and nothing says so; their +`triggerWorkflowDispatch` passes the user's OAuth token as a workflow input, where it is +visible in the Actions UI and kept in the run record; and their translation feature carries +hard-coded English literals beside `stringResource` calls, which `ResourceTranslationTest` +would refuse here. + +**The transport is different on purpose.** Essentials' public path is a comment on a +hard-coded discussion thread, turned into a pull request by a workflow holding +`contents: write`; the contributor survives only as the commit author. That needs a +discussion, a workflow and a write permission this project does not want — and it does not +do what was asked, because the pull request is not the reader's. A fork and a pull request +are, and the `public_repo` scope the sign-in already requests covers both, so nobody has to +re-authorise. + +**Two defects in this batch's own code, found by re-reading it rather than by a failure.** +A repository merely *named* `lessons` was taken for the fork — the check asked for +`/repos/{login}/lessons` and read any 200 as "the fork is there", so a reader who already +owned an unrelated repository of that name would have had a branch cut in it and a commit +written to it, over a corrected string; it now reads the body and requires a fork whose +parent is this project. And the submit ran on `rememberCoroutineScope()`, which dies with the +composition, while the comment above it claimed the view model owned it and it survived +dismissal — closing the sheet cancelled the work. The launch moved to `viewModelScope`, which +fixed the comment's honesty as well as the behaviour. A third was caught before it shipped: +acknowledging the outcome inside the `LaunchedEffect` that opens the browser would have +cleared the message in the same frame it appeared. + +**Two things in that code that are easy to get wrong.** The branch is cut from the +**upstream** commit, not from the fork's own head: a fork made once and never synced is +behind by everything merged since, and would offer all of it back as reverts. And the +**owner of a repository cannot fork it** — GitHub answers 422 — so their branch goes straight +to the upstream repository, which is the case the first person to try this will hit. + +**Three places said 718 tests across 92 classes; the suite is 725 across 93.** This file's +cheat-sheet, the README's «Honest status» table and `docs/architecture.md` are corrected. +`docs/architecture.md` was wrong in a second way that the total had hidden: its per-module +breakdown still summed to 709, because the previous batch moved the total and not the five +numbers under it. They now read `:core:model` 94, `:core:data` 234, `:core:designsystem` 54, +`:widget` 68, `:app` 275 — counted from the test XML of a real run, and they add up. + +**What nothing has verified, and it is the whole point of the batch.** Not one line of the +fork, the branch, the commit or the pull request has executed against GitHub. There is no +test for it and no way to write one here — it needs an account, a token and a real +repository. The two defects above were found by reading, and the same reading cannot prove +there is not a third. **The first press should be the owner's, not a reader's.** Nothing has +been pressed on a device either: the row, the dark button, the spinner and the message after +it are laid out by code and seen by nobody. + +**Updating this file is now a written rule rather than a request (PR #65).** It had to be +asked for twice — once after #62 and once after #64 — and each time a batch had been called +done while the document a new session starts from still described the batch before it. The trigger is +the merge, and it is written in `CLAUDE.md`, in `AGENTS.md`, in the `handover` skill (which +also lists what goes stale mechanically, because reconstructing that list by hand is most of +the work) and in `github-pr`'s new «After it merges» section. `/where-are-we` now compares +the document's claimed state against the commits and says when it is behind. And a second +hook, `.claude/hooks/handover-behind.sh`, says one sentence on `Stop` when a merge commit is +newer than the last commit touching this file — which is true only in the window after a +merge and before the close-out, and stops being true the moment the file is committed. + +**The hook has since fired for real, and it was right.** It was proved in a throwaway +repository before it was committed, and the pull request that carried it said in as many +words that nothing had seen it fire in a session. #65 merged, `dev` was fast-forwarded, and +it spoke — about #65 itself, which this file did not yet describe. That is what the sentences +above and the paragraph at the top of this file are. **The regress ends the same way #63 +ended it:** the close-out describes its own pull request while that pull request is open, so +the file is already true when it merges. A close-out does not get a close-out of its own. + +**Deliberately left alone.** Milestone 6's description on GitHub still reads «PRs #60–#62» +though it now holds #63 and #64 as well — no tool here edits a milestone, so that is the +owner's line to change. The update check stays anonymous: it asks GitHub for the latest +release, needs no token, and putting it behind the sign-in would take a working feature away +from everybody who never signs in. + +--- + +## And before that: nothing on a screen is cut off + +Five commits in `dev`, merged as PR #62 (`f13d60e`), in the milestone `v0.6.0`. Three pieces, +and the second and third are consequences of the first rather than separate work. + +**A line that does not fit now scrolls instead of ending in «…».** «По этому предмету ничего +не задано» was drawn as «По этому предмету ничего н…» in a sheet with a screenful of room +under it. The app already had the better answer in one place — the segmented picker's labels +scroll and fade at both ends, because on a picker the whole word *is* the button — and that +behaviour is `MarqueeText` in `:core:designsystem` now, on 21 call sites. It measures the +string against the width the box actually has before deciding, because the layout cannot be +asked: `basicMarquee` hands the text unbounded width, so the node never reports overflow and +`onTextLayout` answers `false` for ever. A label that fits is left exactly as it was. + +**The nine blocks that cannot scroll stopped being capped instead.** A `maxLines = 2` block +has no single line to move sideways, and stopping there would have left the ellipsis +standing — only the shape of the answer had to change. Every one of the nine sits inside +something that scrolls, so the cap is simply gone: a sheet heading, a screen header and its +subtitle, the supporting line of both row shapes, `RowText`'s subtitle, a lesson's hand-typed +note, the hero card's detail. The row grows and nothing is lost. The one with least excuse +was `TimetableSheet`, which echoes the lines the parser refused so the typo in them can be +found and was cutting them at two. `TimelineBlock` on the week ruler went the other way: its +height *is* the lesson's duration, floored at 30 dp, so it is the one block in the app that +genuinely cannot grow, and its title marquees. + +**Then the test found a silent clip nobody was looking for.** A bare `maxLines = 1` with no +`overflow` does not ellipsize — it clips, with nothing to show that anything was cut, which +is the same refusal with the warning removed. The hero card's countdown row had one: the row +wraps its content and shares no weight, so at a large font scale the number takes the width +and «до конца» loses its end in silence. That label marquees with a weight now. The countdown +beside it deliberately does not — it is rebuilt every tick, so a marquee would be handed a +new string each second and restart from the left for ever. + +`NoEllipsisedLineTest` holds all of it, and it reads **every** module rather than the one it +lives in — the same correction `ResourceTranslationTest` once needed, for the same reason. It +refuses any `TextOverflow.Ellipsis` and any bare `maxLines = 1`, with one opt-out: a `//` +line saying why, which six places carry. Proven red twice, and the second time against real +code rather than a planted fault — the comment explaining one cap sat above the `Text(` +instead of above the cap itself. + +**Three documents said 709 Android tests across 90 classes; the suite is 718 across 92.** +The README's «Honest status» table, this file's command cheat-sheet and +`docs/architecture.md` are corrected. A fourth mention is deliberately left standing: this +file records the gates «on the whole tree at `d330d68`, the last commit before the merge», +and at that commit there really were 709 across 90. Rewriting it to today's number would +turn a true record of a named commit into a false one. + +**Every pull request now carries a milestone, and the rule is written down.** Sixty-two had +gone in without one, and they have one only because somebody went back and did it by hand. +There were no issues in this repository then — #128 opened the first — so the milestones +were the only grouping its history had. Seven existed and they are **retrospective**: the +boundaries were read off the history rather than declared, and nothing here has ever been +tagged or released, so `versionName` is still the `0.1.0` default. + +*The milestone table that stood here, with the paragraphs about it, moved to +`HANDOVER.md`, «The milestones», on 27 September 2026: every pull request still adds to it.* + + +From here the rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` skills: +a found defect becomes an issue before it becomes a fix, the pull request ties itself to it +with `Closes #NN`, and a release explains every change with both numbers beside it. + +**What that rule had to record is what a session cannot do.** Nothing here creates a +milestone or even lists one — no tool, no `gh` CLI, and `issue_write` accepts only a number +that already exists. So when none fits, ask the owner with the title and the description +already written, rather than inventing a version or leaving the pull request bare. Two traps +are written down beside it: a milestone's number can be read back by assigning it and +searching `milestone:"<title>"`, whose result embeds the milestone object; and GitHub's +search index lags the write by up to a minute, so `is:pr no:milestone` reported two bare +pull requests that already carried one. The procedure is in the `github-pr` skill, with a +pointing line each in `CLAUDE.md` and `AGENTS.md`. + +**Deliberately left alone.** `:widget` is outside the no-ellipsis rule and cannot be brought +in: Glance has no `TextOverflow` at all, and no marquee either, because RemoteViews has no +frame loop and a widget cannot animate anything. `WidgetStrings.ellipsize` writes the «…» +into the string by hand because the platform leaves no other answer, and the test says so +where it excludes the module rather than letting a vacuous pass look like coverage. +`.github/copilot-instructions.md` did not get the milestone rule: it is short on purpose +because it is read on every request, and every line in it is about what not to suggest +inside code. + +--- + +## Earlier still, on top of the audit + +Twenty-five commits after `13348d5`, in five pieces. The first two finished the audit batch; +the last three are things that batch left behind, and one of them was found by re-reading +the session's own work rather than the project's. + +**A re-check of the whole batch, and then the remainder of it.** The server half: both bells +writes now answer the caller with `silenced_lessons`, because shrinking a schedule leaves +every lesson past its new last rung stored and drawn nowhere and only the bot was saying so; +a substitution on «1 сентября» is no longer refused as a summer date (`school_year_bounds` +files both June and the first days of a September whose 1st falls at a weekend before +`year_start` — the next four are 2029, 2030, 2035 and 2040 — and one sentence covered both); +`render_import_preview` stopped writing its cap +twice; and `MESSAGE_LIMIT`'s comment now names the one direction in which a raw character +count reads *lower* than Telegram's, which is emoji outside the BMP. The Android half reads +that new field and says «2 урока перестали звонить» under «Сохранено». `docs/bot.md` gained +the budget rules, which were true in six renderers and written down nowhere, and `docs/api.md` +documents the field. + +**Three Android gaps closed.** A phone that signed out and rejoined in the same process got +one refresh and then nothing until the next cold start — `schedulePeriodic`'s only caller +watches the interval, and a re-join moves no interval, so the re-arm moved into +`SessionEffects`. The `304` path stopped re-reading the whole cached year to re-derive an +alarm it almost always finds already armed, and asks `FLAG_NO_CREATE` instead; what that +gives up is written where the decision is. And the alarm chain, the change fingerprint and +both of the widget's reads — the redraw and the tick scheduler that arms it, which is the most +frequent read there is — now take a fortnight rather than a year, through `snapshotAroundToday`, +the bounded read that +`docs/` said could not be written, because `schoolDayAfter` has to reach September from July; +it is resolved in SQL beyond the bound and handed over as `nextSchoolDay`. Separately, +`PeriodsForm` keeps its six bell times through a rotation, and `StabilityPromiseTest` is no +longer one regex for `var`. + +**Dependency injection with dishka** (`server/app/di.py`). A session was made in three +places — a FastAPI dependency, `SessionLocal()` in the bot's middleware, and `session_scope` +in `scripts/seed_demo` — each with its own view of whether the caller or the maker commits. +`session_scope` is the one still standing, because a script is not a request and has no scope +to take a session from. It is +now one container: `Settings` and the session factory at app scope, one `AsyncSession` per +HTTP request or Telegram update. All sixty-four endpoints ask with +`session: FromDishka[AsyncSession]` and `db.get_session` is gone; the bot's +`ContextMiddleware` opens the update's scope itself and takes the session from the same +provider, and still commits there. Dishka rather than FastAPI's `Depends`, which is +already a DI system, for one reason: `Depends` cannot serve an aiogram handler. Three things +worth knowing before adding to it are written in the module: it must not import +`dishka.integrations.aiogram` (that puts aiogram on every cold-start path), the container is +built with `STRICT_VALIDATION` so a duplicate provider is an error rather than silent +shadowing, and `app/api/routing.py` exists because dishka's compiled wrapper carries its own +globals, so under postponed annotations FastAPI took an endpoint's `-> Response` for a +response model. + +**An adversarial re-pass over the container work itself**, which found seven things — most +of them latent, one of them behaviour, and several of them defects in what the session had +just written rather than in the project. + +* `write_bell_periods` answered «перестали звонить уроков: N» with a *state* — which rows + these bells do not cover — while the field it fills is documented as an *event*. Nothing + deletes an orphaned row, so the same write repeated said it again, and so did nudging one + bell by five minutes. It asks `lessons_silenced_by` now, which is what the other way of + losing lessons already asked. +* `close_container()` forgets the container, but `setup_dishka` had put a *reference* on + `app.state` at import and a reference does not update itself — so a second lifespan in one + process, which `tests/test_startup.py` is, served every request from a container that had + shut its app scope. The lifespan re-reads `container()` on the way in now. +* A closed dishka container goes on answering, and asking it for an app-scoped object + **builds a new one** in a scope whose exit stack has already run — so nothing will ever + close it. With an app-scoped HTTP client that is a leaked socket per ask. Invisible today + because nothing app-scoped here owns a resource, which is exactly why it is pinned now. +* `setup_dishka` registers one middleware on every observer, each opening a scope on the + *root* container — so a message got two **sibling** scopes, not nested ones, and anything + resolving a session at update level would have had its own that nothing commits. A comment + claimed the opposite and claimed it had been verified; the verification had tested + something else. `ContextMiddleware` opens the one scope itself now, from `container()` read + per update — which also stops the dispatcher `api/telegram.py` caches for the life of the + process serving webhooks from a container closed at shutdown. +* Three documentation defects: `session_scope` named as the cron tick's, the September + comment missing 2030, and three documents still describing the `setup_dishka` arrangement + after it had been replaced. + +The pass also confirmed four things that would otherwise have stayed assumptions: one session +per request across every `@inject`ed dependency including the sync `_service`; the +`MissingGreenlet` branch in `_touch_last_seen` still answering 200 after a failed commit; all +68 routes carrying real response models with `app.openapi()` generating clean; and +`/api/v1/health` still opening zero connections under the new ASGI middleware. + +**One defect found by the clock.** «📒 Неделя» in the diary took its Monday from +`today - today.weekday()`, so on a Sunday it showed the six days that had just ended. It +surfaced as a test that had been wrong since it was written and went red for the first time +after midnight Moscow time on a Sunday. + +That batch is two pieces. The first took two things from +[GMS Flags Reborn](https://github.com/polodarb/GMS-Flags-Reborn) (Apache 2.0, © polodarb) — +the expressive loader and the transformation between first-run steps — and then, on a second +pass over that repository, the two practices this project was actually missing: lazy-list +content types where a list holds mixed shapes (`DocsScreen` alone), and a Compose stability +configuration. The stability one was measured rather than guessed: the compiler's own report +said 36 of 94 classes in `:app` were unstable, almost always for one `LocalDate`, and +`compose-stability.conf` takes that to 29 with every screen state that holds a date now +stable. What is deliberately **not** promised is written at length in that file. Their module +layout, Koin and MVI were deliberately not taken, and their Gradle configuration and CI are +behind this project's rather than ahead — the detail is in `docs/design.md`. + +The second piece is **the nine-area audit protocol run a second time**, by area, each finding +re-verified by hand before it was fixed and each closed by a test proven red without the fix: +**23 defects**, and then a ninth area — the integrity of the test suite itself — found eight +places where CI was green about things it does not check, `api/index.py` among them: nothing +in the repository read the file Vercel routes every request to, so renaming the symbol left +both gates green and every request a 500. Tests: 1391 → 1450 on the server, 605 → 668 on +Android. Three of the seven +batches reported tests that passed on the broken code when first written and rewrote them +rather than shipping them, and **a fourth found a pre-existing test asserting a defect as +correct behaviour** — `test_the_star_moves_when_another_schedule_is_made_the_default` built a +bell schedule with no rows and asserted the star moved onto it. The fixture was given rows; +the fix was not relaxed. That is the **third** time this project has found a test holding a +defect in place. + +The ones that would actually have been felt, one line each: + +* **nobody could sign in to the diary** — `login` read the session cookie with + `response.cookies.get`, which raises `CookieConflict` on the two-cookie answer, and that is + not an `httpx.HTTPError`, so it escaped as a 500 and spent the sign-in ticket every time; + `_session_cookie` was written for exactly that failure and sat one line away; +* eight bot renderers could still send a message Telegram refuses whole — «🗓 Неделя» + measured at 4648 characters, «👥 Доступ» at 4623, and that is the only screen a class on + «по приглашению» can reopen its door from; +* two screens echoed back text the database had truncated, so the confirmation claimed a + subject or a title that was not saved; +* substitutions announced to the whole class and drawn nowhere, from two independent causes — + a replacement with no subject over an empty number, and the summer rule reaching one screen + further than anybody had checked; +* re-pointing a class at a shorter bell schedule took every later lesson off every weekday + with nothing anywhere naming them, and from the bot an **empty** schedule could still be + made the class default, which blanks the phone, the widget, the calendar feed and the + digest at once *and* disables `can_ring`; +* below API 33 the app recreated itself on every cold start for anyone who had chosen a + language, and the recreation ate home-screen widget day-taps; +* the alert chain cancelled itself across any break longer than the planner's eight-day + horizon, with only a cold start to revive it; +* the widget's «Дальше» column listed the lesson an assembly on screen had replaced. + +**What only the owner can do.** Three decisions were deliberately left rather than taken, two +of them in section 7 — the widget's tick cadence, and whether the diary credential should +carry a bound — and the third named in the merged pull request: whether the four API +announcements that interpolate a person's text should carry `shorten`, which is a decision +about what a notification ought to say rather than a defect. Beyond those, an APK on a real +phone is the only thing that can settle the list below, and only the owner has one. + +Gates on the whole tree at `d330d68`, the last commit before the merge: `ruff` clean, +`python -m mypy` clean across all 81 modules, `pytest -q -n auto` 1465 passed; +`./gradlew test assembleDebug assembleRelease` successful with 709 Android tests across 90 +classes and 0 failures. CI was green on that head and on the four before it. + +**What nothing has verified**, and it is now on `main` rather than proposed: + +* **None of the Android work has run on a real phone.** The `304` path and the widget's + bounded read are claims about battery that only a device can confirm; what the first gives + up is written where the decision is — it trusts a `PendingIntent`'s existence as proof an + alarm stands, so a vendor battery manager that drops one and keeps the other is not healed + there. `BellRowsRotationTest` uses `StateRestorationTester`, which re-composes rather than + killing the process, so it proves the saver round-trips and not that the bundle survives a + real low-memory kill. «2 урока перестали звонить» has never been drawn. +* **`BoundedSnapshotParityTest` reproduces the bound rather than driving the real + repository.** `CachedWindow` and the in-memory DAO are `internal` to `:core:data` and + Kotlin `internal` does not cross a Gradle module, so driving them from `:widget` would mean + adding `testFixtures` to another module's surface for one test. It is reproduced locally + the way `WidgetSizeClassTest` reproduces the launcher's rule; `CachedWindowTest` owns the + other half — that the repository implements that bound against the real DAO. +* **The dishka wiring has now run on Vercel** — see the warmup read above, which is one + request and not a measurement. The 26 ms it adds to a cold start is still measured on a + development machine rather than there, and that the webhook path still defers aiogram is + read off the imports rather than timed there. +* **The bot has not been driven end to end since the container moved under it.** Every + handler is covered by tests that call it directly with a session; nothing in the suite + feeds a real update through `build_dispatcher()`, so `ContextMiddleware` opening its own + scope is proven by unit tests and by reading, not by an update arriving from Telegram. + +Before this batch, after PRs #47, #48, #49, #50 and #51 were merged. The +last of them is the agent configuration in `.claude/` and the whole written layer of the +project moved into English (see "Everything written about the project is English" in +section 6). It landed as `85064cd`, and `main` and `dev` are level. The database is at +head `0013` and `EXPECTED_REVISION` did not move, so that merge needed no migration. The +production deployment it triggered is `READY` on `85064cd`, and `/api/v1/warmup` was read +after it: `{"status":"ok","api_version":1,"schema":"0013"}`. That endpoint opens a +connection, so it answers for the database too, not only for the code. + +After that batch, two small ones: #55 and #56 corrected this file's own header — it said +PR #51 was open minutes after it had been merged — and a sweep over every document +re-measured the numbers they quote. What that sweep found is at the end of section 6. + +Two batches earlier: publishing the repository and everything that followed from it (the +history reviewed for secrets, `pytest` in CI spread across cores, artifacts living a +week), a deployment that refuses to start rather than quietly taking a local default, and +the Google Sans Flex licence — it is OFL 1.1 rather than MIT, as the comment and the +documentation claimed: the licence text now travels inside the APK, stands as the eighth +row under «Лицензии», and `FontLicenceTest` reads the typeface's own `name` table so that +what is claimed and what lies beside it cannot drift apart. + +**PR #50 is merged**, five commits; it needed no migration — the model did not change and the +head stayed `0013`. The first two commits are the translation-correction mode across all of +the app's text (see "The correction mode knows about all the text" in section 6 and the new +section of `docs/design.md`). The other three are **an audit of the whole project by nine +subagents, split by area**: the API, the bot, `services` + `schedule` + `models`, the +providers + config + migrations, `:core:model` + `:core:data`, the design system + the +widget, `:app`, the correction mode itself, and separately the build, CI, the scripts and +the integrity of the test suite. + +Thirty-one findings, every one verified by hand before it was fixed; each closed by a test +that fails on the code without it. Tests: 1362 → 1391 on the server, 578 → 605 on Android. +The most serious, one sentence each: + +* five of the bot's renderers and the evening digest went past Telegram's 4096 characters — + the message is refused whole, and `/today` (a plain `answer`) replied with nothing; +* an empty bell schedule could be made a class's default: `/bundle` handed back zero + lessons, `/now` said «выходной» on a Monday, and the timetable lay untouched throughout; +* renaming a subject onto a name that exists only in the homework failed with a 500 and lost + the rename entirely; +* shortening the bells silently took every lesson above the new ceiling off the timetable; +* a `401` on `/bundle` never reached `onTokenRejected` — a `Response<T>` in Retrofit does not + throw — and a revoked device kept a class and a year of somebody else's data; +* a `304` against an empty cache answered "success" for ever: the app stayed empty; +* a duplicated session cookie dropped the whole diary into a 500 on every call; +* `POST /diary/login` was an unlimited password oracle against somebody else's service; +* a release tag could publish an APK signed with the debug key — the gate checked one secret + of four; +* `seed_demo` wrote to wherever `DATABASE_URL` pointed, saying nothing about it. + +**Three tests asserted the defect as correct behaviour** and were replaced. The full list of +findings and what was done with each is in the bodies of commits `5ec62a6`, `afba3c5`, +`b8d8deb` and `3997b29`. + +What is still open: + +1. **The external cron is not set up.** Until it is, the digests go out whenever GitHub + deigns to run the schedule — measured at 6.7 times a day instead of 288. The bot's promise + that they arrive "within about five minutes" is untrue until then. What exactly to set up + is in `docs/deploy.md`, "The clock". +2. **The production Neon endpoint's host and the project id stayed in the history.** They are + out of the working tree, but the repository is public and that does not change the + history. The owner changed the role's password and updated `DATABASE_URL` in Vercel, so + the address in the history is no longer enough on its own. **The variable is set for + Production only:** Preview fails with `ModuleNotFoundError: No module named 'aiosqlite'` — + which is the refusal at the door, just from before it learned to name itself. Either set + it for Preview too, or do not look at preview deployments. + +If you are an agent: `CLAUDE.md` first (the project's rules), then this file (what is already +done and what is left), and the agent configuration is in `.claude/` (see section 6, "The +agent configuration lives in `.claude/`"). Treat everything below as verified fact as of the +date above, but **re-check the branches and CI before your first action** — they live their +own lives, and this file goes stale the moment it stops being updated. + +--- + +## 1. In one paragraph + +**There are exactly two branches, `main` and `dev`,** and after PR #43 they met. Everything +that had piled up in `dev` is now in `main`: the former working branch, five dependabot +branches — cryptography, asyncpg, AGP, the androidx group and the Gradle wrapper — and eight +substantive commits on top. The six original branches are deleted and their pull requests +(#35, #36, #38, #39, #41, #42) are closed with the status **Closed rather than Merged**: +GitHub counts a pull request as merged only when its commits reached its own base, and the +base for all six was `main`. The code was not lost: it arrived through #43. + +On top of that, ten substantive commits landed in `dev`: + +* `8ec2e31` — a phone holds several classes at once and switches between them; +* `569bab8` — six defects that four audits found in `8ec2e31`. The first is serious: a `401` + on one class threw the device out of **all** of them; +* `ce02348` — corrections laid over the diary, with an undo, and revision `0009`; +* `c6ba66c` — fifteen findings from two audits of `ce02348`; +* `59c7a77` — the class's join mode, the personal connect codes, revisions `0010` and `0011`, + and seven findings from one more audit; +* `98c8018` — the database brought up to `0011` through the Neon connector, **before** the + merge; +* `70b9dcb` — a `429` on the code screen says how long to wait rather than "HTTP 429"; +* `ab488ad` — twenty-one findings from three audits: Android, the bot and the documentation; +* `8aa4ecd` — three of the app's screens are pressed in the build (Robolectric in `:app`); +* `bf74233` — «🗓 Четверти» crashed in production on every press; fixed; +* `a58d2be` — the "does the code reach for an attribute that does not exist" check across the + whole server; `rows_affected`; thirteen tests on the flows in `content.py`; +* `33deca3` — the rest of the bot's cards are drawn in tests, and eight of them turned out to + be broken; +* `a9be1c4` — every drawn row has a button, the alert is cut at Telegram's ceiling, a dead + renderer is deleted; +* `6a1dded` — a forged press gets a refusal rather than an endless spinner; +* `f3839c8` — a date that is not in the calendar is rejected rather than crashing the handler; +* `c2038e4` — an event's kind and a lesson's number are checked where they are picked; +* `1d84d89` — a far-away date answers 422 rather than 500, and `PATCH /tasks` does not put + NULL into a NOT NULL; +* `ae8e3b8` — the countdown and the quarter speak the phone's language; the translation guard + is extended from one module to all four; +* `8cba40b` — seven findings in the adapters and the plumbing: the diary no longer loses a + lesson's time or an only child; +* `94ea9b5` — a bell schedule is read by its numbers rather than by its row count; four + findings in the shared rules; +* `4f5471d` — the template stopped expanding all summer; a substitution and a pasted day + check the bell; one assignment per subject per day; revisions `0012` and `0013`; +* `3a592c9` — the diary sign-in page stopped blaming the password; `httpx` pinned; the + turnstile, a token made of spaces, a rolled-back transaction in `current_revision`; +* `69bf4ba` — one link, one sign-in; `/bundle` does not fail after losing the race to seed + the terms; the subjects screen does not throw away its own link. + +The fourth pass (four subagents over four non-overlapping zones, every finding re-checked +here by reverting the fix rather than taken on trust): + +* `ea3afc8` — "N skipped, no bell" counts rows rather than numbers; +* `24b4841` — the diary notices a changed response shape instead of an empty week; +* `7712dc7` — `scripts.init_db` stamps `alembic_version`; `requirements.txt` is kept level + with `pyproject.toml` by tests rather than by attentiveness; +* `8bec2ff` — the selected class survived the sweeping of abandoned dialogues; +* `0c99993` — revoked access takes the class's subscriptions with it; +* `8995fa6` — the role in the menu, the time of the first digest, the length of the homework + digest; +* `38e8aec` — a day cannot be hung on a bell schedule with no rows; +* `bf2338d` — signing into the diary with no `DIARY_SECRET` answers 503 rather than 500; +* `591b3a4` — «Выйти» from the diary leaves no second live session behind; +* `7c99652` — every notification has its own press target; the widget does not hide the room + for the sake of a teacher who is not there; +* `cc3935e` — deleting a lesson does not shift its neighbour onto a number with no bell; the + "collect from the timetable" counter stopped counting other classes' rows as its own. + +The fifth pass — what the fourth named but did not do: + +* `a47d58c` — on a failed read the widget does not push you to "enter a class code"; the one + unverifiable minute setting is brought into a range; +* `1676915` — the webhook checks the secret before parsing the body, and the sign-in form's + body ceiling is measured on the way rather than after everything is already in memory; +* `a0fe48b` — one calendar link per class (a conditional `UPDATE` and a read back), and the + digest assembled inside a savepoint, so that one failing class does not take the whole tick + down on Postgres; +* `060f385` — cancelling a lesson that is not in that day is rejected: it used to go into the + log and out to every subscriber, and be drawn nowhere. + +The sixth pass — both of the owner's decisions taken and done: + +* `f0ba014` — a date outside the school year reads as `DayOff(HOLIDAY)` rather than "no + data": in summer the widget says «Каникулы» and shows the homework for 1 September instead + of asking to be pulled down for something that was never coming. A date **inside** the year + with an empty cache stayed `NoData` — there, pulling down is exactly what helps; +* `5b10815` — the client sends `If-None-Match`. The tag sits in DataStore under the request's + signature (class, `start`, `days`), so 1 September and a change of class simply stop + matching and the next sync asks for the whole window. A `304` does not write to Room and + does **not** wake the widget, but it does move "updated N ago": that line is about the + check rather than about the data. + +**Section 3.1 was closed entirely when this was written.** One requested item has been +added since and is open: scrolling the calendar by years, which is a decision rather than +work — see section 7. + +The block below is **the state on the day this section was written**, kept because the +migration order it records is the thing worth reading twice. It is not today's: the +branches, the open pull request and the two test counts have all moved since, and the +paragraph at the very top of this file is the one that is kept current. + +``` +As of PR #51 — not current; see the top of this file +Merged: PR #43, PR #44, PR #45 (six passes, 38 commits, merge 26ad184), + then PR #47, #48, #49 and #50 — main at 22399e9 +Open: PR #51 (dev → main) — the agent configuration, and this translation +Branches: main and dev; dev runs from 22399e9, that is, from the merge of #50 +Gates: ruff clean, mypy clean, 1391 server tests, 605 Android, both assembles +Database: production at 0013, which is the head. 0010–0012 were applied through + the Neon connector BEFORE the merge, 0013 (a UNIQUE) AFTER, as its + shape requires. No separate database action is outstanding +``` + +**A merge to `main` is a deploy.** Vercel builds `main` by itself. The order was mixed this +time, and deliberately so: `0010`–`0012` went into the database in advance, so the window in +which the code knows a column the database does not have never opened for a second, while +`0013` — a constraint that the **old** code breaks against — went on immediately after the +merge. Between them `services/homework.py` behaved exactly as production did before it. One +request checks that it all lines up: + +```bash +curl -s https://<project>.vercel.app/api/v1/warmup # {"status":"ok","schema":"0013"} +``` + +A `"degraded"` here would mean the deploy had not arrived; before `0013` was applied, the +same request honestly called the database behind, because `EXPECTED_REVISION` was already +`0013`. The head is `0017` today — see the top of this file — and the same request reads it +the other way round while a revision waits for its merge: the database is *ahead* of the +code, and `/warmup` says so in as many words, «База впереди кода…». + +**The five dependabot pull requests can now be closed without regret** — their bumps arrived +in `main` together with `dev`. If it managed to recreate them before the merge, they will +turn empty by themselves. + +*«How to continue», the last part of this section, stayed in `HANDOVER.md`, at the end of +section 8.* + +--- + +## 2. What has been done + +Bottom up. The details of each are in its commit body and in the description of PR #43; this +is only so that you do not have to go looking. + +| Commit | What it did | +| --- | --- | +| `b7c82d1` | The bottom fade starts where Essentials' does (130 dp) | +| `aacf886` | Three defects found by comparing against Essentials: `CrashReporter`, `AppLocale`, `derivedStateOf` | +| `478861e` | The timetable's horizon is a school year, not a month from Monday | +| `cf01b96` | A class by its number and letter; quarters and half-years; revision `0008` | +| `d2d8d23` | `CLAUDE.md`: migrations are applied through the Neon connector | +| `9b7b907` | The schools registry behind `providers/dadata/`, searchable in the bot and the app | +| `af20180` | A `401` on a class token drops the session and the cache | +| `fc9989f` | The subject dictionary and the timetable are one list | +| `92518c5` | Twelve defects from two audits of fresh code | +| `bd4ce41` | Week parity, the calendar's UIDs, the two alarm chains | +| `ef6e530` | One tick per digest; a shortened day with no bells is refused | +| `c35ebd3` | CI: `setup-android` pinned to `v4.0.1` + `packages: platform-tools` | +| `236b259` | Quoting in the timetable export; a lesson with no bell is not written | +| `e5cc939` | `pyproject.toml` level with `requirements.txt` after the pip bumps | +| `bfa1689` | What compose-bom 2026.09.00 did to the intercepting layer | +| `e55ea2f` | This file, on `dev` rather than on one working branch | +| `a1bbeb5` | This file, brought to the facts: six branches closed, one live pull request | +| `8ec2e31` | Several classes on one phone, and switching between them | +| `569bab8` | Six defects from the audit of `8ec2e31`; a `401` drops one class, not all | +| `ce02348` | Corrections over the diary, with an undo; revision `0009` | +| `c6ba66c` | Fifteen findings from two audits of `ce02348` | +| `59c7a77` | The class's join mode and the personal codes; revisions `0010` and `0011` | +| `98c8018` | The database brought up to `0011` | +| `70b9dcb` | The `429` on the code screen, in minutes rather than "HTTP 429 Too Many Requests" | +| `8aa4ecd` | Three of the app's screens are pressed in the build: Robolectric in `:app` | +| `bf74233` | «🗓 Четверти» crashed in production on every press; the rendering is covered | +| `a58d2be` | The "attribute that does not exist" check across the whole server; `rows_affected` | +| `33deca3` | The bot's cards drawn in tests; eight turned out to be broken | +| `a9be1c4` | Every row of a list is reachable by a button; the alert is cut at 200 | +| `6a1dded` | A forged press gets a refusal; the order of memberships is fixed | +| `f3839c8` | A day offset out of callback data does not overflow the date | +| `c2038e4` | An event's kind and a lesson's number are checked where they are picked | +| `1d84d89` | 422 instead of 500 on a far-away date; NULL into a NOT NULL refused | +| `ae8e3b8` | The countdown and the quarter localised; the translation guard across all modules | +| `8cba40b` | Seven findings in the providers, the config, the FSM and the database URL parsing | +| `94ea9b5` | Bells by number; a slot does not double; a quarter on the diary's clock | +| `4f5471d` | A summer with no lessons; the bell under a substitution and a paste; revisions `0012`/`0013` | +| `3a592c9` | The diary sign-in does not blame the password; `httpx` with an upper bound | +| `69bf4ba` | Two races closed with a conditional UPDATE and a savepoint | +| `ea3afc8` | The import counts dropped rows rather than their numbers | +| `24b4841` | The diary notices a changed response shape instead of answering with an empty week | +| `7712dc7` | The revision stamp after `init_db`; the `requirements.txt` mirror under test | +| `8bec2ff` | The selected class is not swept up along with the dialogues | +| `0c99993` | Revoked access takes the class's subscriptions with it | +| `8995fa6` | The role in the menu, the time of the first digest, the length of the homework digest | +| `38e8aec` | A day is not hung on a bell schedule with no rows | +| `bf2338d` | Signing into the diary with no key is a 503, not a 500 | +| `591b3a4` | «Выйти» from the diary leaves no second session | +| `7c99652` | Each notification has its own press target; the room in the widget | +| `cc3935e` | Deleting a lesson does not shift its neighbour onto a number with no bell | + +**There were thirteen audits on this branch.** Four of the early work (sixteen findings), +four of `8ec2e31` (six), two of `ce02348` (fifteen) and one of `59c7a77` (seven); three +covering Android, the bot and the documentation (`ab488ad`), and the last two, which drew the +bot's cards and found nine defects (`bf74233`, `33deca3`). The heaviest of the lot: week +parity was computed from the ISO week number, which does not alternate in a 53-week year — so +from January 2027 the whole denominator of the **current** school year slid by a week, +simultaneously in the API, the widget, the digests and the calendar. + +**Migrations:** the last revision written is `0017`, and production is at `0017`. +`0007`–`0012` were applied **before** their merge through the Neon connector, `0013` after it +(it adds a `UNIQUE`, and a constraint migrates in the opposite direction from a column), and +`0014` before it again. `0015`, `0016` and `0017`, all written on #140, went on before #140's +merge, in one transaction. `0017` rewrites a key, which on a database holding rows goes on +after the merge; production held none. «Schema» in that batch's section at the top of this +file has what the database said. What each earlier revision did is in `CLAUDE.md` and in section 7, +item 1. + +--- + +## 3. What has NOT been done + +### 3.1. The features that were requested — all of them are done + +**No requested work is left untaken.** The one item that was open here — scrolling the +calendar by years — was a decision rather than work, the owner made it on 21 September +2026 (the windowed sync, not the picker bound to the synced year), and it is done. The +section is kept struck through rather than deleted: it shows what exactly was asked for +and what it turned out to be. + +**One request has come in since, and it is on #140.** On 25 September the owner asked for a +way in through the family's own school's diary, with the password never reaching our server +(#141). It is built — the first run, the diary-only home, the legal line, the catalog and the +directory — and closes when #140 merges; what nobody has verified about it is in section 5. + +~~1. **A pupil choosing their own class.**~~ Done in `8ec2e31`. The phone keeps a list of + memberships, shows one of them and switches instantly; the cache is split by class, so + switching works with no network too. What exactly is unverified is in section 5. +~~2. **Corrections over dnevnik2's data, with a reset.**~~ Done in `ce02348`. Pressing a + lesson or an assignment opens a window where the fields can be rewritten; under each it + says what the diary actually holds. Nothing goes upstream, marks and the turnstile cannot + be corrected, and the bot does not show corrections (section 6). +~~3. **Two modes on invitation, and a reversible switch between them.**~~ The statement was + clarified with the owner: this is the **class's join mode**. Done — `join_mode` on a + class, `open` or `invite`; in `invite` the class code lets nobody in and a phone joins + with a personal one-time code from the bot. The switch is reversible and disconnects not + one already-connected phone. The details are in section 6, "Who lets a phone in". + +### 3.2. What does not exist at all (long-standing gaps, not regressions) + +The same as the "What does not exist at all" section of `README.md`: + +- Attachments to homework: the `attachment_url` field is in the schema, there is no upload. +- A link between a class and a registry record: only the school's name is stored, so a rename + in the company register passes the class unnoticed. +- The widget stays on the system font: Glance passes `fontFamily` as the name of a system + family rather than as a resource. + +And two that #140 left out on purpose, which are issues rather than lines in `README.md`'s +list: + +- A phone that reads only its diary gets nothing from it in the widget, «Сегодня», + «Календарь» or the alerts (#142). +- A diary session opened on the phone is invisible to the bot (#143). + +### 3.3. The typeface's licence — closed, and not the way this said + +**`google_sans_flex.ttf` is under SIL Open Font License 1.1**, Copyright 2015 Google LLC. The +typeface declares that itself, in its `name` table, records 13 and 14. This section and the +comment in `theme/Type.kt` said "MIT, from Essentials" and concluded that the typeface was +non-free and had to be removed before publication; neither held up once the file was finally +opened and read. + +`FontLicenceTest` in `:core:designsystem` holds this: it parses the `name` table of every +font in the tree and requires a notice under `assets/licenses/` with the same copyright and +the same licence, and that it be the text rather than a link. The link between the file and +the notice used to rest on nothing — move one and the build would stay green. + +There is nothing to remove. What was done is what the licence actually requires: the OFL text +is placed next to the font in `assets/licenses/` — so it travels inside the APK, as "a copy +of the licence accompanies a copy of the font" — the licence is named in the app on the +«Лицензии» sheet, and neither the comment nor `docs/design.md` asserts something untrue any +more. No Reserved Font Name is declared, the file is not modified, and the "Google Sans" +trademark stays a trademark: bundling is allowed, naming a product after it is not. + +--- + +## 4. Open defects: none that #140 does not fix, and one fix that waits for a phone + +**The defects open as this is written are the ones #140 fixes.** #136–#138 and #145–#160 are +all fixed on its branch and meant to close with its merge — the table is in that batch's +section at the top of this file. The exception is **#156**: crash reports are now excluded +from every backup path in the rule files and a test reads both, but whether a phone's backup +really leaves them out takes a phone and `bmgr`, so the issue stays open, `needs:device`. +Everything below is the record from before the tracker, and it still holds. + +All sixteen findings of the first four audits are closed, as are all six findings of the four +audits of `8ec2e31` (`569bab8`), the fifteen of `ce02348` (`c6ba66c`), the seven of `59c7a77` +and every finding of the last three audits — Android, the bot and the documentation. And five +of the six defects `docs/design.md` carried under "known and not yet fixed". The sixth — the +screenshot on the main thread — turned out not to be a defect but a platform limitation +(`View.draw` is obliged to run on the UI thread) and was rewritten into "Limitations". + +**Do not file these again as bugs.** If a new session's audit names something from the list +below again, check the code first for whether it is already closed: + +- week parity from the ISO number → now counted from the start of the school year; +- positional UIDs in the calendar → now a row's identifier; +- `setWindow` in the widget's alarms → now `setAndAllowWhileIdle`; +- `SchoolAlerts.fire` with unprotected publishing → every publication in a `runCatching`; +- `mark_sent` after the selection → now `claim`, a conditional `UPDATE`; +- `MAX_INDEX = 20` as a day's ceiling → now a ceiling from the class's bell count; +- the timetable export without escaping commas → quoting, plus the last field taking the + remainder; +- `LARGE` hid the homework → the `LARGE_TALL` threshold lowered from 400 to 300 dp; +- `OverlayLayerTest` "failing" on the intercepting layer → **not a defect**: the test was + rewritten for compose-bom 2026.09.00, which changed Compose's behaviour. It was red exactly + once, at the merge; see section 6. + +The six multi-class findings closed in `569bab8` — do not file those again either: + +- `onTokenRejected` called `signOut` → now `leaveActive`, and a `401` on one class drops only + that one; +- the membership list was decoded as a whole → now per entry, so one broken row does not take + the rest with it; +- `syncNow` with `KEEP` swallowed the sync after a switch → the switch now uses + `APPEND_OR_REPLACE`; +- leaving a class that was **not** on screen cleared the timetable fingerprint → now only + when the active class actually changed; +- a notification from the previous class stayed in the shade → switching removes it; +- an in-flight sync resurrected rows of a class that had been left → `retainOnly` sweeps them + at the start of every sync. + +The findings of the last three audits are closed too, and these are the ones easiest to find +a second time: + +- an enum's `server_default` written through `.value` → now `.name`; the column holds `OPEN`, + and three tests check it (section 6); +- `burn` assigned an attribute → now a conditional `UPDATE`, and `/join` burns the code + before it issues a token; +- the mode button was a toggle → it now carries the mode it wants; +- joining with a personal code was not written to the log → `device.link` is now written in + `/join`; +- revoking a member did not kill their unissued codes → now `drop_for`; +- `session.refresh` after a swallowed rollback stood outside the `try` and could replace a + `401` with `X-Diary-Reauth` → now `_refresh_quietly`, and the same in `api/deps.py`; +- `mint` deleted spent codes along with live ones → now live ones only; +- `_is_iso_date` accepted `20260915` and `2026-W38-1` → now `YYYY-MM-DD` only; +- the `429` on the code screen was drawn as "HTTP 429 Too Many Requests" → now a Russian + sentence with the number of minutes from `Retry-After`; +- `join_error_generic` became unreachable and an English sentence went out in its place → + `JoinError.of` reads the classified refusal rather than the raw one; +- a row with no `target` was pressable and led to a `422` → now `correctable`; +- the correction window could stay over the sign-in form → `applyFailure` closes it together + with any request for a password; +- four comments asserted things the code does not do → rewritten to the facts. + +And nine came not from an audit but from the bot's cards finally being **drawn in a test**. +The first came from production: the owner pressed «🗓 Четверти» and got an error dialog. + +- `_terms_card` printed `term.days`, and `Term` has no such attribute: `days` belonged to + `TermView` — "a flattened copy of a term for a renderer with no session" — which **no code + path ever created**. The line was written against a type that never reaches it, and the + only way to find out was to press the button. `days` moved onto the model, the dead twin + was deleted, and the rendering is covered by tests. + +The other eight are from `33deca3`, and two of them took the whole screen: + +- **the diary escaped nothing** that the external service sent: the subject, the room, the + teacher, the topic, the assignment's text. Telegram refuses **the whole message** on one + angle bracket, so «реши § 4 при a<b» left a parent with no timetable at all; +- **the editor did not escape a subject's name**, while the paste grammar accepts «Алгебра + <7>» whole — one bracket, and the editor does not draw the day it is editing; +- a slot's card showed its own tags to a viewer: `answerCallbackQuery` has no parse mode → + `editor_render.as_alert`; +- `plural` prints the number itself, and three places printed it again («перемена · 10 10 + минут»). One of the three **had a test**, and it passed: «10 минут» is a substring of + «10 10 минут»; +- the import preview put the line about the bells under its own footer, so a paste of nothing + but bells read as "not one day recognised" above a button that was about to replace those + bells; +- the import's result counted what was parsed rather than what was written, and contradicted + itself on adjacent lines; +- `render_bells` silently lost the tail of the list past `LIST_MAX`; +- `_next_day_line` indexed an empty list; +- three list pages out of four drew more rows than there were buttons beneath them: forty + subjects over thirty ✏️, twenty bell schedules over ten, twenty phones over fifteen. The + tail was visible, unreachable and unexplained; «Особые дни» agreed with itself by accident — + both sides said 20. Each page now has one number for both + (`manage_render.SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX`, `LIST_MAX`), and + `test_no_list_page_draws_a_row_the_keyboard_cannot_reach` checks it: it asks the keyboard, + by row id, which of the drawn rows it carries; +- the alert from a lesson's card measured 284 characters on a doubled lesson — + `answerCallbackQuery` returns 400 past 200, that is, an endless spinner; +- `diary_render.student_line` was called by nobody: a dead renderer of the same shape as the + one that crashed «🗓 Четверти». Deleted. + +**The second pass over defects** (four agents over non-overlapping areas plus a slice of my +own; every finding has a test that fails with a real error if the fix is removed): + +- **two role-picking screens caught one press.** The invite-by-number handler stood on + `RolePick.filter()` — on *any* role press while its state was live. An admin who had + started "invite by number" and then pressed a role on an older «Новая роль» card created a + **phone invitation** and got a success message about a number rather than about a person; +- three bare conversions from callback data in `access.py` (`int(target)`, `int(value)`, + `Role(role)`) — the one file of the bot the check that closed this in `manage.py` never + reached. A bare `int()` does not refuse a press, it **escapes the handler**: + `callback.answer()` is never called and the button spins until Telegram gives up; +- `timedelta(days=…)` from callback data in three paging screens (day, week, diary) — an + `OverflowError` rather than a far-away day; +- an event's kind and a lesson's number in `content.py` were stored raw and turned into an + `EventKind` / an `int` three questions later — exactly what the comment a line above in the + same file warns about; +- the order of memberships was undefined while three places read it as meaningful, including + **the order of the «🔀 Сменить класс» buttons**; +- `GET /homework?from=9999-12-31` answered 500 (the window arithmetic ran before the bounds + check); the same in the diary's `_range`; `PATCH /tasks` with `{"title": null}` put NULL + into a NOT NULL column; +- the diary lost **a lesson's time** when the upstream answers in ISO, and **a whole child** + when the first `educations` entry is unreadable; a failed sign-in was reported to the phone + as "the session expired", so the person retyped their password endlessly; +- «МБОУ "СОШ № 197"» was drawn as «МБОУ "Сош № 197"»; a typo in `TIMEZONE` crashed `/start`; + `state.clear()` wrote an empty string to the database (113 such places in the bot); + `describe()` leaked the tail of a password containing an `@`; +- on the phone: the countdown — the largest digits on the home screen — was Russian under an + English caption, the calendar's heading read «October 2026 · 1 четверть», and a `401` in + the diary **crashed the app** if the write to disk failed. +- **the lesson ceiling was counted from the number of bells rather than from their numbers.** + The paste grammar allows a gap, and a class with bells at 1, 2, 4 got both errors at once: + «4. Химия» was rejected with the words "there is no such bell" — about a bell from the same + paste — while the editor would have written a third lesson the class does not ring; +- **a timetable slot could get a second row shadowing the first.** `uq_timetable_cell` does + not forbid "every week" and "numerator" on one lesson, both pass the parity filter, and + `_load` selects with no `ORDER BY` — the database decided what the phone would draw, and + the answer could differ between two reads; +- **a task's reminder was claimed by an attribute rather than by the database.** The digests + obey the rule in the module's docstring, the tasks did not, and two overlapping ticks sent + «⏰ Напоминание» twice; +- the diary's "current quarter" was read on the server's clock rather than the diary's: on + the evening of a quarter's first day the subjects screen arrived empty. + +**Not a finding but an honest caveat.** The order of memberships has no test that fails +before the fix: the tests run on SQLite, which returns insertion order both with and without +an `ORDER BY`. The test left there is a guard, not a reproduction. + +**The third pass — what the owner named, item by item** (`4f5471d`, `3a592c9`): + +- **the template expanded in June, July and August.** `SCHOOL_YEAR_END_MONTH` is 5 and the + comment beside it says the template must not repeat from June — and `_resolve_day` never + read that constant. A summer weekday arrived full on the phone, in the widget, in the + calendar feed and in the morning digest, whose **own** rule about staying silent on an + empty day could never fire: the day was not empty; +- **a substitution could be written onto a number with no bell** — it went into the log and + into a «🔁 Замена … урок №8» notification, and was drawn by nobody. The check is now in both + shells and **against that day's bells** (`rung_indexes_on`), because a shortened day rings + shorter than an ordinary one; +- **the bot's single-day paste went round `apply_timetable`** — the one entrance into the + template without all of its checking. Eight lessons into a class that rings seven gave + "lessons saved — 8" and a list of eight; +- **two people saving one assignment at the same time got two.** Both shells promised "one + assignment per subject per day" in their own docstrings; it is now one + `services/homework.py`; +- **the diary sign-in page blamed the password for any of somebody else's errors** — a person + retyped a correct password until they gave up; +- `httpx` had no upper bound while depending on a deprecated capability; the turnstile read + an unrecognised direction as "exit"; a token made of spaces looked like an exhausted quota; + `current_revision` left the Postgres transaction aborted. + +- **two read-then-write races.** `diary_link.claim` read the ticket, checked it in Python and + then assigned `used_at`: two simultaneous sign-ins got two diary sessions for one account. + And `GET /api/v1/bundle` seeds the terms for a new class — while every phone in the class + polls it on one timer, so "both found the year unseeded" is the ordinary case, and on + Postgres the second got an `IntegrityError`, that is, **a 500 on a read**; +- `GET /api/v1/manage/subjects` linked lessons to the dictionary and **committed only if it + had created something**: for a class with a full dictionary and unlinked lessons the + UPDATEs ran and were thrown away on every read. It was only cured by `/bundle` committing + unconditionally. + +**Where I disagreed with an agent.** It proposed handing the sign-in ticket back on an +"incomprehensible answer" from the diary too. We cannot tell a captcha from a wrong password: +a Yii form answers a wrong password with the same "200 with some HTML". Handing the ticket +back on such an answer would make the link an unlimited oracle for guessing a password from +our address — precisely what spending the ticket in advance is for. The hand-back is narrowed +to "the diary did not answer at all"; the message stopped blaming the password in both cases, +and that was the defect. + +**The three the first real build found** (#79) are closed too, and are worth knowing about +because none of them is the kind an audit finds by reading: a `LazyColumn` key that was +never interpolated, a fixed-height fade inside a view whose height is whatever is left, and +`cameraDistance` multiplied by the density. All three are measurements. All three passed +every test that asked whether the screen was *built*, and all three fail the one that asks +whether its rows are **displayed**. If an agent proposes any of them again, check +`DayRibbonView.kt` first. + +**And the six from the build after it** (#80), which are the same family one step wider — +every one is a layout or a default that nothing in the code reads as wrong: + +- a marquee left on `MarqueeDefaults.Iterations`, so a title stops scrolling after three + passes and sits clipped — per composition, so two rows of one list disagree; +- a screen title sharing a `Row` with four controls under `weight(1f)`, which is the + correct way to share a row and the wrong amount of room; +- a button that appears and disappears without its slot being kept, so everything beside it + moves 48 dp between two presses; +- a container radius picked as a token rather than derived from what is inside it; +- an item that pads itself inside a list that already pads every item; +- `retention-days:` asking for more than the repository allows, which is silently reduced. + +The last one is not an Android defect and is listed with them on purpose: it is the same +shape. **A number written next to the thing that overrides it is a wish, not a setting**, +and three documents had been quoting the wish for months. + +**And one from #81, which is the family's sharpest member**: a test that asserted how its +own build was configured. `AboutCardTest` read `BuildProvenance.current()` and asserted the +badge that a build told nothing about itself draws — so it passed under `ci.yml`, which +sets no build properties, and failed under `apk.yml`, which sets them all. Green on every +pull request; red only in the workflow whose job is to produce an APK. **A test that reads +a global is a test of the environment**, and the environment a test runs in is not the one +the code ships in. + +--- + +## Moved out of section 5 on 27 September 2026 + +Two bullets of `HANDOVER.md`'s «What nobody has verified» that stopped being true: the frame +after a drag, which #180 and #85 closed, and the warmup request, which was read against +production on 26 September 2026. + +- **There was a window of a frame or two after the drag, and it was written here as + inherent. It was not (#180):** between the drag ending and the preferences answering, the + pager's index still names the old order, and the bar read its selection from that index — + so the selected circle hopped for a frame. It reads the tab being kept on now. The + other one — a frame of the pre-drag order at the moment the mode closes — was written down + here as deliberate and is closed by #85. +- **`/api/v1/warmup` was read on 26 September 2026** through the Vercel connector, which + carries the owner's access — `"schema":"0017"`; see the opening. What follows was true + until then. The deployments are behind Vercel's Deployment + Protection and answer a redirect to a login page, so no `curl` from here can settle + whether the schema — `0017` once #140 has deployed — and the code that needs it + met. It needs the owner's browser or a bypass + token; it has been outstanding since #61 and it is in section 7 for that reason. + +## Moved out of section 6 on 27 September 2026 + +What `HANDOVER.md`'s «What you need to know so as not to break things» carried until then +and no longer needs: a paragraph about an APK artifact that later builds replaced; eleven +subsections retelling, in older words, rules `CLAUDE.md` carries; one describing `.claude/`, +which `.claude/README.md` describes; and two narrating batches that are done. Where one of +them disagrees with `CLAUDE.md` — the school year ends when the class's own terms say so, +not on a date, and a lesson's ceiling is the set of bell numbers, not their count — +`CLAUDE.md` is the later word. + +The APK's "Run workflow" takes `main` by default, and after the merge that is finally the +right branch. The last build sitting in the artifacts — +[run 34948610365](https://github.com/lumenpearson/lessons/actions/runs/34948610365), the +`lessons-apk` artifact — was made from the former working branch, that is, **without** AGP +9.4.0, Gradle 9.7.1, the new compose-bom and everything described in this file. Build it +again: that combination has gone through on the runner many times, but nobody has held an +APK with it in their hands. + +### Everything that came from outside is escaped before it is sent + +The bot sends HTML, and on one angle bracket Telegram refuses **the whole message** rather +than spoiling a line. So an unescaped string does not produce a broken layout, it produces +**a blank screen and not one error anybody will see**. + +What comes from outside is: everything from the Petersburg diary (subject, room, teacher, +topic, homework), everything typed into the bot and pasted into the paste grammar (a subject +really can be called «Алгебра <7>»), and everything from the schools registry. `render.py` +always did this; `diary_render.py` and `editor_render.py` never did, and both shipped that +way. + +Two traps of the same kind next door. `plural(n, …)` **already contains the number**, so +`f"{n} {plural(n, …)}"` prints «10 10 минут» — it was in three places, and one had a test +that passed because «10 минут» is a substring. And `answerCallbackQuery` has **no parse +mode**: a card assembled for a message shows its own tags in an alert, which is what +`editor_render.as_alert` is for — it also cuts at 200 characters, because past that Telegram +answers 400 and the press answers with nothing at all. + +### Callback data is whatever the client sent, and this is not caution for its own sake + +A client is free to send any string as callback data. The difference between `int(x)` and +"check and refuse" is not tidiness: a bare `int()` **escapes the handler**, which means +`callback.answer()` is never called and the button spins until Telegram gives up. `manage.py` +and `tasks.py` have `_int_or_none` for this, `calendar.py` and `content.py` have +`_date_or_none`, `access.py` now has `_int_or_none` and `_role_or_none`, and `content.py` also +has `_kind_or_none` and `_index_or_none`. The rule is one: **check where the value is +picked**, not where it is finally read — otherwise it travels through three questions and +fails in front of somebody who has already typed a time and a title. + +The same goes for arithmetic: `shift_days` / `shift_weeks` in `keyboards.py` build the date +and let `date` say whether it is one. `timedelta(days=999999999)` is an `OverflowError`, not +a far-away day. + +### Two screens can catch one press + +Both flows send a `RolePick` — inviting by number and changing a member's role — and the only +thing that tells them apart is that the first leaves `target` empty. While the invite's +filter was simply `RolePick.filter()`, it took both, because it stood higher in the file. If +you add a second screen on an existing payload, **separate the filters by a field** rather +than by registration order; `test_the_two_role_pickers_never_match_the_same_press` holds +this. + +### The translation is guarded in every module that ships strings + +`ResourceTranslationTest` used to read `:app` and nothing else, while there are strings in +`:core:data`, `:core:designsystem` and `:widget` too — including the countdown on the home +screen. It now finds every module with a `values/strings.xml` by itself, names the module in +every error, and a separate test holds the list itself, so that the walk cannot narrow +silently. A `<plurals>`' arguments are counted **per form**: Russian has four and English +two, and over the concatenation they can never agree (it never showed in `:app`, because +everything there is `%1$d` rather than `%d`). + +Russian text hard-coded into Kotlin is not caught by this at all — those words are in neither +folder. Check it this way: `grep -rnP '"[^"]*[\x{0400}-\x{04FF}]'` over `src/main`. Today +what is left is only `@Preview`, the maintainer-facing report bodies, and the timezone list, +where that decision is recorded in the file itself. + +### A constraint migrates in the opposite direction from a column + +The rule "migration before the merge" is about code that knows a column the database does +not. For this chain it is right everywhere but one case: **a `UNIQUE` and a `NOT NULL` break +the old code, not the new.** Before `services/homework.py` reaches `main`, the losing side of +a race does an ordinary INSERT and gets an `IntegrityError` nobody catches — that is, a 500 +where today there is a duplicate. So `0013` is applied **after** the merge, and that is +written in the revision itself; `services/homework.py` is deliberately correct without the +constraint too, so that the window between the merge and the application behaves as things do +today. + +`0012` is the safe shape (eight timestamps that already hold no NULLs) and was applied the +usual way, before the merge. **The database was read before both**, and that paid off: unlike +`0011`, `0012` turned out not to be a no-op — all eight columns in production really were +nullable. + +**The database's state right now:** Neon's head is `0013`, and it agrees with +`EXPECTED_REVISION`. The revision was applied as one transaction through the connector right +after PR #45 was merged, with the stamp last inside it; `homework` was empty, so its +deduplication deleted no rows, and `uq_homework_per_subject_per_day` now stands as exactly +what the model builds. + +### The school year ends, and the template with it + +`SCHOOL_YEAR_END_MONTH` is 5, and the comment beside it explains why the template must not +repeat from June: it "would show lessons nobody is going to". Only `school_year_bounds` read +that constant. `_resolve_day` now asks it too. A day marked by hand keeps its kind and its +note; events and homework are kept either way — it is the lessons that are out of season, not +the day. + +The rule is about a **date** rather than about the quarters. A school that really does teach +in June enters those days as events. + +### A lesson's ceiling is a set of numbers, not a count of them + +The resolver takes a lesson's time from the bell row **with the same number** (`schedule.py`, +`period = bells.get(entry.index)`). So the question "may lesson 4 be written" is "is there a +bell 4", not "how many bells are there in total". The paste grammar allows a gap +(`parse_bells_block` refuses only on `index < 1` and on duplicates), so for a class with bells +at 1, 2, 4 a count is wrong in both directions at once. `timetable_edit.rung_indexes` answers +the right question, `can_ring` asks it, and `rings` stayed a counter because it is printed as +"there are N lessons in the bell schedule". + +Every entrance is closed: a substitution (`api/edit.py`, `bot/handlers/content.py`) and the +single-day paste check the bell, the day paste goes through `apply_timetable`, deleting a +lesson closes the gap in the numbering **only** if every lesson it moves lands on a number +that rings (otherwise a class with bells at 1, 2, 4 lost its fourth lesson by shifting it +onto the third), and a «⏱ Сокращённый день» cannot be hung on a bell schedule with no rows — +neither from the API nor from the bot: such a day draws nothing at all. + +**And count rows, not numbers.** `apply_timetable` returns a `TimetableImport` with (day, +number) pairs: «⚠️ Не добавлены уроки № …» names a number once — that is one thing to fix — +while "N skipped, no bell" and `rejected` in the API count the rows that were dropped, +because one number under two days (or under «чёт»/«нечёт» in one day) is two lessons. + +### A list's length and its keyboard's length are one number, not two + +`manage_render` declares `SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX` and `LIST_MAX` (special +days), and `manage_keyboards` builds its rows **from those same ones**. While there were two +numbers, three pages of four drew rows nothing could reach, and «… и ещё N» said nothing about +them, because it counted from its own number. Do not "bring them to one value for tidiness": +the numbers differ on purpose — a bell schedule's row carries three buttons and twelve lines +of times, a subject's one of each. The rule is one: what is drawn is what can be pressed, and +`test_no_list_page_draws_a_row_the_keyboard_cannot_reach` holds it. + +The pages **do not paginate** — none of them. Past the cap a row is only a number in +«… и ещё N»; for a class with forty subjects the last ten are unreachable from the bot +entirely. Raising the caps is a wall of buttons; the real fix is pagination, and nobody has +written it. + +### `python -m mypy` answers one question, and that is enough + +Not "type everything" but "does the code reach for an attribute the type does not have". That +is exactly what crashed «🗓 Четверти», and the check reproduces it word for word if the +property is put back. It is configured in `pyproject.toml`, where **every other code is +switched off by name, with a count and a reason** — a check whose output cannot be read is a +check nobody runs. + +It is currently clean across all 78 modules. The one thing that stood between the project and +cleanliness was `Result.rowcount`: `AsyncSession.execute` is typed as returning a +`Result[Any]`, which has no such field, while DML returns a `CursorResult`, which does. +Eleven places wrote `result.rowcount or 0` and meant one thing; that is now +`db.rows_affected`, and the cast lives in one place. + +**It is not in CI.** `CLAUDE.md` asks that the workflows not be edited casually, and adding a +job is the owner's decision, which nobody asked for. Run it by hand before pushing server +code. + +### A renderer is written against the type it will be handed + +«🗓 Четверти» crashed in production on every press, because the card read `term.days`, while +`days` belonged to `TermView` — a dataclass nobody ever constructed. Two types for one entity +is a way to write a renderer against the one that never reaches it; there is no compiler +here, and an `AttributeError` is visible only from the button. + +The moral is not "add type hints" but something more specific: **if a model's "flattened copy +for the renderer" sits beside it, check that somebody creates it.** And remember where the +tests' boundary runs: `tests/test_terms.py` opens with the words "the rules, not the +rendering", and that is an honest split right up to the day nobody checks the rendering. +The terms card is now drawn by a test (`test_the_terms_card_draws`), and it asserts the +numbers rather than only that the call returned: a card with «0 дн.» is as wrong as one that +crashed. + +### The ceiling on lessons in a day + +Not `MAX_INDEX` but the class's bell count. A lesson with a number that has no row in the +bell schedule cannot be placed by the resolver and used to be dropped silently. On import the +ceiling is computed from what the class will ring **after** the import — a paste with its own +`== Звонки ==` block legitimately brings a ninth bell and a ninth lesson in one message. + +--- + +### The agent configuration lives in `.claude/` + +There was none at all — no settings, no agents, no skills. There is now, and it is arranged +so as not to retell `CLAUDE.md` but to describe the shape: who owns what, which checks are +real, and which commands are never run from a session. + +``` +.claude/settings.json permissions, two hooks, the marketplace this project knows about +.claude/agents/ eighteen agents by area +.claude/skills/ nine procedures +.claude/commands/ /where-are-we and /pre-push +.claude/hooks/ the one hook too long to live inline +.claude/README.md what is here and what is deliberately absent +AGENTS.md a pointer for agents that read something other than `CLAUDE.md` +.github/copilot-instructions.md a short file: it is read on every request +``` + +Eighteen agents rather than a hundred, because each file exists for a trap that has already +sprung in that area, and carries the fact that would have prevented it. An agent that retells +`CLAUDE.md` would not survive the same review that lets no comment through that retells the +line below it, and a stub agent is worse than no agent: it answers confidently from nothing. +The nine-way split in `skills/audit/SKILL.md` is the one that found thirty-one findings in a +pass; the other nine are areas that have since grown traps of their own. + +Three things in `settings.json` worth knowing: + +* **`deny` compares the start of the command string.** `DATABASE_URL=… .venv/bin/alembic + upgrade head` walks past the `alembic upgrade *` rule. Those are guard rails, not a fence; + the reason not to run it by hand is in `skills/migration/SKILL.md`. +* **There are two hooks and both only print.** On a write to any module's + `values/strings*.xml`, the first mentions the twin in `values-en/`. The second, + `hooks/handover-behind.sh`, runs on `Stop` and speaks only when a merge commit on `HEAD` + **neither carried the close-out nor predates it** — a state that exists only after a pull + request has merged and `dev` has been fast-forwarded onto it, which is exactly when the + close-out is the work that is left. The first half of that condition is the correction: + a close-out written inside its own pull request, which is what the rule asks for while + that pull request is open, is landed *by* the merge and is therefore always older than + it. Comparing timestamps alone called that missing, and did so the first time the rule + was followed properly — on #67. A committed hook runs on the machine of everybody + who cloned the repository, which is why both are this small and why neither can fail: + each exits quietly on anything unexpected. +* **`extraKnownMarketplaces` registers `anthropics/skills`**, but no plugin is enabled: + enabling one is a decision for everybody who clones the repository, not for the session + that added the file. + +**There is deliberately no `.mcp.json`.** The Neon and Vercel connections need credentials, +and secrets do not enter this repository. The Neon project is the one **named `lessons`** +(the account has two), and that is all that can safely be written down. + +### Everything written about the project is English + +The product speaks Russian; everything written *about* the project is English. User-facing +strings stay where they were — `values/` is Russian and is the source, `values-en/` is the +translation, and the reader picks the language in the app — and every string the bot sends is +untouched. What moved: `README.md`, all of `docs/`, this file, the community documents, the +issue and pull request templates, and every comment and docstring under `server/` and +`android/`. + +Where any of those quotes a button, a menu path or an error the reader will see, it quotes it +in Russian, in guillemets, because that is what is on the screen. «🔔 Звонки» is a quotation, +not prose. + +Two things about the edges of that rule: + +* **The pull requests were rewritten on GitHub**, titles, descriptions and the eight + Russian comments under #16, #22, #34, #35 and #47. Those are GitHub objects, not repository + content: nothing in git moved, and no hash changed. The bots' comments are not ours and were + left alone. +*The bullet that followed, about the commit history, stayed in `HANDOVER.md`'s section 6, +«Two things left in Russian on purpose».* + + +The rule itself is written into `CLAUDE.md`, `AGENTS.md`, `.github/copilot-instructions.md` +and the `.claude/` agents and skills that touch strings or releases. Two of them had been +missed and told the next session to write **this file** in Russian — the `handover` skill +and the `handover-keeper` agent. Both now say English, and quote the README's "Written, +never run" instead of its Russian ancestor. + +### What the documents claimed, and what was actually true + +A number is the part of a document that rots first, so every one of them was re-measured on +19 September 2026 rather than copied forward: + +| Measured | Now | +| --- | --- | +| server tests | 1391, over 38 files | +| Android tests | 605, over 73 classes — `:core:model` 89, `:core:data` 186, `:core:designsystem` 45, `:widget` 45, `:app` 240 | +| modules under `mypy` | 79 | +| commits | 258 | +| schema head | `0013` | + +What was wrong and is now right: + +* `CLAUDE.md` said 1362 tests and 178 commits. +* `docs/architecture.md` gave `schedule.py` fifteen tests (it has twenty-two) and + `:core:model` fourteen (it has eighty-nine), listed eleven of the thirty-eight server + suites as though that were all of them, and ended with "the Android UI and the Glance + widget have no automated coverage yet" — which stopped being true when three screens went + under Robolectric and the size ladder got a test that walks real sizes. +* `CONTRIBUTING.md` said the same thing about screens and the widget. +* `docs/build.md` quoted 1340 tests without saying that was the count at the time of that + measurement, so it read as the current one. + +Everything else was checked and left alone: `README.md`'s "Honest status", `docs/README.md`, +the `0013` head wherever it is named, the twelve rungs, and the eight documents plus an +index. The sweep changed no code and ran no gate — there was nothing to run. + +*The paragraph that followed, about five test names, stayed in `HANDOVER.md`'s section 6, +«Two things left in Russian on purpose».* + + +## Moved out of section 7 on 27 September 2026 + +What `HANDOVER.md`'s «Left to the owner» asked for and got, or recorded as already decided: +the warmup request, answered on 26 September 2026 together with the bot's `/start`, which +closed #119; the report from #79; the calendar's year scroll, decided and built in #78; the +milestones' tidy-up; items 1, 1a and 1b of its numbered list; and item 5, the correction +mode's walk, which #186 made on an emulator and which closed #115. + +**Open `/api/v1/warmup` in a browser — it is the one thing that settles whether the schema +and the code that needs it actually met**, and it is outstanding since #61. It cannot be +closed from a session here at any effort: the deployments are behind Vercel's Deployment +Protection and answer a redirect to a login page, so this needs the owner's own browser or a +bypass token. The answer wanted once #140 has merged and deployed is +`{"status":"ok","api_version":1,"schema":"0017"}`; a +`"degraded"` naming two revisions is the honest report of a migration and a deploy that have +not met, and which way round it is, is in the `detail`. + +**One of these stopped being theoretical in #79, and it is the most useful thing that has +happened to this project.** The owner installed an APK, used it, and sent back both the +symptom and the full Android bugreport. That found three defects in a screen with three +passing test suites over it, and settled in one line a question the branch could only +speculate about — whether the crash on rotation was a fourth defect. It was not. +**Every batch that changes a screen is worth an APK and five minutes of the owner's +thumb**, and the bugreport is worth more than the description, because the description +cannot contain `not-handles={}`. + +**The calendar year-scroll was a decision and it has been made.** The owner chose (b), the +windowed sync, on 21 September 2026, over (a), a picker bound to the year already synced — +which would have scrolled to a year with no days in it. It is done, in #78. What is left of +it for the owner is one number: the cache keeps three school years per class, which is a +guess rather than a measurement, and nobody has watched what four costs on a real phone. + +**The milestones were the newest of these, and that one is done.** Milestones 1 to 6 and 8 +cover versions that are finished, and the owner has closed all seven. Three stay open on +purpose: number 9, `v0.8.0 — On-device checks, 89-region e-diary survey`, whose device work +is still to do; number 10, `v0.9.0 — NetSchool e-diary, onboarding via the school's +diary`, which #140 is on; and number 7, `Dependencies — dependabot bumps`, which takes every +future bump. The ten titles, and what each was called before the owner renamed them on +25 September, are in the table under «And before that: nothing on a screen is cut off». The +reason a new one has to be asked for stands for next time: no tool in a session here changes +a milestone's state or creates one — `issue_write` only assigns an existing one by number — +and there is no `gh` CLI. + +~~1. **Decide the fate of PR #43.**~~ Merged. The order was kept: `0010` (the join mode and + the personal-codes table) and `0011` (two timestamps in `diary_overrides` brought to `NOT + NULL`) were applied through the Neon connector **before** the merge. Neither destroyed + anything: `0010` added a column with a default preserving the current behaviour, plus an + empty table; `0011` changed nothing at all on this database — the columns were already + `NOT NULL`, because the DDL for `0009` came from the model rather than from the revision's + text. Verified afterwards: head `0011`, the single class reads `OPEN`, `device_invites` + matches the model column for column, three indexes. +~~1a. **Apply `0013` after PR #45 is merged.**~~ Applied: head `0013`, the constraint in + place, zero rows deleted (`homework` had none). +1b. **Open `/api/v1/warmup` and make sure the deploy arrived** — once #140 has merged and + deployed that is `{"status":"ok","schema":"0017"}` — and then send the bot `/start`: the + very first message goes through the middleware that reads a class, and that is the fastest + check that the schema and the code agree. That is all that is left of item 1; it needs a + live service, and since the deployments sit behind Deployment Protection it needs a browser + or a bypass token rather than a `curl` from a session. +5. **Switch on «Настройки → Перевод → Режим исправления» and walk the screens.** What is + being checked is what a JVM test cannot see: that the outline appears around labels rather + than around subject names; that a long press on a settings row opens the editor rather + than toggling the row (the gesture is read on `PointerEventPass.Initial` precisely for + this); that pressing a sentence with a number in it — «12,4 МБ» under updates — shows the + pattern `%1$s МБ` in the editor rather than the sum; and that inside the editor itself a + long press does nothing. diff --git a/server/tests/test_schema_version.py b/server/tests/test_schema_version.py index 2a4cd7a7..5a9cebab 100644 --- a/server/tests/test_schema_version.py +++ b/server/tests/test_schema_version.py @@ -92,14 +92,21 @@ def test_the_constant_the_app_ships_is_the_real_migration_head(): _WARMUP_OK = re.compile(r'"status": ?"ok"[^}\n]*"schema": ?"(\d{4})"') +#: The record of past batches, moved verbatim out of HANDOVER.md: it quotes the +#: head of every commit it describes, true of that commit, and is never +#: brought up to date. +_HISTORY = REPOSITORY / "docs" / "history.md" + + def _documents() -> list[Path]: """Everything a person or an agent reads to learn the head — not - HANDOVER.md, which is a history and holds every head there has been.""" + HANDOVER.md or docs/history.md, which between them hold every head + there has been.""" found = [REPOSITORY / name for name in ("README.md", "CLAUDE.md", "AGENTS.md")] found.append(REPOSITORY / ".github" / "copilot-instructions.md") found += sorted((REPOSITORY / "docs").rglob("*.md")) found += sorted((REPOSITORY / ".claude").rglob("*.md")) - return [document for document in found if document.is_file()] + return [document for document in found if document.is_file() and document != _HISTORY] def test_every_document_that_names_the_head_names_this_one(): From 15363d2e11d5ebf8cecb1478f30697716c455a82 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 13:23:20 +0300 Subject: [PATCH 06/43] Hand the compose server every setting it reads, so the diary, the tick and the links work there MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A container sees only what docker-compose.yml lists, whatever `.env` holds, and the server's list stopped at TIMEZONE. DIARY_SECRET, WEBHOOK_SECRET, CRON_SECRET, PUBLIC_BASE_URL, BOT_USERNAME and DADATA_TOKEN never reached it, so a compose deployment had no diary, no digests and no calendar link however it was configured — and the startup log said each was off without a hint why. The list is taken from `Settings` rather than from the issue: the six strings above are forwarded as `${NAME:-}`, which for a string whose default is empty is the same as unset, and RUN_BOT and TRUSTED_PROXY_HOPS are forwarded with their own defaults written in, because an empty string is neither a boolean nor a number to pydantic and the server would refuse to start over a variable nobody set. Four are left out on purpose and the file says why: VERCEL (the platform's own, and it switches on Vercel's refusal to start), HOST and PORT (read only by `python -m app.main`; the image's command binds 0.0.0.0:8000 itself) and WEBHOOK_PATH (read by nothing). tests/test_compose.py now checks the server's environment against `Settings.model_fields` in both directions, and checks that every fallback written in the file parses to the setting's own default. The first failed on the old file, naming the missing six plus the two non-strings. docs/deploy.md, «Option 2», lists what is forwarded and which of them a compose deployment needs for what. Not covered: written, never run under Docker. Closes #191 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docker-compose.yml | 21 +++++++++++++ docs/deploy.md | 11 +++++++ server/tests/test_compose.py | 59 ++++++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 1edbaaf0..95c4b954 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -60,6 +60,27 @@ services: BOT_TOKEN: ${BOT_TOKEN:?set BOT_TOKEN in .env} OWNER_IDS: ${OWNER_IDS:?set OWNER_IDS in .env} TIMEZONE: ${TIMEZONE:-Europe/Moscow} + # Every optional setting app/config.py reads. A container sees only what + # is listed here, whatever `.env` holds, and none of these was listed: a + # compose deployment had no diary, no tick and no calendar link however it + # was configured (#191). Unset, each arrives empty, which for every one + # of these strings is exactly its default — tests/test_compose.py checks + # that, and checks this list against `Settings`. + WEBHOOK_SECRET: ${WEBHOOK_SECRET:-} + CRON_SECRET: ${CRON_SECRET:-} + BOT_USERNAME: ${BOT_USERNAME:-} + DIARY_SECRET: ${DIARY_SECRET:-} + DADATA_TOKEN: ${DADATA_TOKEN:-} + PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-} + # Not strings, so not empty when unset: "" is neither a boolean nor a + # number to pydantic, and the server would refuse to start over a + # variable nobody set. The defaults written here are the settings' own. + RUN_BOT: ${RUN_BOT:-true} + TRUSTED_PROXY_HOPS: ${TRUSTED_PROXY_HOPS:-0} + # Deliberately absent: VERCEL is the platform's own, and set here it would + # switch on Vercel's refusal to start; HOST and PORT are read only by + # `python -m app.main`, while the image's command binds 0.0.0.0:8000 + # itself; WEBHOOK_PATH is read by nothing. depends_on: db: condition: service_healthy diff --git a/docs/deploy.md b/docs/deploy.md index 615d62be..893a57a9 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -560,6 +560,17 @@ the container exactly what the file lists; the image copies no `.env` of its own used to say `server/.env`, which compose never reads, so `up` stopped at «set BOT_TOKEN in .env» however carefully that file had been filled in. +**Every setting the server reads reaches the container.** Besides `BOT_TOKEN`, `OWNER_IDS` +and `TIMEZONE`, the file hands it `WEBHOOK_SECRET`, `CRON_SECRET`, `BOT_USERNAME`, +`DIARY_SECRET`, `DADATA_TOKEN`, `PUBLIC_BASE_URL`, `RUN_BOT` and `TRUSTED_PROXY_HOPS` from the +same `.env`, each arriving as its own default when unset. Until #191 none of those was +passed, and a container sees only what the file lists: a compose deployment had no diary, +no digests and no calendar link whatever `.env` said. What they are for is the table under +Option 1; here, the digests need `CRON_SECRET` and an external cron exactly as on Vercel +(«The clock» below), the diary needs `DIARY_SECRET` and, for its sign-in page, +`PUBLIC_BASE_URL`, and behind a reverse proxy that terminates HTTPS, `TRUSTED_PROXY_HOPS=1` +is what lets the throttles see the caller rather than the proxy. + **The database password is yours, and letters and digits only.** `POSTGRES_PASSWORD` is required — `docker compose up` refuses to start without it. The file used to carry `lessons` in plain text, which in a public repository is the password of every deployment that ran it diff --git a/server/tests/test_compose.py b/server/tests/test_compose.py index dc3951ce..f97c04d2 100644 --- a/server/tests/test_compose.py +++ b/server/tests/test_compose.py @@ -13,9 +13,30 @@ import yaml +from app.config import Settings + ROOT = Path(__file__).resolve().parents[2] COMPOSE = ROOT / "docker-compose.yml" +#: Settings the server container is deliberately not handed, and why. Each is +#: said in the compose file too; this is the list the test believes. +NOT_FORWARDED = { + "VERCEL": "the platform's own; set here it would switch on Vercel's refusal to start", + "HOST": "read only by `python -m app.main`; the image's command binds 0.0.0.0 itself", + "PORT": "the same, and the published port is 8000 either way", + "WEBHOOK_PATH": "read by nothing: the webhook's route is fixed in app/api/telegram.py", +} + +#: ``${NAME:-default}`` — forwarded, with what an unset variable becomes. +_FORWARDED = re.compile(r"^\$\{(?P<name>[A-Z][A-Z0-9_]*):-(?P<default>[^}]*)\}$") + + +def _field_names() -> dict[str, str]: + """Environment name → field name, for every setting `Settings` reads.""" + return { + (field.alias or name).upper(): name for name, field in Settings.model_fields.items() + } + #: The one way the database password may appear: interpolated from the #: environment, refusing to start without it. _PASSWORD = re.compile(r"^\$\{POSTGRES_PASSWORD:\?[^}]*\}$") @@ -47,3 +68,41 @@ def test_the_database_password_comes_from_the_environment_and_nowhere_else(): assert user == services["db"]["environment"]["POSTGRES_USER"], name assert _PASSWORD.match(password), f"{name} carries a literal database password" assert host == "db:5432/lessons", name + + +def test_the_server_is_handed_every_setting_the_code_reads(): + """#191. A container sees only what the file lists, whatever `.env` holds, + and the list stopped at `TIMEZONE`: a compose deployment had no diary, no + tick and no calendar link however carefully it was configured, and the + startup log said each was off without saying why.""" + handed = set(_services()["server"]["environment"]) + names = set(_field_names()) + + missing = names - handed - set(NOT_FORWARDED) + assert not missing, f"docker-compose.yml does not hand the server: {sorted(missing)}" + # And the exceptions are real settings, not a list that outlived them. + assert set(NOT_FORWARDED) <= names, sorted(set(NOT_FORWARDED) - names) + assert not set(NOT_FORWARDED) & handed, sorted(set(NOT_FORWARDED) & handed) + + +def test_a_setting_nobody_set_reaches_the_server_as_its_own_default(): + """`${NAME:-}` does not leave a variable unset — it hands the container an + empty string. For a string whose default is empty that is the same thing; + for `RUN_BOT` it would be a value pydantic refuses, and the server would + not start over a line nobody wrote. So every fallback written in the file + has to parse to the default the setting already has.""" + fields = _field_names() + forwarded = 0 + for name, value in _services()["server"]["environment"].items(): + match = _FORWARDED.match(str(value)) + if match is None: + continue + forwarded += 1 + assert match["name"] == name, f"{name} is filled from ${{{match['name']}}}" + field = fields[name] + parsed = getattr(Settings(**{field: match["default"]}), field) + assert parsed == Settings.model_fields[field].default, ( + f"{name} unset becomes {match['default']!r}, which is {parsed!r}, " + f"not the setting's own default {Settings.model_fields[field].default!r}" + ) + assert forwarded, "no optional setting is forwarded at all" From eb1015c0055fe4a8ab4d86b7d39de2e63c38c6ef Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 13:23:29 +0300 Subject: [PATCH 07/43] Give the diary's state and its empty cache files of their own DiaryViewModel.kt was 949 lines, and the first 160 were not the view model: they were the state it publishes, the outcome of a sign-in it reports, and the zone the diary defaults to. The last twenty were a cache that holds nothing, for view models built without one. DiaryUiState.kt now holds the state and the sign-in outcome, and NoDiaryCache.kt the empty cache, so DiaryViewModel.kt is the class and the few rules only it applies. Moved verbatim, comments included; DefaultDiaryZone and NoStudents go from private to internal because the view model reads both and is now in another file. Refs #209 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../lessons/ui/diary/DiaryUiState.kt | 130 ++++++++++++++++ .../lessons/ui/diary/DiaryViewModel.kt | 143 ------------------ .../lessons/ui/diary/NoDiaryCache.kt | 29 ++++ 3 files changed, 159 insertions(+), 143 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/NoDiaryCache.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt new file mode 100644 index 00000000..23a2e99b --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt @@ -0,0 +1,130 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId + +/** + * Everything the diary section is, as one state object. + * + * @property ready false only until the stored session has been read once. The + * screen shows placeholders rather than the sign-in form in that moment: a + * login page that flashes up for somebody who is already signed in is the + * worst frame this section can draw. + * @property reauth the upstream session died. The login is still known, so the + * screen asks for the password alone — the case the server sends + * `X-Diary-Reauth: required` for, and the whole reason it is a header rather + * than one 401 for both meanings. + * @property student the pupil everything below is about; `null` only while the + * list is still loading or empty. + * @property zone the zone the diary cuts its days at — the session's, which the + * server named at registration. Moscow until a session says otherwise, which + * is what every session before the second diary was. + * @property signInTarget which diary the form would sign in to: one picked on + * this screen, else the live session's, else the one a bare `401` left, else + * the class's binding, else Petersburg — the one diary this form ever offered + * before it could be asked for another. Its login is a placeholder; the typed + * one replaces it on submit. + * @property place what the catalog says about [signInTarget] — its names and + * the host the password goes to — or `null` until the catalog has been read. + * @property picking the diary picker is open in place of the form. + * @property savedAt the rows on screen are what was saved at this moment, + * shown because the diary could not be reached just now; `null` when they + * are the diary's answer of this visit. + */ +data class DiaryUiState( + val ready: Boolean = false, + val session: DiarySession? = null, + val reauth: Boolean = false, + val signingIn: Boolean = false, + /** + * Why the last sign-in failed, for the form to paint itself by — cleared by + * the next keystroke. The sentence is [signInOutcome]'s to say. + */ + val signInError: DiarySignInProblem? = null, + /** + * What the last sign-in attempt came to, waiting to be shown once. + * + * Separate from [signInError] because the two answer different questions + * and live for different lengths of time. [signInError] is the state of the + * form — it paints the fields red and is cleared by the next keystroke. + * This is an event: it is shown in a pop-up, acknowledged, and gone, and it + * carries the success case too, which the form has nothing to say about + * because the form is no longer on screen by then. + */ + val signInOutcome: DiarySignInOutcome? = null, + val signInTarget: DiaryTarget = DiaryTarget.petersburg(""), + val place: DiaryPlace? = null, + val picking: Boolean = false, + val signingOut: Boolean = false, + val students: List<DiaryStudent> = emptyList(), + val studentsLoading: Boolean = false, + val studentsError: DiaryFailure? = null, + val selectedStudentId: Long? = null, + val tab: DiaryTab = DiaryTab.SCHEDULE, + val zone: ZoneId = DefaultDiaryZone, + val weekStart: LocalDate = diaryWeekStart(diaryToday(DefaultDiaryZone)), + val scheduleLoading: Boolean = false, + val scheduleError: DiaryFailure? = null, + val days: List<DiaryDayUi> = emptyList(), + val gradesLoading: Boolean = false, + val gradesError: DiaryFailure? = null, + val subjects: List<DiarySubjectMarks> = emptyList(), + val gradeRange: DiaryRange? = null, + val savedAt: Instant? = null, + /** The row whose corrections are open in a sheet, or `null` for none. */ + val editing: DiaryCorrections? = null, + val savingEdit: Boolean = false, + val editError: DiaryFailure? = null, +) { + /** + * The date it is where the diary is. + * + * Read on every access rather than frozen into the state, because the + * state object is built once when the screen opens and carried forward by + * `copy` from then on: a value stored here was whatever the date was when + * the pupil first opened the diary, and a phone left on the screen + * overnight kept offering «на этой неделе» for the week that had ended. + */ + val today: LocalDate get() = diaryToday(zone) + + val student: DiaryStudent? get() = students.firstOrNull { it.id == selectedStudentId } + + /** Signed in and not being asked for the password again. */ + val signedIn: Boolean get() = session != null && !reauth + + /** A picker is only worth its row when there is something to pick. */ + val showStudentPicker: Boolean get() = students.size > 1 + + /** Whether stepping back to this week would move anything. */ + val canReturnToThisWeek: Boolean get() = weekStart != diaryWeekStart(today) + + /** The login the form starts with: the account's, when one is known. */ + val knownLogin: String get() = session?.login ?: signInTarget.login +} + +/** Petersburg's zone, which every diary session had before the second diary. */ +internal val DefaultDiaryZone: ZoneId = ZoneId.of(DiaryTarget.PETERSBURG_ZONE) + +/** + * The result of one sign-in attempt, for the pop-up that reports it. + * + * Both cases are worth saying out loud. «Не удалось войти» because the reason + * matters — a wrong password and a diary that is down need different things + * from the person reading; «Вход выполнен» because a form that answers a + * correct password with silence is a form you cannot tell you have finished + * with. + */ +sealed interface DiarySignInOutcome { + + /** @param login the account, echoed back so it can be checked for typos. */ + data class Succeeded(val login: String) : DiarySignInOutcome + + /** @param problem said by `DiaryProblemText`, the one mapping there is. */ + data class Failed(val problem: DiarySignInProblem) : DiarySignInOutcome +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index f0dd9c1e..57cef171 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -7,9 +7,6 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.diary.DiaryCache -import com.lumenpearson.lessons.core.data.diary.DiaryCachedMarks -import com.lumenpearson.lessons.core.data.diary.DiaryCachedPeriods -import com.lumenpearson.lessons.core.data.diary.DiaryCachedStudents import com.lumenpearson.lessons.core.data.diary.DiaryCachedWeek import com.lumenpearson.lessons.core.data.diary.diaryIsFresh import com.lumenpearson.lessons.core.data.repository.DiaryBinding @@ -24,7 +21,6 @@ import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.Clock import java.time.Instant import java.time.LocalDate -import java.time.ZoneId import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope @@ -39,126 +35,6 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -/** - * Everything the diary section is, as one state object. - * - * @property ready false only until the stored session has been read once. The - * screen shows placeholders rather than the sign-in form in that moment: a - * login page that flashes up for somebody who is already signed in is the - * worst frame this section can draw. - * @property reauth the upstream session died. The login is still known, so the - * screen asks for the password alone — the case the server sends - * `X-Diary-Reauth: required` for, and the whole reason it is a header rather - * than one 401 for both meanings. - * @property student the pupil everything below is about; `null` only while the - * list is still loading or empty. - * @property zone the zone the diary cuts its days at — the session's, which the - * server named at registration. Moscow until a session says otherwise, which - * is what every session before the second diary was. - * @property signInTarget which diary the form would sign in to: one picked on - * this screen, else the live session's, else the one a bare `401` left, else - * the class's binding, else Petersburg — the one diary this form ever offered - * before it could be asked for another. Its login is a placeholder; the typed - * one replaces it on submit. - * @property place what the catalog says about [signInTarget] — its names and - * the host the password goes to — or `null` until the catalog has been read. - * @property picking the diary picker is open in place of the form. - * @property savedAt the rows on screen are what was saved at this moment, - * shown because the diary could not be reached just now; `null` when they - * are the diary's answer of this visit. - */ -data class DiaryUiState( - val ready: Boolean = false, - val session: DiarySession? = null, - val reauth: Boolean = false, - val signingIn: Boolean = false, - /** - * Why the last sign-in failed, for the form to paint itself by — cleared by - * the next keystroke. The sentence is [signInOutcome]'s to say. - */ - val signInError: DiarySignInProblem? = null, - /** - * What the last sign-in attempt came to, waiting to be shown once. - * - * Separate from [signInError] because the two answer different questions - * and live for different lengths of time. [signInError] is the state of the - * form — it paints the fields red and is cleared by the next keystroke. - * This is an event: it is shown in a pop-up, acknowledged, and gone, and it - * carries the success case too, which the form has nothing to say about - * because the form is no longer on screen by then. - */ - val signInOutcome: DiarySignInOutcome? = null, - val signInTarget: DiaryTarget = DiaryTarget.petersburg(""), - val place: DiaryPlace? = null, - val picking: Boolean = false, - val signingOut: Boolean = false, - val students: List<DiaryStudent> = emptyList(), - val studentsLoading: Boolean = false, - val studentsError: DiaryFailure? = null, - val selectedStudentId: Long? = null, - val tab: DiaryTab = DiaryTab.SCHEDULE, - val zone: ZoneId = DefaultDiaryZone, - val weekStart: LocalDate = diaryWeekStart(diaryToday(DefaultDiaryZone)), - val scheduleLoading: Boolean = false, - val scheduleError: DiaryFailure? = null, - val days: List<DiaryDayUi> = emptyList(), - val gradesLoading: Boolean = false, - val gradesError: DiaryFailure? = null, - val subjects: List<DiarySubjectMarks> = emptyList(), - val gradeRange: DiaryRange? = null, - val savedAt: Instant? = null, - /** The row whose corrections are open in a sheet, or `null` for none. */ - val editing: DiaryCorrections? = null, - val savingEdit: Boolean = false, - val editError: DiaryFailure? = null, -) { - /** - * The date it is where the diary is. - * - * Read on every access rather than frozen into the state, because the - * state object is built once when the screen opens and carried forward by - * `copy` from then on: a value stored here was whatever the date was when - * the pupil first opened the diary, and a phone left on the screen - * overnight kept offering «на этой неделе» for the week that had ended. - */ - val today: LocalDate get() = diaryToday(zone) - - val student: DiaryStudent? get() = students.firstOrNull { it.id == selectedStudentId } - - /** Signed in and not being asked for the password again. */ - val signedIn: Boolean get() = session != null && !reauth - - /** A picker is only worth its row when there is something to pick. */ - val showStudentPicker: Boolean get() = students.size > 1 - - /** Whether stepping back to this week would move anything. */ - val canReturnToThisWeek: Boolean get() = weekStart != diaryWeekStart(today) - - /** The login the form starts with: the account's, when one is known. */ - val knownLogin: String get() = session?.login ?: signInTarget.login -} - -/** Petersburg's zone, which every diary session had before the second diary. */ -private val DefaultDiaryZone: ZoneId = ZoneId.of(DiaryTarget.PETERSBURG_ZONE) - -/** - * The result of one sign-in attempt, for the pop-up that reports it. - * - * Both cases are worth saying out loud. «Не удалось войти» because the reason - * matters — a wrong password and a diary that is down need different things - * from the person reading; «Вход выполнен» because a form that answers a - * correct password with silence is a form you cannot tell you have finished - * with. - */ -sealed interface DiarySignInOutcome { - - /** @param login the account, echoed back so it can be checked for typos. */ - data class Succeeded(val login: String) : DiarySignInOutcome - - /** @param problem said by `DiaryProblemText`, the one mapping there is. */ - data class Failed(val problem: DiarySignInProblem) : DiarySignInOutcome -} - /** * The diary section's state holder — and, on a phone in no class, the diary * home's. @@ -928,22 +804,3 @@ private val DiaryCachedWeek.savedAt: Instant? val homework = homeworkLoadedAt ?: return null return minOf(lessons, homework) } - -private val NoStudents = DiaryCachedStudents(emptyList(), loadedAt = null) - -/** - * A cache that holds nothing, for a view model built without one — the tests - * that are about the network and nothing in front of it. - */ -internal object NoDiaryCache : DiaryCache { - override val students: Flow<DiaryCachedStudents> = flowOf(NoStudents) - override val selectedStudentId: Flow<Long?> = flowOf(null) - override suspend fun selectStudent(id: Long?) = Unit - override fun week(studentId: Long, monday: LocalDate): Flow<DiaryCachedWeek> = - flowOf(DiaryCachedWeek(monday, emptyList(), emptyList(), null, null)) - override fun marks(studentId: Long): Flow<DiaryCachedMarks> = - flowOf(DiaryCachedMarks(null, null, emptyList(), null)) - override fun periods(studentId: Long): Flow<DiaryCachedPeriods> = - flowOf(DiaryCachedPeriods(emptyList(), null)) - override suspend fun clear() = Unit -} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/NoDiaryCache.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/NoDiaryCache.kt new file mode 100644 index 00000000..228eff45 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/NoDiaryCache.kt @@ -0,0 +1,29 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.diary.DiaryCache +import com.lumenpearson.lessons.core.data.diary.DiaryCachedMarks +import com.lumenpearson.lessons.core.data.diary.DiaryCachedPeriods +import com.lumenpearson.lessons.core.data.diary.DiaryCachedStudents +import com.lumenpearson.lessons.core.data.diary.DiaryCachedWeek +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf + +internal val NoStudents = DiaryCachedStudents(emptyList(), loadedAt = null) + +/** + * A cache that holds nothing, for a view model built without one — the tests + * that are about the network and nothing in front of it. + */ +internal object NoDiaryCache : DiaryCache { + override val students: Flow<DiaryCachedStudents> = flowOf(NoStudents) + override val selectedStudentId: Flow<Long?> = flowOf(null) + override suspend fun selectStudent(id: Long?) = Unit + override fun week(studentId: Long, monday: LocalDate): Flow<DiaryCachedWeek> = + flowOf(DiaryCachedWeek(monday, emptyList(), emptyList(), null, null)) + override fun marks(studentId: Long): Flow<DiaryCachedMarks> = + flowOf(DiaryCachedMarks(null, null, emptyList(), null)) + override fun periods(studentId: Long): Flow<DiaryCachedPeriods> = + flowOf(DiaryCachedPeriods(emptyList(), null)) + override suspend fun clear() = Unit +} From 2c889a366b347cf9f857b522c84fed08fb46192a Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 13:25:11 +0300 Subject: [PATCH 08/43] Run the server container as an unprivileged user, with its package installed after its code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit server/Dockerfile had no USER, so uvicorn ran as root inside the container, and it ran `pip install .` with only pyproject.toml copied: setuptools found no `app` to package, and the image worked only because `python -m uvicorn` puts the working directory on the import path and `/srv` is where `app/` was copied afterwards. The code is now copied first and installed after, so the package in site-packages is whole — the region catalog's data included — and imports from any directory. A system user `lessons` runs it. The user owns `/srv` itself and nothing in it: the SQLite default (`./lessons.db`, for a class run without the `db` service) has to be able to create its file there, and the code must not be writable by the process that runs it. The cost of the new order is that a code change re-resolves the dependencies on rebuild; for a server rebuilt a few times a term that is minutes nobody waits on. tests/test_dockerfile.py reads the file for both properties — a non-root USER before CMD, and `COPY app` before the `pip install` — and both failed on the old file. Not covered: there is no Docker here, so the image is written, never built or run. In particular `useradd` on python:3.12-slim and the SQLite path under the new user are unverified. Closes #195 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/Dockerfile | 23 ++++++++++++-- server/tests/test_dockerfile.py | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 server/tests/test_dockerfile.py diff --git a/server/Dockerfile b/server/Dockerfile index fc79a1f5..2ac48084 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -6,11 +6,19 @@ ENV PYTHONUNBUFFERED=1 \ WORKDIR /srv +# The code first and the install after it, not the other way round. With only +# pyproject.toml in place, `pip install .` found no `app` to package and +# installed the dependencies around an empty distribution; the image worked +# only because `python -m uvicorn` puts the working directory on the import +# path and the working directory happened to be where `app/` was copied later. +# Installed after the copy, the package is whole in site-packages — catalog +# data included — and imports from any directory. The price is that a code +# change re-resolves the dependencies on rebuild, which for a server rebuilt a +# few times a term is minutes nobody waits on. COPY pyproject.toml ./ -RUN pip install --no-cache-dir . - COPY app ./app COPY scripts ./scripts +RUN pip install --no-cache-dir . # The revisions and their config, although nothing imports them and the package # metadata above deliberately excludes them. @@ -24,6 +32,17 @@ COPY scripts ./scripts COPY alembic.ini ./ COPY migrations ./migrations +# Not root. Nothing here needs a privilege — 8000 is above 1024, and the +# process only reads its code and talks to the network — and a process that is +# root inside a container is root to whatever a container escape reaches. The +# user owns /srv itself and nothing in it: the SQLite default +# (`sqlite+aiosqlite:///./lessons.db`, for a class run without the `db` +# service) has to be able to create its file there, and the code must not be +# writable by the process that runs it. +RUN useradd --system --no-create-home --shell /usr/sbin/nologin lessons \ + && chown lessons /srv +USER lessons + EXPOSE 8000 # One process runs both the read API and the Telegram long-poll loop. diff --git a/server/tests/test_dockerfile.py b/server/tests/test_dockerfile.py new file mode 100644 index 00000000..306590b7 --- /dev/null +++ b/server/tests/test_dockerfile.py @@ -0,0 +1,56 @@ +"""`server/Dockerfile`, read for the two properties a build would not report. + +Neither is visible from outside: an image that runs as root answers exactly as +one that does not, and a package installed before its code works for as long as +the working directory happens to be the one `app/` was copied into. Nothing +here runs Docker, so the file is what is checked. +""" + +from __future__ import annotations + +from pathlib import Path + +DOCKERFILE = Path(__file__).resolve().parents[1] / "Dockerfile" + + +def _instructions() -> list[tuple[str, str]]: + """``(INSTRUCTION, arguments)`` in order, continuation lines joined.""" + joined = DOCKERFILE.read_text("utf-8").replace("\\\n", " ") + out: list[tuple[str, str]] = [] + for line in joined.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + keyword, _, rest = stripped.partition(" ") + out.append((keyword.upper(), rest.strip())) + return out + + +def test_the_server_does_not_run_as_root(): + """#195. The last `USER` is what `CMD` runs as, and without one it is root.""" + users = [args for keyword, args in _instructions() if keyword == "USER"] + assert users, "no USER: uvicorn runs as root inside the container" + assert users[-1].split(":")[0] not in {"root", "0"}, users[-1] + + # A USER after CMD would change nothing about what CMD runs as. + order = [keyword for keyword, _ in _instructions()] + assert order.index("USER") < order.index("CMD") + + +def test_the_package_is_installed_after_its_code_is_copied(): + """#195. Installed first, `pip install .` packaged an `app` that was not + there yet, and the image imported the copy in the working directory + instead — which only a `python -m` started from `/srv` can see.""" + instructions = _instructions() + install = next( + index + for index, (keyword, args) in enumerate(instructions) + if keyword == "RUN" and "pip install" in args + ) + copied = [ + args.split()[0] + for keyword, args in instructions[:install] + if keyword == "COPY" + ] + assert "pyproject.toml" in copied + assert "app" in copied, "the package is installed before app/ is in the image" From c6ae393d2194ff871efdbc8b2fb2b57ca82d4c7a Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 13:25:39 +0300 Subject: [PATCH 09/43] Point every reference that now crosses HANDOVER.md and docs/history.md at its file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the move, «section 5», «above», «the top of this file» and «the section on #140 below» each led somewhere else than they meant: a batch section in the history pointing at HANDOVER.md's section 6, the opening pointing at #140's «Schema», which is in the history now. Each one names its file, or says «below» when the text it meant moved into the history's «Moved out of section …» parts. Sections 5 to 8 kept their numbers so that most of these stayed one-word edits. Three references needed the fact rather than the pointer, because what they pointed at will not stay: #186's «#119 — read» said «see the opening paragraph», which the next close-out rewrites; the dishka note said «the warmup read above», which meant an opening from 20 September that is gone; and «What the session before it added» names a different batch after every close-out, so the stash note names #187's section by its subject instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- HANDOVER.md | 30 ++++++++++++------- docs/history.md | 80 +++++++++++++++++++++++++++++-------------------- 2 files changed, 66 insertions(+), 44 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index 9fb947be..90cf6bd6 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -44,8 +44,9 @@ messages, not by this paragraph — read them against this list before merging. needs. `0016` creates `usage_counters`, the anonymous school directory's daily count of DaData requests. `0017` files the diary corrections under the child rather than a login, and it is data only. All three went on through the Neon connector (the project named `lessons`) -**before** #140's merge, in one transaction; «Schema» in the section on #140 below says what -the database said. The `0014` chapter still holds: #83's pinned table of the enum column +**before** #140's merge, in one transaction; «Schema» in the section on #140, in +[docs/history.md](docs/history.md) now, says what the database said. The `0014` chapter +still holds: #83's pinned table of the enum column widths fails when a `SAEnum` member's **name** outgrows its `VARCHAR`, which SQLite cannot see and production Postgres finds at the moment somebody marks a day. @@ -315,8 +316,9 @@ here changes what #186 could not answer: a thumb, a haptic, a real GPU, a real l **The milestones as they are now.** The owner renamed all nine on 25 September 2026, so that every title names what its version delivered and every description names its pull requests -and issues, and created the tenth the same day. The older sections of this file quote the -titles of their own time, which a search no longer finds; the third column maps them. The +and issues, and created the tenth the same day. The older batch sections, in `docs/history.md` +now, quote the titles of their own time, which a search no longer finds; the third column +maps them. The `github-pr` skill carries the same table. | # | Title | Called before 25 September | State | Covers | @@ -362,8 +364,9 @@ device on it. #140's additions below belong to #121 where they need a live diary merge. The prose here is kept because it says *why* each one is unverifiable, which an issue title cannot. -**#186 looked at a good part of this on an emulator** (26–27 September 2026; the section -«…the first walk of the app on a device» has the detail). The bullets it answered say so in place, and what an emulator +**#186 looked at a good part of this on an emulator** (26–27 September 2026; its section, +«…the first walk of the app on a device», in `docs/history.md` now, has the detail). The +bullets it answered say so in place, and what an emulator cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — is still here. - **Not one route in `docs/diaries/` has been seen answering.** #134's 1916 routes @@ -548,7 +551,8 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i animations, not dynamic colours, and not the widget — about which what is proved is exactly that the size ladder is monotonic over real sizes. - **Every card in the bot is now drawn**, and that found eight defects in one pass - (section 4). The hole that is left is exactly where it was: the tests assert what is + (section 4, in `docs/history.md` now). The hole that is left is exactly where it was: the + tests assert what is written on a card rather than how it looks in a client, and nobody has opened a live Telegram with these changes. **Nobody draws the widget.** Glance has `glance-appwidget-testing` at the same version as @@ -992,9 +996,11 @@ written parses as it did before. bodies. Rewriting them means rewriting every hash from the first affected commit and force pushing `main` and `dev`: every existing clone breaks, the merge references in the pull requests stop resolving, and the release tags move. The owner decided not to. So a `git log` - older than this batch reads in two languages, and that is expected rather than missed. + older than #51's move into English reads in two languages, and that is expected rather + than missed. -**One thing it found and did not touch.** Five test functions on the server carry a Russian +**One thing the documents' sweep of 19 September 2026 found and did not touch.** Five test +functions on the server carry a Russian word in their names — `test_a_day_with_one_maximum_length_задание_still_sends` and four like it, in `test_bot_message_limits.py` and `test_bot_manage.py`. The rule says identifiers are English; it also says a quotation of what the user sees keeps its Russian, and an identifier @@ -1029,14 +1035,16 @@ start once below 2 GB, and the AVD's Quick Boot image alone is 8.5 GB. The workt `.claude/worktrees/` each carry their own Gradle build directories. **Drop the `Teleport auto-stash` when convenient** (`stash@{0}`, over `c26eace`). It holds -what the IDE generated rather than work — «What the session before it added» lists it — and +what the IDE generated rather than work — #187's section, «…the first instrumented tests…», +lists it — and nothing in a session here drops a stash it did not make. **Restart Android Studio once, when it is free.** Three changes wait for it, because the IDE rewrites those files on exit: `server/.venv` as the Python SDK, the root module as a Python one (which quiets «Unsupported Modules Detected»), and the third-party «Python Portable» plugin disabled, since it fails to load on every start. Everything else in the IDE's set-up -is already in place (see «…the first walk of the app on a device», the section on #186). +is already in place (see «…the first walk of the app on a device», the section on #186, in +`docs/history.md` now). **The tenth milestone exists, and #140 is on it.** The owner created `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` on 25 September and renamed diff --git a/docs/history.md b/docs/history.md index f40d5590..f3777c0e 100644 --- a/docs/history.md +++ b/docs/history.md @@ -18,7 +18,8 @@ The text was moved verbatim out of `HANDOVER.md` on 27 September 2026 (#211), so the conventions of the file it was written in: - «this file» and «this document» mean `HANDOVER.md` as it was when the sentence was - written; + written; a reference that would now lead into the wrong one of the two files names + the file; - sections 5 to 8 are `HANDOVER.md`'s, which kept their numbers; sections 1 to 4 are here, after the oldest batch; - the last three sections hold what was taken out of `HANDOVER.md`'s sections 5, 6 and 7 the @@ -58,7 +59,9 @@ the release build the APK workflow made from `bd7c816`, already installed and jo deleted, `bmgr restore`: a probe file in `files/` and one in the `external` domain came back, the report did not. Again with the transport flagged `is_device_transfer=true`: the same. The Google transport was put back afterwards. The issue closes on this. -- **#119, warmup and `/start` — read.** See the opening paragraph. Closes. +- **#119, warmup and `/start` — read.** On 26 September production's `/api/v1/warmup` + answered `"schema":"0017"`, read through the Vercel connector, and the bot answered + `/start` in the owner's chat. Closes. - **#114, arranging the tabs.** The long press opens the mode (labels fold, the icons wobble); a second touch dragging «Задания» to the first slot lands there; the reader stays on «Календарь», which moves with its tab; back leaves the mode, not the app; the order @@ -481,7 +484,7 @@ changed since `061a716`. ### What nobody has verified in this batch -Section 5 carries each of these with the reason it is unverifiable. In short: +`HANDOVER.md`'s section 5 carries each of these with the reason it is unverifiable. In short: - **Nothing has met a live diary.** «Сетевой город» has never been signed in to for real, on the server or through the phone's port, and Петербург never through the phone. @@ -570,7 +573,7 @@ that exist nowhere else. A later correction is an edit to the Markdown. - **Provider code.** #130 asked for the map and nothing else. Which provider comes second, and how it signs in, is the owner's decision. It is filed as #135 and set out in - section 7. + `HANDOVER.md`'s section 7. - **The teacher's side, and a parent with several children.** The open clients barely touch either, and the overview says so rather than guessing. - **The generator**, for the reason above. @@ -594,7 +597,7 @@ where #85 measured them. - **#128** opened the issue tracker: forty-two issues, #86–#108 closed and #109–#127 open, labelled `type:`, `area:`, `status:` and `needs:`. It also moved the work to a local machine with an emulator and a phone, and wrote down what that unlocks and what it still - cannot do. That is the section «Where the work happens from here» above. + cannot do. That is the section «Where the work happens from here» in `HANDOVER.md`. - **#129** made it a standing rule that a found defect becomes an issue before it becomes a fix, with one issue per finding, `Closes #NN` in the pull request and both numbers in the release notes. The rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` @@ -612,7 +615,8 @@ where #85 measured them. it is: the `Commands` line is the only count in `CLAUDE.md`, and one more place to remember is what this issue now records. -**Nothing new has been verified.** Everything in sections 5 and 7 still stands, and both +**Nothing new has been verified.** Everything in `HANDOVER.md`'s sections 5 and 7 still +stands, and both already point at their issues. `/api/v1/warmup` has still not been read since #61 (#119). ## What the batch before added: the gesture #84 shipped did nothing, and the variables nobody could find @@ -1671,7 +1675,7 @@ None of these is closed; all are verified enough to act on. - **`DATABASE_URL` set to blank or with a leading space** walks past `deployment_problems()`. - Four rotation defects in `:app` (correction editor, diary correction sheet), the widget's narrow-column labels, `docs/widget.md`'s size ladder disagreeing with `docs/design.md`, - stale counts in `docs/architecture.md` and sections 1, 5 and 7 of this file, `docs/app/` + stale counts in `docs/architecture.md` and sections 1, 5 and 7 of `HANDOVER.md`, `docs/app/` missing from the CI path filter, and a dozen string findings — three names for the app, two Russian names for `VIEWER`, a nominative weekday where the sentence needs accusative. @@ -2596,7 +2600,8 @@ The ones that would actually have been felt, one line each: * the widget's «Дальше» column listed the lesson an assembly on screen had replaced. **What only the owner can do.** Three decisions were deliberately left rather than taken, two -of them in section 7 — the widget's tick cadence, and whether the diary credential should +of them in `HANDOVER.md`'s section 7 — the widget's tick cadence, and whether the diary +credential should carry a bound — and the third named in the merged pull request: whether the four API announcements that interpolate a person's text should carry `shorten`, which is a decision about what a notification ought to say rather than a defect. Beyond those, an APK on a real @@ -2622,7 +2627,7 @@ classes and 0 failures. CI was green on that head and on the four before it. adding `testFixtures` to another module's surface for one test. It is reproduced locally the way `WidgetSizeClassTest` reproduces the launcher's rule; `CachedWindowTest` owns the other half — that the repository implements that bound against the real DAO. -* **The dishka wiring has now run on Vercel** — see the warmup read above, which is one +* **The dishka wiring has now run on Vercel** — see the warmup read after #61, which is one request and not a measurement. The 26 ms it adds to a cold start is still measured on a development machine rather than there, and that the webhook path still defers aiogram is read off the imports rather than timed there. @@ -2633,8 +2638,9 @@ classes and 0 failures. CI was green on that head and on the four before it. Before this batch, after PRs #47, #48, #49, #50 and #51 were merged. The last of them is the agent configuration in `.claude/` and the whole written layer of the -project moved into English (see "Everything written about the project is English" in -section 6). It landed as `85064cd`, and `main` and `dev` are level. The database is at +project moved into English (see "Everything written about the project is English", in +«Moved out of section 6» below). It landed as `85064cd`, and `main` and `dev` are level. The +database is at head `0013` and `EXPECTED_REVISION` did not move, so that merge needed no migration. The production deployment it triggered is `READY` on `85064cd`, and `/api/v1/warmup` was read after it: `{"status":"ok","api_version":1,"schema":"0013"}`. That endpoint opens a @@ -2642,7 +2648,8 @@ connection, so it answers for the database too, not only for the code. After that batch, two small ones: #55 and #56 corrected this file's own header — it said PR #51 was open minutes after it had been merged — and a sweep over every document -re-measured the numbers they quote. What that sweep found is at the end of section 6. +re-measured the numbers they quote. What that sweep found is in «Moved out of section 6», +below. Two batches earlier: publishing the repository and everything that followed from it (the history reviewed for secrets, `pytest` in CI spread across cores, artifacts living a @@ -2654,7 +2661,8 @@ what is claimed and what lies beside it cannot drift apart. **PR #50 is merged**, five commits; it needed no migration — the model did not change and the head stayed `0013`. The first two commits are the translation-correction mode across all of -the app's text (see "The correction mode knows about all the text" in section 6 and the new +the app's text (see "The correction mode knows about all the text" in `HANDOVER.md`'s +section 6 and the new section of `docs/design.md`). The other three are **an audit of the whole project by nine subagents, split by area**: the API, the bot, `services` + `schedule` + `models`, the providers + config + migrations, `:core:model` + `:core:data`, the design system + the @@ -2700,8 +2708,9 @@ What is still open: it for Preview too, or do not look at preview deployments. If you are an agent: `CLAUDE.md` first (the project's rules), then this file (what is already -done and what is left), and the agent configuration is in `.claude/` (see section 6, "The -agent configuration lives in `.claude/`"). Treat everything below as verified fact as of the +done and what is left), and the agent configuration is in `.claude/` (see "The +agent configuration lives in `.claude/`", in «Moved out of section 6» below). Treat +everything below as verified fact as of the date above, but **re-check the branches and CI before your first action** — they live their own lives, and this file goes stale the moment it stops being updated. @@ -2801,15 +2810,15 @@ The sixth pass — both of the owner's decisions taken and done: **Section 3.1 was closed entirely when this was written.** One requested item has been added since and is open: scrolling the calendar by years, which is a decision rather than -work — see section 7. +work — see «Moved out of section 7», below, where it is made. The block below is **the state on the day this section was written**, kept because the migration order it records is the thing worth reading twice. It is not today's: the branches, the open pull request and the two test counts have all moved since, and the -paragraph at the very top of this file is the one that is kept current. +paragraph at the very top of `HANDOVER.md` is the one that is kept current. ``` -As of PR #51 — not current; see the top of this file +As of PR #51 — not current; see the top of HANDOVER.md Merged: PR #43, PR #44, PR #45 (six passes, 38 commits, merge 26ad184), then PR #47, #48, #49 and #50 — main at 22399e9 Open: PR #51 (dev → main) — the agent configuration, and this translation @@ -2833,8 +2842,8 @@ curl -s https://<project>.vercel.app/api/v1/warmup # {"status":"ok","schema":" A `"degraded"` here would mean the deploy had not arrived; before `0013` was applied, the same request honestly called the database behind, because `EXPECTED_REVISION` was already -`0013`. The head is `0017` today — see the top of this file — and the same request reads it -the other way round while a revision waits for its merge: the database is *ahead* of the +`0013`. The head is `0017` today — see the top of `HANDOVER.md` — and the same request +reads it the other way round while a revision waits for its merge: the database is *ahead* of the code, and `/warmup` says so in as many words, «База впереди кода…». **The five dependabot pull requests can now be closed without regret** — their bumps arrived @@ -2917,9 +2926,9 @@ simultaneously in the API, the widget, the digests and the calendar. (it adds a `UNIQUE`, and a constraint migrates in the opposite direction from a column), and `0014` before it again. `0015`, `0016` and `0017`, all written on #140, went on before #140's merge, in one transaction. `0017` rewrites a key, which on a database holding rows goes on -after the merge; production held none. «Schema» in that batch's section at the top of this -file has what the database said. What each earlier revision did is in `CLAUDE.md` and in section 7, -item 1. +after the merge; production held none. «Schema» in #140's batch section, above, has +what the database said. What each earlier revision did is in `CLAUDE.md` and in «Moved out of +section 7», item 1, below. --- @@ -2936,20 +2945,24 @@ and what it turned out to be. **One request has come in since, and it is on #140.** On 25 September the owner asked for a way in through the family's own school's diary, with the password never reaching our server (#141). It is built — the first run, the diary-only home, the legal line, the catalog and the -directory — and closes when #140 merges; what nobody has verified about it is in section 5. +directory — and closes when #140 merges; what nobody has verified about it is in +`HANDOVER.md`'s section 5. ~~1. **A pupil choosing their own class.**~~ Done in `8ec2e31`. The phone keeps a list of memberships, shows one of them and switches instantly; the cache is split by class, so - switching works with no network too. What exactly is unverified is in section 5. + switching works with no network too. What exactly is unverified is in `HANDOVER.md`'s + section 5. ~~2. **Corrections over dnevnik2's data, with a reset.**~~ Done in `ce02348`. Pressing a lesson or an assignment opens a window where the fields can be rewritten; under each it says what the diary actually holds. Nothing goes upstream, marks and the turnstile cannot - be corrected, and the bot does not show corrections (section 6). + be corrected, and the bot does not show corrections (`HANDOVER.md`'s + section 6). ~~3. **Two modes on invitation, and a reversible switch between them.**~~ The statement was clarified with the owner: this is the **class's join mode**. Done — `join_mode` on a class, `open` or `invite`; in `invite` the class code lets nobody in and a phone joins with a personal one-time code from the bot. The switch is reversible and disconnects not - one already-connected phone. The details are in section 6, "Who lets a phone in". + one already-connected phone. The details are in `HANDOVER.md`'s section 6, + "Who lets a phone in". ### 3.2. What does not exist at all (long-standing gaps, not regressions) @@ -2993,8 +3006,8 @@ trademark stays a trademark: bundling is allowed, naming a product after it is n ## 4. Open defects: none that #140 does not fix, and one fix that waits for a phone **The defects open as this is written are the ones #140 fixes.** #136–#138 and #145–#160 are -all fixed on its branch and meant to close with its merge — the table is in that batch's -section at the top of this file. The exception is **#156**: crash reports are now excluded +all fixed on its branch and meant to close with its merge — the table is in #140's batch +section, above. The exception is **#156**: crash reports are now excluded from every backup path in the rule files and a test reads both, but whether a phone's backup really leaves them out takes a phone and `bmgr`, so the issue stays open, `needs:device`. Everything below is the record from before the tracker, and it still holds. @@ -3020,7 +3033,7 @@ below again, check the code first for whether it is already closed: - `LARGE` hid the homework → the `LARGE_TALL` threshold lowered from 400 to 300 dp; - `OverlayLayerTest` "failing" on the intercepting layer → **not a defect**: the test was rewritten for compose-bom 2026.09.00, which changed Compose's behaviour. It was red exactly - once, at the merge; see section 6. + once, at the merge; see `HANDOVER.md`'s section 6. The six multi-class findings closed in `569bab8` — do not file those again either: @@ -3040,7 +3053,7 @@ The findings of the last three audits are closed too, and these are the ones eas a second time: - an enum's `server_default` written through `.value` → now `.name`; the column holds `OPEN`, - and three tests check it (section 6); + and three tests check it (`HANDOVER.md`'s section 6); - `burn` assigned an attribute → now a conditional `UPDATE`, and `/join` burns the code before it issues a token; - the mode button was a toggle → it now carries the mode it wants; @@ -3242,7 +3255,8 @@ production on 26 September 2026. Protection and answer a redirect to a login page, so no `curl` from here can settle whether the schema — `0017` once #140 has deployed — and the code that needs it met. It needs the owner's browser or a bypass - token; it has been outstanding since #61 and it is in section 7 for that reason. + token; it has been outstanding since #61 and it was in section 7 for that reason — + «Moved out of section 7», below, since it was read. ## Moved out of section 6 on 27 September 2026 @@ -3581,7 +3595,7 @@ purpose: number 9, `v0.8.0 — On-device checks, 89-region e-diary survey`, whos is still to do; number 10, `v0.9.0 — NetSchool e-diary, onboarding via the school's diary`, which #140 is on; and number 7, `Dependencies — dependabot bumps`, which takes every future bump. The ten titles, and what each was called before the owner renamed them on -25 September, are in the table under «And before that: nothing on a screen is cut off». The +25 September, are in the table under «The milestones» in `HANDOVER.md`. The reason a new one has to be asked for stands for next time: no tool in a session here changes a milestone's state or creates one — `issue_write` only assigns an existing one by number — and there is no `gh` CLI. From ebdb67f70a045e16fb63025a6b70dc7b2486b704 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 13:27:14 +0300 Subject: [PATCH 10/43] Sign every request from credentials held in memory, and stop blocking coroutines on the preferences The three OkHttp interceptors read the server address and the bearers through `runBlocking` on every request: a DataStore round trip on a parked OkHttp thread for the address and another for the bearer, per call. And two coroutines made the same kind of read from inside themselves, parking the dispatcher thread they ran on: `SessionRepositoryImpl.serverStatus` (`baseUrlBlocking`) and the periodic-sync re-arm in `SessionEffects.onActiveClassChanged` (`syncIntervalMinutesBlocking`), which the session repository calls inside its own `withContext`. The interceptors now read `CredentialsSnapshot`, a field `LessonsPreferences` keeps current two ways. Every write refreshes it in the writer's coroutine before returning, so the request that follows a switch of class or of server - the sync a join asks for, the status the settings screen asks of the new address - is signed for the new one rather than for whichever the last emission named. And a follower, launched with the client in the container's scope, refreshes it on every emission, for a write through another instance (`SchoolAlerts` opens its own). Both re-read the store under one lock instead of publishing the value they were handed, so the copy never moves backwards. A request that arrives before anything has been read - the widget's first sync after a cold start - reads the store once, blocking, on OkHttp's thread, which is neither a coroutine nor the main thread. The two coroutine callers suspend on `currentSettings()` now; `startBackgroundSync` and `onActiveClassChanged` became suspend functions for it. The four `*Blocking` reads they used are gone; `languageBlocking`, which `attachBaseContext` needs, stays. `RequestCredentialsTest` drives the real preferences through the real client over an in-memory store (DataStore's file layer cannot replace a file on Windows, where the gates run too): twenty requests read the store not at all, where the old reads came to forty; the first request after a cold start carries the stored address and both bearers; a switch, a leave, a sign-out and a new address are each seen by the very next request with no follower running; the diary bearer follows its own sign-in and sign-out and nothing else; and a write through another instance reaches the copy through the follower. `ServerStatusReadTest` holds the server badge's read on one thread, so a blocking read times it out. Each was watched red against the behaviour it guards: a read per request, no refresh after a write, no follower, and the `runBlocking` read back in `serverStatus`. Not covered: `SchoolAlerts` still reads the preferences and the cached timetable through `runBlocking`, and two of its entry points (`onDataChanged` and the `reschedule` it ends with) are reached from coroutines on the IO dispatcher - the sync's `onDataChanged` and `SessionEffects`. Its KDoc calls that deliberate, and making it suspend reaches into the receivers and the alarm; it is left for its own issue. Nothing here has run on a device. Closes #203 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../data/datastore/CredentialsSnapshot.kt | 73 ++++++ .../core/data/datastore/LessonsPreferences.kt | 126 ++++----- .../lessons/core/data/di/LessonsContainer.kt | 28 +- .../lessons/core/data/di/SessionEffects.kt | 8 +- .../core/data/network/AuthInterceptor.kt | 6 +- .../core/data/network/DiaryAuthInterceptor.kt | 4 +- .../core/data/network/NetworkModule.kt | 30 +-- .../core/data/network/RequestCredentials.kt | 27 ++ .../data/repository/SessionRepositoryImpl.kt | 10 +- .../data/datastore/RequestCredentialsTest.kt | 243 ++++++++++++++++++ .../core/data/di/SessionEffectsTest.kt | 7 +- .../core/data/network/BearerTestSupport.kt | 12 +- .../data/repository/ServerStatusReadTest.kt | 91 +++++++ 13 files changed, 562 insertions(+), 103 deletions(-) create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/CredentialsSnapshot.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/RequestCredentials.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/CredentialsSnapshot.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/CredentialsSnapshot.kt new file mode 100644 index 00000000..aca39771 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/CredentialsSnapshot.kt @@ -0,0 +1,73 @@ +package com.lumenpearson.lessons.core.data.datastore + +import com.lumenpearson.lessons.core.data.network.RequestCredentials +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The request credentials, held in memory for the one reader that cannot + * suspend. + * + * OkHttp runs an interceptor on its own dispatcher thread and gives it no way + * to suspend, so the three of them used to read the preferences through + * `runBlocking`: a DataStore round trip on a parked thread for the address and + * another for the bearer, on every request the app made. This is what they + * read instead — a field. + * + * It is kept current two ways, and both are needed. + * + * * **After every write, in the writer's own coroutine** ([refresh], called by + * [LessonsPreferences] once its `edit` has returned). A switch of class or + * of server is followed at once by a request — the join asks for a sync, the + * settings screen asks the new server how it is — and a copy that waited for + * DataStore's emission to reach a collector would sign that request for the + * class the user had just left, or send it to the old address. + * * **On every emission of the file** ([follow]), for a write that does not go + * through the instance holding this copy: `SchoolAlerts` opens preferences + * of its own. + * + * Both re-read the store under one lock rather than publishing the value they + * were handed, and that is what keeps the copy from ever going backwards. An + * emission can be delivered after a later write has already been published, + * and publishing *it* would put the old class's token back until the next + * emission arrived. DataStore's current value only moves forward, so reads + * that are each published before the next one begins only move forward too. + */ +internal class CredentialsSnapshot( + private val read: suspend () -> RequestCredentials, +) { + @Volatile + private var held: RequestCredentials? = null + + private val publishing = Mutex() + + /** + * For an interceptor, and for nothing else: memory, once anything at all + * has been read. + * + * The exception is a request that arrives before the first read of the + * process has landed — the widget's first sync after a cold start can get + * there before [follow] has had its first emission — and that one reads the + * store, blocking, on OkHttp's thread. That thread is not a coroutine and + * is never the main thread, and an empty copy is not an answer: it would + * send the request to no address with no bearer, and a sync that fails for + * that reason says nothing true about the phone. + */ + fun current(): RequestCredentials = held ?: runBlocking { refresh() } + + /** Reads the store again and publishes what it says; see the class notes. */ + suspend fun refresh(): RequestCredentials = publishing.withLock { + read().also { held = it } + } + + /** + * Keeps the copy current for as long as [changes] emits, which from the + * container's scope is the life of the process. What each emission carries + * is ignored on purpose; see the class notes. + */ + suspend fun follow(changes: Flow<*>) { + changes.collect { refresh() } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt index 727bcd33..460d0e0e 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt @@ -14,6 +14,7 @@ import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore +import com.lumenpearson.lessons.core.data.network.RequestCredentials import com.lumenpearson.lessons.core.data.repository.AppSettings import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiarySessionStore @@ -41,12 +42,14 @@ import com.lumenpearson.lessons.core.model.ThemeMode import com.lumenpearson.lessons.core.model.TodayLayout import com.lumenpearson.lessons.core.model.WeekStart import java.io.IOException +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext /** * One preferences file for the whole app. DataStore forbids opening the same @@ -70,10 +73,15 @@ private val Context.lessonsDataStore: DataStore<Preferences> by preferencesDataS * Session and settings share a file on purpose: they are written from the same * screens, they are both tiny, and a single file means a single fsync and a * single flow to observe. + * + * @param dataStore the app's one file on a phone. A test hands in a store of + * its own, which is the only reason this is not built from the context here. */ -internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellModeSource, SettingsStore { +internal class LessonsPreferences( + private val dataStore: DataStore<Preferences>, +) : DiarySessionStore, ShellModeSource, SettingsStore { - private val dataStore = context.applicationContext.lessonsDataStore + constructor(context: Context) : this(context.applicationContext.lessonsDataStore) /** * A corrupt or unreadable file must not take the app down: it degrades to @@ -84,6 +92,32 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo if (cause is IOException) emit(emptyPreferences()) else throw cause } + /** + * What the OkHttp interceptors read — the address and both bearers, held in + * memory; see [CredentialsSnapshot]. Every [write] brings it up to date + * before returning, and [followCredentials] keeps it there for writes made + * through another instance. + */ + val credentials = CredentialsSnapshot { preferences.first().requestCredentials() } + + /** Runs for as long as the file can emit; the container launches it once. */ + suspend fun followCredentials() = credentials.follow(preferences) + + /** + * The only way anything here is written: DataStore's `edit`, then the copy + * the interceptors read, before the caller moves on. + * + * Every write rather than the eight that move a credential today, so that a + * ninth cannot be added without it. The refresh is not cancellable once the + * edit has landed: a caller cancelled between the two would leave the next + * request signed for the class it had just left, for as long as the + * follower took to hear about it. + */ + private suspend fun write(transform: suspend (MutablePreferences) -> Unit) { + dataStore.edit(transform) + withContext(NonCancellable) { credentials.refresh() } + } + /** The class being shown, or `null` when this device is in none. */ val session: Flow<Session?> = preferences.map { it.activeMembership() }.distinctUntilChanged() @@ -107,7 +141,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo * twice, nor move it to the bottom of a list the user has got used to. */ suspend fun addSession(value: Session) { - dataStore.edit { prefs -> + write { prefs -> prefs.writeMemberships(prefs.memberships().withMembership(value)) prefs.activate(value.classId) } @@ -120,8 +154,8 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo * memberships still on disk. */ suspend fun selectSession(classId: Long) { - dataStore.edit { prefs -> - if (prefs.memberships().none { it.classId == classId }) return@edit + write { prefs -> + if (prefs.memberships().none { it.classId == classId }) return@write prefs.activate(classId) } } @@ -135,7 +169,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo * lands on the same keys [clearSession] would leave behind. */ suspend fun removeSession(classId: Long) { - dataStore.edit { prefs -> + write { prefs -> val remaining = prefs.memberships().filterNot { it.classId == classId } prefs.writeMemberships(remaining) val was = prefs[MembershipKeys.ACTIVE_CLASS_ID] @@ -167,7 +201,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo * half, and it is just as narrow. */ suspend fun clearSession() { - dataStore.edit { prefs -> + write { prefs -> // Written on the way out, because the token this is about to remove // is what the read side uses to recognise somebody who predates the // introduction flag. To be here at all you were in a class, and to @@ -206,17 +240,17 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo preferences.first().toDiarySession() override suspend fun writeDiarySession(value: DiarySession) { - dataStore.edit { it.putDiarySession(value) } + write { it.putDiarySession(value) } } /** A bare `401`; see [dropDiaryToken]. */ override suspend fun clearDiaryToken() { - dataStore.edit { it.dropDiaryToken() } + write { it.dropDiaryToken() } } /** Signing out: the diary and only the diary; [clearSession] is its counterpart. */ override suspend fun forgetDiary() { - dataStore.edit { it.dropDiary() } + write { it.dropDiary() } } override val diaryTarget: Flow<DiaryTarget?> = @@ -228,7 +262,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo preferences.map { it[DiaryKeys.STUDENT_ID] }.distinctUntilChanged() override suspend fun selectStudent(id: Long?) { - dataStore.edit { prefs -> + write { prefs -> if (id == null) prefs.remove(DiaryKeys.STUDENT_ID) else prefs[DiaryKeys.STUDENT_ID] = id } } @@ -250,17 +284,17 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo .distinctUntilChanged() override suspend fun hold() { - dataStore.edit { it[ShellKeys.ONBOARDING_HELD] = true } + write { it[ShellKeys.ONBOARDING_HELD] = true } } override suspend fun release() { - dataStore.edit { it.remove(ShellKeys.ONBOARDING_HELD) } + write { it.remove(ShellKeys.ONBOARDING_HELD) } } override suspend fun settleColdStart(): ShellState { // Read and written in the one transaction, so a join landing between // a separate read and write cannot have its hold taken away. - dataStore.edit { prefs -> + write { prefs -> if (prefs.shellState().mode == ShellMode.NONE) prefs.remove(ShellKeys.ONBOARDING_HELD) } return current() @@ -268,7 +302,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo /** Read-modify-write inside DataStore's transaction, so concurrent edits merge. */ override suspend fun updateSettings(transform: (AppSettings) -> AppSettings) { - dataStore.edit { prefs -> + write { prefs -> val updated = transform(prefs.toSettings()) prefs[KEY_BASE_URL] = updated.baseUrl.trim() prefs[KEY_THEME_MODE] = updated.themeMode.name @@ -340,44 +374,6 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo } } - /** - * Blocking reads for the OkHttp interceptors, which cannot suspend. - * - * They run on OkHttp's dispatcher threads, never on the main thread, and - * DataStore serves everything after the first read from an in-memory cache, - * so the cost is a thread hop rather than disk I/O. - */ - fun tokenBlocking(): String? = runBlocking { currentSession()?.token } - - /** - * The diary bearer, for `DiaryAuthInterceptor`. - * - * A second method rather than a parameter on [tokenBlocking], because the - * two tokens are not two values of one thing: one of them can be present - * while the other is absent, and a caller that took the wrong one would - * send a class token to a family's diary. - * - * @see tokenBlocking - */ - fun diaryTokenBlocking(): String? = runBlocking { currentDiarySession()?.token } - - /** @see tokenBlocking */ - fun baseUrlBlocking(): String = runBlocking { currentSettings().baseUrl } - - /** - * How often the background refresh should run, for the one caller that - * arms it outside the settings screen. - * - * `SessionEffects.onActiveClassChanged` re-installs the periodic worker - * after a sign-out cancelled it, and it is handed a plain `() -> Unit` — - * the table of what happens on a session change holds no coroutines, so - * the interval is read the way the interceptors read a token. It runs on - * the session repository's IO dispatcher, never on the main thread. - * - * @see tokenBlocking - */ - fun syncIntervalMinutesBlocking(): Int = runBlocking { currentSettings().syncIntervalMinutes } - /** * The stored language, read the only way the caller can read it. * @@ -401,7 +397,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo /** @see scheduleFingerprint */ suspend fun writeScheduleFingerprint(value: String) { - dataStore.edit { prefs -> prefs[KEY_SCHEDULE_FINGERPRINT] = value } + write { prefs -> prefs[KEY_SCHEDULE_FINGERPRINT] = value } } /** @@ -425,12 +421,12 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo /** @see bundleTag */ suspend fun writeBundleTag(signature: String, etag: String) { - dataStore.edit { prefs -> prefs[bundleTagKey(signature)] = etag } + write { prefs -> prefs[bundleTagKey(signature)] = etag } } /** @see bundleTag */ suspend fun forgetBundleTag(signature: String) { - dataStore.edit { prefs -> prefs.remove(bundleTagKey(signature)) } + write { prefs -> prefs.remove(bundleTagKey(signature)) } } /** @@ -445,7 +441,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo */ suspend fun forgetBundleTagsOf(classId: Long) { val prefix = bundleTagPrefix(classId) - dataStore.edit { prefs -> prefs.removeKeysStartingWith { it.startsWith(prefix) } } + write { prefs -> prefs.removeKeysStartingWith { it.startsWith(prefix) } } } /** @@ -455,7 +451,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo */ suspend fun forgetBundleTagsOutside(keep: Collection<Long>) { val kept = keep.map { bundleTagPrefix(it) } - dataStore.edit { prefs -> + write { prefs -> prefs.removeKeysStartingWith { name -> name.startsWith(BUNDLE_TAG_PREFIX) && kept.none { name.startsWith(it) } } @@ -489,6 +485,20 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo remove(KEY_SCHEDULE_FINGERPRINT) } + /** + * The same three answers the screens get from [currentSettings], + * [currentSession] and [currentDiarySession], from one emission. + * + * The two bearers stay two fields: one can be present while the other is + * absent, and an interceptor that took the wrong one would send a class + * token to a family's diary. + */ + private fun Preferences.requestCredentials(): RequestCredentials = RequestCredentials( + baseUrl = toSettings().baseUrl, + classToken = activeMembership()?.token, + diaryToken = toDiarySession()?.token, + ) + /** * Enums are stored by name rather than by ordinal, and unknown names fall * back to the default instead of throwing: reordering an enum must not be diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt index 5c2c5346..c32c25cd 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt @@ -52,6 +52,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient @@ -146,7 +147,8 @@ class DefaultLessonsContainer( /** * For work that must outlive whatever screen started it — the GitHub device - * flow keeps polling after its sheet is closed. Process-scoped and never + * flow keeps polling after its sheet is closed, and the interceptors' copy + * of the credentials follows the preferences file. Process-scoped and never * cancelled, like the application's own scope, and for the same reason: the * process ending is the only thing that should end it. */ @@ -173,7 +175,7 @@ class DefaultLessonsContainer( // number, and re-arming at the default would quietly undo a user who // had asked for a different one the last time the app was open. startBackgroundSync = { - SyncScheduler.schedulePeriodic(appContext, preferences.syncIntervalMinutesBlocking()) + SyncScheduler.schedulePeriodic(appContext, preferences.currentSettings().syncIntervalMinutes) }, syncNow = { SyncScheduler.syncNow(appContext, wantsDifferentData = true) }, ) @@ -183,16 +185,26 @@ class DefaultLessonsContainer( /** * One client, two interfaces, two bearers. * - * The diary's token is read through its own provider — see + * The diary's token is read into a field of its own — see * `DiaryAuthInterceptor` — so that neither account can ever be signed with * the other's credentials. + * + * The interceptors read a copy held in memory, and the follower that keeps + * it current is started here, with the client, rather than with the + * container, whose construction on the main thread starts nothing. Launching + * it reads nothing either, wherever this runs; a request that beats its + * first emission reads the store once, on OkHttp's thread — see + * `CredentialsSnapshot.current`. */ private val apis: NetworkModule.Apis by lazy { - NetworkModule.apis( - tokenProvider = { preferences.tokenBlocking() }, - baseUrlProvider = { preferences.baseUrlBlocking() }, - diaryTokenProvider = { preferences.diaryTokenBlocking() }, - ) + containerScope.launch { + // Caught because nothing else would: an exception escaping this + // scope ends the process, and a follower that stopped costs only + // the writes made through another instance — every write through + // this one brings the copy up to date on its own. + runCatching { preferences.followCredentials() } + } + NetworkModule.apis(credentials = preferences.credentials::current) } private val api: LessonsApi by lazy { apis.lessons } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt index d8ca18b9..8cee227e 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt @@ -22,7 +22,9 @@ package com.lumenpearson.lessons.core.data.di * @param startBackgroundSync install the periodic `SyncWorker` at the stored * interval. Idempotent — `schedulePeriodic` enqueues unique work with * `UPDATE`, so asking again neither stacks a second worker nor pushes the - * next run out by a period. + * next run out by a period. It suspends because reading that interval does, + * and it is called from inside the session repository's coroutine: a + * `runBlocking` read here parked the thread that coroutine was running on. * @param syncNow ask for one refresh, as soon as the platform allows. */ internal class SessionEffects( @@ -30,7 +32,7 @@ internal class SessionEffects( private val clearAlerts: () -> Unit, private val replanAlerts: () -> Unit, private val stopBackgroundSync: () -> Unit, - private val startBackgroundSync: () -> Unit, + private val startBackgroundSync: suspend () -> Unit, private val syncNow: () -> Unit, ) { @@ -88,7 +90,7 @@ internal class SessionEffects( * interval and so reaches the collector not at all. `schedulePeriodic` is * idempotent, which is what lets both of them ask. */ - fun onActiveClassChanged() { + suspend fun onActiveClassChanged() { redrawWidget() clearAlerts() replanAlerts() diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt index bbdb294f..e0e42270 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt @@ -10,8 +10,10 @@ import okhttp3.Response * only exists after the user joins a class and disappears again on sign-out - * the OkHttp client outlives both events. * - * [tokenProvider] is blocking on purpose: OkHttp interceptors cannot suspend, - * and they run on OkHttp's own dispatcher threads, never on the main thread. + * [tokenProvider] is called on every request, on OkHttp's own dispatcher + * thread, and cannot suspend — so it answers from memory. It used to read the + * preferences through `runBlocking`, which parked a thread per request; see + * `CredentialsSnapshot` for what it reads now and how that stays current. * * It signs the class timetable's calls only; see [DiaryAuthInterceptor] for the * diary's own bearer and for why the two are not one. diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt index 2f1c994b..d742be0e 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt @@ -21,8 +21,8 @@ import okhttp3.Response * so there is still one connection pool, one dispatcher and one set of * timeouts for the whole app. * - * [tokenProvider] is blocking for the same reason [AuthInterceptor]'s is: - * interceptors cannot suspend, and they run on OkHttp's own threads. + * [tokenProvider] answers from memory for the same reason [AuthInterceptor]'s + * does: it is asked on every request, and an interceptor cannot suspend. */ internal class DiaryAuthInterceptor( private val tokenProvider: () -> String?, diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt index b223053f..565ce5a5 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt @@ -39,12 +39,10 @@ internal object NetworkModule { } /** - * @param tokenProvider blocking read of the stored class bearer, or `null` - * before the device has joined a class. - * @param baseUrlProvider blocking read of the configured server address. - * @param diaryTokenProvider blocking read of the stored diary bearer, or - * `null` while nobody is signed in to a diary. A different token from - * [tokenProvider] and never a substitute for it. + * @param credentials the address and both bearers, asked by each + * interceptor on every request, on OkHttp's own thread. It must answer from + * memory — the container hands in `CredentialsSnapshot.current` — because a + * read of the store here is a parked thread on every call the app makes. * * Timeouts are short enough that the widget's sync worker cannot hang on a * dead school server for minutes. Whether they are long enough is the half @@ -56,11 +54,7 @@ internal object NetworkModule { * before moving any of these: a number raised on a guess is one nobody can * lower again. */ - fun okHttpClient( - tokenProvider: () -> String?, - baseUrlProvider: () -> String, - diaryTokenProvider: () -> String? = { null }, - ): OkHttpClient = OkHttpClient.Builder() + fun okHttpClient(credentials: () -> RequestCredentials): OkHttpClient = OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) @@ -68,7 +62,7 @@ internal object NetworkModule { .retryOnConnectionFailure(true) // Order matters: the URL is rewritten first so the auth interceptors see // the real path when they decide whether the call is theirs to sign. - .addInterceptor(BaseUrlInterceptor(baseUrlProvider)) + .addInterceptor(BaseUrlInterceptor { credentials().baseUrl }) // Two bearers, one client. The class token and the diary token are // independent — either can exist without the other, and signing out of // one must not disturb the other — so each has an interceptor that @@ -76,8 +70,8 @@ internal object NetworkModule { // `/api/v1/diary`, [DiaryAuthInterceptor] touches only it. One client // rather than two because they talk to the same host and there is no // reason to pay for a second connection pool and dispatcher. - .addInterceptor(AuthInterceptor(tokenProvider)) - .addInterceptor(DiaryAuthInterceptor(diaryTokenProvider)) + .addInterceptor(AuthInterceptor { credentials().classToken }) + .addInterceptor(DiaryAuthInterceptor { credentials().diaryToken }) .build() /** Retrofit configured for kotlinx.serialization; see [PLACEHOLDER_BASE_URL]. */ @@ -97,13 +91,9 @@ internal object NetworkModule { * client is the expensive part and all four interfaces want the same one — * the same pool, the same timeouts and the same base-URL rewrite. */ - fun apis( - tokenProvider: () -> String?, - baseUrlProvider: () -> String, - diaryTokenProvider: () -> String?, - ): Apis { + fun apis(credentials: () -> RequestCredentials): Apis { val retrofit = retrofit( - client = okHttpClient(tokenProvider, baseUrlProvider, diaryTokenProvider), + client = okHttpClient(credentials), json = json(), ) return Apis( diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/RequestCredentials.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/RequestCredentials.kt new file mode 100644 index 00000000..eb4b7c87 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/RequestCredentials.kt @@ -0,0 +1,27 @@ +package com.lumenpearson.lessons.core.data.network + +/** + * What the three interceptors put on a request: where it goes and which of the + * two bearers it may carry. + * + * One value rather than three providers because all three come out of the same + * preferences file and change on the same writes — a join, a switch, a + * sign-in, a new address — and one value is one thing to keep current. + * + * @property baseUrl the server address as stored; blank while none is set, + * which [BaseUrlInterceptor] refuses rather than sends. + * @property classToken the bearer of the class on screen, or `null` in none. + * @property diaryToken the diary's own bearer, or `null` while nobody is signed + * in to one. Never a substitute for [classToken]; see [DiaryAuthInterceptor]. + */ +internal data class RequestCredentials( + val baseUrl: String, + val classToken: String?, + val diaryToken: String?, +) { + /** The bearers are secrets, and a data class prints every field it has. */ + override fun toString(): String = + "RequestCredentials(baseUrl=$baseUrl, classToken=${mask(classToken)}, diaryToken=${mask(diaryToken)})" + + private fun mask(token: String?): String = if (token == null) "null" else "<redacted>" +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt index 0e1c3f82..a60bd184 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt @@ -53,8 +53,11 @@ internal class SessionRepositoryImpl( * the armed alarm both describe a class, and after a switch it is the wrong * one until something tells them. The device is still in a class, so they * are re-pointed rather than cleared. + * + * It suspends because one of the things it does reads the preferences, and + * it is called from inside this class's own coroutines. */ - private val onActiveClassChanged: () -> Unit = {}, + private val onActiveClassChanged: suspend () -> Unit = {}, ) : SessionRepository { override val session: Flow<Session?> = preferences.session @@ -70,7 +73,10 @@ internal class SessionRepositoryImpl( // request would be sent to the placeholder host the Retrofit instance // is built with, fail there, and be reported as «сервер не отвечает» — // which is a sentence about a server nobody has named yet. - if (preferences.baseUrlBlocking().isBlank()) return@withContext ServerStatus.NotConfigured + // + // A suspending read: this is a coroutine, and the `runBlocking` read + // that stood here parked the dispatcher thread it was running on. + if (preferences.currentSettings().baseUrl.isBlank()) return@withContext ServerStatus.NotConfigured try { val body = api.warmup() diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt new file mode 100644 index 00000000..63d19e41 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt @@ -0,0 +1,243 @@ +package com.lumenpearson.lessons.core.data.datastore + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import com.lumenpearson.lessons.core.data.network.NetworkModule +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.Session +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeout +import mockwebserver3.Dispatcher +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * What the interceptors put on a request, read through the real preferences and + * the real client — and read from memory. + * + * They used to read the store through `runBlocking` on every request, for the + * address and again for the bearer. The cure has two ways to be wrong, and + * each is a request signed for somebody else: a copy that is still empty when + * a process's first request leaves, and a copy that has not yet heard about a + * switch when the request after it does. Neither may be answered by waiting — + * nothing in the app waits between a switch and the sync it asks for — so no + * test here waits either, except the one about a write the copy can only hear + * about through the store. + * + * The store is [MemoryStore] rather than DataStore's file: what is under test is + * when the copy is filled and refreshed, none of which is about files, and + * DataStore's file layer cannot replace a file on Windows, where these run too. + */ +class RequestCredentialsTest { + + private lateinit var server: MockWebServer + private val scopes = mutableListOf<CoroutineScope>() + + @Before + fun setUp() { + server = answering(MockWebServer()) + } + + @After + fun tearDown() { + server.close() + scopes.forEach { it.cancel() } + } + + /** The regression itself: nothing per request touches the store. */ + @Test + fun `requests are signed from memory, not from the preferences`() = runBlocking { + val store = MemoryStore() + val preferences = LessonsPreferences(store) + preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } + preferences.addSession(session(7, "token-7")) + val client = NetworkModule.okHttpClient(preferences.credentials::current) + val readsBefore = store.reads.get() + + repeat(20) { + assertEquals("Bearer token-7", authorizationOn(client, "/api/v1/bundle")) + } + + assertEquals( + "every request used to read the store again, for the address and for the bearer", + readsBefore, + store.reads.get(), + ) + } + + /** + * A process's first request, before anything has filled the copy — the + * widget's first sync after a cold start can be exactly that. A new store + * holding what the last process wrote, and a new copy holding nothing, is + * what a cold start looks like from here; an empty answer would send that + * sync to no address, without its bearer. + */ + @Test + fun `the first request after a cold start carries what was stored before it`() = runBlocking { + val lastProcess = MemoryStore() + LessonsPreferences(lastProcess).apply { + updateSettings { it.copy(baseUrl = server.url("/").toString()) } + addSession(session(7, "token-7")) + writeDiarySession(DiarySession(login = "parent", token = "diary-1")) + } + + val preferences = LessonsPreferences(MemoryStore(lastProcess.value)) + val client = NetworkModule.okHttpClient(preferences.credentials::current) + + assertEquals("Bearer token-7", authorizationOn(client, "/api/v1/bundle")) + assertEquals("Bearer diary-1", authorizationOn(client, "/api/v1/diary/days")) + } + + /** + * The several-classes half. `select` is followed at once by the sync it + * asks for, and that request must be the new class's — no follower runs + * here, so only the write itself can have told the copy. + */ + @Test + fun `a switch of class signs the very next request`() = runBlocking { + val preferences = LessonsPreferences(MemoryStore()) + preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } + preferences.addSession(session(1, "token-1")) + preferences.addSession(session(2, "token-2")) + val client = NetworkModule.okHttpClient(preferences.credentials::current) + assertEquals("Bearer token-2", authorizationOn(client, "/api/v1/bundle")) + + preferences.selectSession(1) + assertEquals("Bearer token-1", authorizationOn(client, "/api/v1/bundle")) + + preferences.removeSession(1) + assertEquals("Bearer token-2", authorizationOn(client, "/api/v1/bundle")) + + preferences.clearSession() + assertNull( + "a phone that has left every class signs nothing with the last one's token", + authorizationOn(client, "/api/v1/bundle"), + ) + } + + /** The base-URL half: a new address is where the very next request goes. */ + @Test + fun `a new server address takes the very next request`() = runBlocking { + answering(MockWebServer()).use { other -> + val preferences = LessonsPreferences(MemoryStore()) + preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } + val client = NetworkModule.okHttpClient(preferences.credentials::current) + authorizationOn(client, "/api/v1/warmup") + assertEquals(1, server.requestCount) + + preferences.updateSettings { it.copy(baseUrl = other.url("/").toString()) } + authorizationOn(client, "/api/v1/warmup", at = other) + + assertEquals("the old server heard nothing more", 1, server.requestCount) + assertEquals(1, other.requestCount) + } + } + + /** Two accounts, two bearers: signing out of one leaves the other signing. */ + @Test + fun `the diary bearer follows its own sign-in and sign-out, and only its own`() = runBlocking { + val preferences = LessonsPreferences(MemoryStore()) + preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } + preferences.addSession(session(7, "token-7")) + val client = NetworkModule.okHttpClient(preferences.credentials::current) + assertNull(authorizationOn(client, "/api/v1/diary/days")) + + preferences.writeDiarySession(DiarySession(login = "parent", token = "diary-1")) + assertEquals("Bearer diary-1", authorizationOn(client, "/api/v1/diary/days")) + + preferences.forgetDiary() + assertNull(authorizationOn(client, "/api/v1/diary/days")) + assertEquals("Bearer token-7", authorizationOn(client, "/api/v1/bundle")) + } + + /** + * `SchoolAlerts` opens preferences of its own, and a write through that + * instance does not refresh this one's copy; the follower is what hears + * about it. Without one, the copy would name class 2 for ever. + */ + @Test + fun `a write through another instance reaches the copy through the store`() = runBlocking { + val store = MemoryStore() + val preferences = LessonsPreferences(store) + val elsewhere = LessonsPreferences(store) + preferences.addSession(session(1, "token-1")) + preferences.addSession(session(2, "token-2")) + assertEquals("token-2", preferences.credentials.current().classToken) + scope().launch { preferences.followCredentials() } + + elsewhere.selectSession(1) + + withTimeout(10_000) { + while (preferences.credentials.current().classToken != "token-1") delay(10) + } + } + + // ----------------------------------------------------------------------- + + private fun session(classId: Long, token: String) = + Session(classId = classId, className = "$classId«А»", school = null, token = token) + + private fun scope(): CoroutineScope = CoroutineScope(Job() + Dispatchers.IO).also { scopes += it } + + /** The `Authorization` header [path] arrived with [at] that server, or `null`. */ + private fun authorizationOn(client: OkHttpClient, path: String, at: MockWebServer = server): String? { + // The placeholder host is what Retrofit builds against; the base-URL + // interceptor rewrites it, exactly as for every real call. + client.newCall(Request.Builder().url("http://base-url.invalid$path").build()).execute().close() + // The server records a request before it answers, so by the time + // `execute` returns it is either queued there or went somewhere else. + val arrived = at.takeRequest(2, TimeUnit.SECONDS) ?: error("$path never reached ${at.url("/")}") + return arrived.headers["Authorization"] + } + + private fun answering(server: MockWebServer): MockWebServer = server.apply { + dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json").body("{}").build() + } + start() + } + + /** + * DataStore's contract without its file — one value, edits one at a time, + * every change emitted — counting each time anybody starts reading it. + */ + private class MemoryStore(initial: Preferences = emptyPreferences()) : DataStore<Preferences> { + private val state = MutableStateFlow(initial) + private val turn = Mutex() + val reads = AtomicInteger() + + val value: Preferences get() = state.value + + override val data: Flow<Preferences> = flow { + reads.incrementAndGet() + emitAll(state) + } + + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences = + turn.withLock { transform(state.value).toPreferences().also { state.value = it } } + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffectsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffectsTest.kt index e818840e..82332881 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffectsTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffectsTest.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.core.data.di +import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Test @@ -50,7 +51,7 @@ class SessionEffectsTest { * next cold start, which is the one thing a switch is asking to fix. */ @Test - fun `switching class asks for a sync instead of stopping one`() { + fun `switching class asks for a sync instead of stopping one`() = runTest { effects.onActiveClassChanged() assertEquals( @@ -72,7 +73,7 @@ class SessionEffectsTest { * again until the app is killed and reopened. */ @Test - fun `joining a class again after a sign-out re-arms the background refresh`() { + fun `joining a class again after a sign-out re-arms the background refresh`() = runTest { effects.onSignedOut() done.clear() @@ -92,7 +93,7 @@ class SessionEffectsTest { * background sync, and they are one word apart in the container. */ @Test - fun `the two answers point the background sync in opposite directions`() { + fun `the two answers point the background sync in opposite directions`() = runTest { effects.onSignedOut() val signedOut = done.toList() done.clear() diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt index 82704ea2..9ab6a7dd 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt @@ -20,11 +20,13 @@ internal class BearerHarness( diaryToken: String? = DIARY_TOKEN, basePath: String = "/", ) { - private val client = NetworkModule.okHttpClient( - tokenProvider = { classToken }, - baseUrlProvider = { server.url(basePath).toString() }, - diaryTokenProvider = { diaryToken }, - ) + private val client = NetworkModule.okHttpClient { + RequestCredentials( + baseUrl = server.url(basePath).toString(), + classToken = classToken, + diaryToken = diaryToken, + ) + } init { server.dispatcher = object : Dispatcher() { diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt new file mode 100644 index 00000000..f97916b3 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt @@ -0,0 +1,91 @@ +package com.lumenpearson.lessons.core.data.repository + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences +import com.lumenpearson.lessons.core.data.network.LessonsApi +import com.lumenpearson.lessons.core.data.network.dto.BundleDto +import com.lumenpearson.lessons.core.data.network.dto.DeviceMeDto +import com.lumenpearson.lessons.core.data.network.dto.HealthDto +import com.lumenpearson.lessons.core.data.network.dto.JoinRequestDto +import com.lumenpearson.lessons.core.data.network.dto.JoinResponseDto +import com.lumenpearson.lessons.core.data.network.dto.UnlinkResponseDto +import com.lumenpearson.lessons.core.data.network.dto.WarmupDto +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test +import retrofit2.Response + +/** + * The server badge asks the preferences whether an address is set before it + * asks the server anything — from inside a coroutine, where a `runBlocking` + * read parks the dispatcher thread for as long as the file takes to answer. + * + * Held on one thread, so the difference is visible: the test's own thread runs + * the repository's coroutine, and the preferences cannot answer until the test + * says so. A read that suspends lets the test go on and say it; a read that + * blocks holds the only thread that could, and the test times out instead of + * failing on an assertion — which is why it carries a timeout at all. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ServerStatusReadTest { + + @Test(timeout = 20_000) + fun `asking for the server's status suspends on the preferences instead of blocking`() = runTest { + val answer = CompletableDeferred<Unit>() + val repository = SessionRepositoryImpl( + preferences = LessonsPreferences(SlowStore(answer)), + api = NoCallsApi, + cache = NoCache, + ioDispatcher = StandardTestDispatcher(testScheduler), + ) + + val status = async { repository.serverStatus() } + runCurrent() + assertFalse("still waiting for the file, and not holding the thread", status.isCompleted) + + answer.complete(Unit) + + assertEquals( + "no address stored is «not configured», asked of nobody", + ServerStatus.NotConfigured, + status.await(), + ) + } + + /** A file that answers "nothing stored" once it is allowed to. */ + private class SlowStore(private val answer: CompletableDeferred<Unit>) : DataStore<Preferences> { + override val data: Flow<Preferences> = flow { + answer.await() + emit(emptyPreferences()) + } + + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences = + error("nothing here writes") + } + + /** With no address the badge must not reach the network at all. */ + private object NoCallsApi : LessonsApi { + override suspend fun join(body: JoinRequestDto): JoinResponseDto = error("no call expected") + override suspend fun bundle(start: String, days: Int, ifNoneMatch: String?): Response<BundleDto> = + error("no call expected") + override suspend fun health(): HealthDto = error("no call expected") + override suspend fun warmup(): WarmupDto = error("no call expected") + override suspend fun me(): DeviceMeDto = error("no call expected") + override suspend fun unlink(): UnlinkResponseDto = error("no call expected") + } + + private object NoCache : TimetableCache { + override suspend fun forgetClass(classId: Long) = Unit + override suspend fun forgetEverything() = Unit + } +} From b52c0469dd8d14ddd336756819a2e1fb491a950e Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:00:48 +0300 Subject: [PATCH 11/43] Refuse to let another site frame the diary sign-in page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /diary/signin is the one page of ours that takes a password, and it sent neither `Content-Security-Policy: frame-ancestors` nor `X-Frame-Options`, so a page elsewhere could draw it out of sight inside its own: a click aimed at that page would land on «Войти», and a password manager's fill in our fields. The page's CSP already said `default-src 'none'`, which reads as if it covered everything and does not — `frame-ancestors` falls back to nothing and has to be named. Every answer this router draws goes through `_page` and its one header dict, so both headers are now on the form, the refusals (400, 401, 410 on GET and on POST, 503 with the diary off) and the success page alike. The CSP directive is the standard; `X-Frame-Options: DENY` is for the browsers that predate it. tests/test_diary_web.py walks all seven of those answers and checks both headers on each. It failed on the old module at the first page. Not covered: FastAPI's own answers under /diary — a 404 for a path with no code, a 405, a 500 from Starlette's error middleware — carry none of these headers. They are JSON or plain text with no form and nothing to click, and putting headers on them would take an app-wide middleware for a page that has none of its own. Closes #196 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/api/diary_web.py | 14 ++++++++++-- server/tests/test_diary_web.py | 41 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index c055dd78..5b58b817 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -23,7 +23,7 @@ no guess was made (see ``_unspend``, which says why that line is drawn there and not further along). -Three headers do the rest of the work, and each answers a specific leak: +Headers do the rest of the work, and each answers a specific leak: ``Referrer-Policy: no-referrer`` The ticket is in the URL. Any link or image the browser fetched from this @@ -35,6 +35,11 @@ ``X-Robots-Tag: noindex`` A ticket URL pasted somewhere public is worth fifteen minutes; it should not also be worth a search result. +``frame-ancestors 'none'`` and ``X-Frame-Options: DENY`` + The one page here that takes a password must not be drawn inside somebody + else's: framed out of sight, a click aimed at their page lands on «Войти» + and a password manager's fill lands in our fields (#196). The CSP directive + is the standard; the older header is for the browsers that predate it. """ from __future__ import annotations @@ -78,7 +83,12 @@ "X-Content-Type-Options": "nosniff", # No inline script, no external anything. Written down rather than assumed, # so that an added <script> fails visibly instead of running. - "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'", + # `frame-ancestors` is not covered by `default-src` and has to be named. + "Content-Security-Policy": ( + "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; " + "frame-ancestors 'none'" + ), + "X-Frame-Options": "DENY", } _STYLE = """ diff --git a/server/tests/test_diary_web.py b/server/tests/test_diary_web.py index 7f4222e6..4880ccb7 100644 --- a/server/tests/test_diary_web.py +++ b/server/tests/test_diary_web.py @@ -74,6 +74,47 @@ async def test_the_headers_that_keep_the_ticket_out_of_the_world_are_sent(web, t assert "default-src 'none'" in response.headers["content-security-policy"] +async def test_no_page_this_router_draws_can_be_framed( + web, ticket, upstream, session, school_class, monkeypatch +): + """#196. The page takes a password, and `default-src` does not cover + framing: drawn invisibly inside another site, a click aimed at that site + lands on «Войти». Every answer is checked, not only the form, because a + refusal page framed over a real one is the same trick with other words.""" + answers = [ + await web.get(f"/diary/signin/{ticket}"), + await web.get("/diary/signin/never-minted-this"), + await web.post(f"/diary/signin/{ticket}", data={"login": "", "password": ""}), + await web.post( + f"/diary/signin/{ticket}", + data={"login": "parent@example.com", "password": "wrong"}, + ), + # The same ticket, now spent: the POST's own 410. + await web.post( + f"/diary/signin/{ticket}", + data={"login": "parent@example.com", "password": "correct"}, + ), + ] + fresh = await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + answers.append( + await web.post( + f"/diary/signin/{fresh}", + data={"login": "parent@example.com", "password": "correct"}, + ) + ) + monkeypatch.setattr(get_settings(), "diary_secret", "", raising=False) + try: + answers.append(await web.get(f"/diary/signin/{fresh}")) + finally: + get_settings.cache_clear() + + assert [answer.status_code for answer in answers] == [200, 410, 400, 401, 410, 200, 503] + for answer in answers: + assert answer.headers["content-type"].startswith("text/html") + assert "frame-ancestors 'none'" in answer.headers["content-security-policy"] + assert answer.headers["x-frame-options"] == "DENY" + + async def test_a_get_does_not_spend_the_ticket(web, ticket, session): """A link preview or a prefetch would otherwise burn it before anybody had typed anything — and Telegram fetches link previews by itself.""" From f2a685bb17111210e65463b2b25ba4a51156242e Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:01:03 +0300 Subject: [PATCH 12/43] Take naive UTC one way everywhere, and never through datetime.utcnow() Every timestamp column here is a naive DateTime holding UTC, and the server builds that value as datetime.now(UTC).replace(tzinfo=None) in security, linking, tasks, the diary services and the cron. Six places called datetime.utcnow() instead: the FSM storage four times, the phone invite redemption in bot/roles.py and the demo seed. The value is the same; the function is deprecated from Python 3.12, which is what CI and Vercel run, so each call warned and each is scheduled to stop working. The FSM storage gets a _utcnow() of its own, as security, linking and tasks have; the other two take the expression inline, as the cron does. tests/test_naive_utc.py reads app/, scripts/ and migrations/ as syntax trees and fails on utcnow or utcfromtimestamp taken off datetime, the module or the class. It reads the source rather than the warnings, because a warning only fires on a path some test happens to drive. It matches the attribute rather than the text, because diary_link.utcnow() and its two siblings are the idiom rather than the slip; a second test holds both halves of that. It named all six on the code before this commit. Not covered: tests/ still calls datetime.utcnow() eleven times in four files (test_api_extended, test_diary_keepalive, test_fsm_storage, test_hardening). They warn in the test run only, and several of those files are being edited by other work right now, so they are left to a change of their own rather than folded in here. Closes #197 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/bot/roles.py | 4 +- server/app/fsm_storage.py | 17 +++++-- server/scripts/seed_demo.py | 4 +- server/tests/test_naive_utc.py | 85 ++++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 9 deletions(-) create mode 100644 server/tests/test_naive_utc.py diff --git a/server/app/bot/roles.py b/server/app/bot/roles.py index d3f8b61a..079fbc6f 100644 --- a/server/app/bot/roles.py +++ b/server/app/bot/roles.py @@ -14,7 +14,7 @@ from __future__ import annotations -from datetime import datetime +from datetime import UTC, datetime from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession @@ -148,7 +148,7 @@ async def claim_phone_invites( membership.full_name = full_name invite.used_by = telegram_id - invite.used_at = datetime.utcnow() + invite.used_at = datetime.now(UTC).replace(tzinfo=None) # The role they now hold, not the one the invite named. The rule above # keeps the higher of the two, so an invite below somebody's existing # role changes nothing — but the caller draws the main menu from what diff --git a/server/app/fsm_storage.py b/server/app/fsm_storage.py index d24aaebe..16992321 100644 --- a/server/app/fsm_storage.py +++ b/server/app/fsm_storage.py @@ -19,7 +19,7 @@ from __future__ import annotations import json -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta from typing import Any from aiogram.fsm.state import State @@ -80,6 +80,13 @@ def _encode(key: StorageKey) -> str: ) +def _utcnow() -> datetime: + """Naive UTC, matching the naive ``updated_at`` column, the way the rest of + the server takes it. ``datetime.utcnow()`` gave the same value and is + deprecated from Python 3.12, which is what CI and Vercel run.""" + return datetime.now(UTC).replace(tzinfo=None) + + class DatabaseStorage(BaseStorage): """aiogram storage that survives the process it was created in.""" @@ -91,7 +98,7 @@ async def set_state(self, key: StorageKey, state: State | str | None = None) -> def apply(record: FsmRecord) -> None: record.state = resolved - record.updated_at = datetime.utcnow() + record.updated_at = _utcnow() # Clearing the state ends the conversation, so its data goes too. # Leaving it behind is how a later flow picks up a stale key and # acts on a date the user chose an hour ago for something else. @@ -111,7 +118,7 @@ async def set_data(self, key: StorageKey, data: dict[str, Any]) -> None: def apply(record: FsmRecord) -> None: record.data = encoded - record.updated_at = datetime.utcnow() + record.updated_at = _utcnow() # Same rule as set_state's, and for the same reason: a row that holds # an empty dict says exactly what no row says. It matters because @@ -156,7 +163,7 @@ async def _write( key=encoded, state=initial_state, data=initial_data, - updated_at=datetime.utcnow(), + updated_at=_utcnow(), ) ) try: @@ -193,7 +200,7 @@ async def purge_stale(self, older_than: timedelta = STALE_AFTER) -> int: See [PREFS_DESTINY] - ``_encode`` puts the destiny last, so that is what the suffix matches. """ - cutoff = datetime.utcnow() - older_than + cutoff = _utcnow() - older_than async with self._session_factory() as session: stale = await session.scalars( select(FsmRecord.key).where( diff --git a/server/scripts/seed_demo.py b/server/scripts/seed_demo.py index 5b86d502..c72fbc31 100644 --- a/server/scripts/seed_demo.py +++ b/server/scripts/seed_demo.py @@ -11,7 +11,7 @@ from __future__ import annotations import asyncio -from datetime import date, datetime, time, timedelta +from datetime import UTC, date, datetime, time, timedelta from sqlalchemy import select @@ -220,7 +220,7 @@ async def seed() -> None: class_id=klass.id, device_name="Демо-телефон", telegram_id=DEMO_EDITOR_ID, - linked_at=datetime.utcnow(), + linked_at=datetime.now(UTC).replace(tzinfo=None), ) ) diff --git a/server/tests/test_naive_utc.py b/server/tests/test_naive_utc.py new file mode 100644 index 00000000..777c0e43 --- /dev/null +++ b/server/tests/test_naive_utc.py @@ -0,0 +1,85 @@ +"""One way of taking «now» in naive UTC, and it is not ``datetime.utcnow()``. + +Every timestamp column here is a naive ``DateTime`` holding UTC, and the server +builds that value as ``datetime.now(UTC).replace(tzinfo=None)`` — in +``security``, ``linking``, ``tasks``, the diary services and the cron. Six +places used ``datetime.utcnow()`` instead: the FSM storage four times, the +phone-invite redemption and the demo seed. Same value, but the function is +deprecated from Python 3.12, which is what CI and Vercel run, so each call +warned and each is scheduled to stop working (#197). + +The check reads the source rather than the warnings, because a warning is only +raised on a path a test happens to drive, and the four in the FSM storage sit +on paths most tests never reach. It looks for the *attribute* on ``datetime`` +— the module or the class — rather than for the text ``utcnow(``: three +services export a helper of that name (``diary_link.utcnow`` and its two +siblings), which is the idiom rather than the slip, and the modules that call +them belong to other people. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +SERVER = Path(__file__).resolve().parents[1] + +#: What ships, and what a person runs against a real database. +ROOTS = ("app", "scripts", "migrations") + +#: Both are deprecated from 3.12 for the same reason; ``utcfromtimestamp`` is +#: the same slip made from a number instead of from the clock. +DEPRECATED = {"utcnow", "utcfromtimestamp"} + + +def _is_datetime(node: ast.expr) -> bool: + """``datetime`` the module or the class, and ``datetime.datetime``.""" + if isinstance(node, ast.Name): + return node.id == "datetime" + return isinstance(node, ast.Attribute) and node.attr == "datetime" + + +def _offences(tree: ast.AST) -> list[tuple[int, str]]: + return [ + (node.lineno, node.attr) + for node in ast.walk(tree) + if isinstance(node, ast.Attribute) + and node.attr in DEPRECATED + and _is_datetime(node.value) + ] + + +def test_nothing_takes_the_time_through_the_deprecated_constructors(): + found: list[str] = [] + for root in ROOTS: + for path in sorted((SERVER / root).rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + found += [ + f"{path.relative_to(SERVER).as_posix()}:{line} datetime.{name}" + for line, name in _offences(tree) + ] + assert found == [], ( + "naive UTC is `datetime.now(UTC).replace(tzinfo=None)` here; " + "`datetime.utcnow()` is deprecated from Python 3.12: " + ", ".join(found) + ) + + +def test_the_check_recognises_the_slip_and_not_the_idiom(): + """Held here rather than trusted: a matcher narrower than its sentence is + how a guard reports green over the thing it was written for.""" + for source in ( + "datetime.utcnow()", + "datetime.datetime.utcnow()", + "stamp = datetime.utcnow() - timedelta(days=2)", + "Column(DateTime, default=datetime.utcnow)", + "datetime.utcfromtimestamp(0)", + ): + assert _offences(ast.parse(source)), source + + for source in ( + "datetime.now(UTC).replace(tzinfo=None)", + "diary_link.utcnow()", + "utcnow()", + "device_invites.utcnow() - timedelta(seconds=1)", + ): + assert not _offences(ast.parse(source)), source From 4275bc0397b27fd224da917c08213d11240386d9 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:05:15 +0300 Subject: [PATCH 13/43] Tell the reader of a spent sign-in link that it is spent, and which buttons make the next MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The diary sign-in page spends its ticket before the upstream sign-in, and only a diary that did not answer hands it back. Every other failure then drew a page a reader could take for «press again»: the crash page said «Что-то пошло не так. Попробуйте ещё раз.» outright, and the rest ended on «Вернитесь в бота и запросите ссылку заново» under a heading like «Неверный логин или пароль», which reads as «retype it». Either way the nearest thing to hand — the back button, or the card in the chat with the old link on it — opened a link that answered 410. Now every page after a spent ticket ends on «Эта ссылка уже израсходована — войти по ней ещё раз не получится», and then says where the next one comes from by the bot's own buttons: «📒 Мой дневник» → «🔐 Войти в дневник». A verdict's own advice (the parent's-account one, say) goes before that, never instead of it, so the two verdicts that each carried their own «попросите у бота новую ссылку» lost it rather than say it twice. The crash page no longer says «Попробуйте ещё раз». A kept ticket still says the link still works. The button names are copied into the page rather than imported, because importing the bot's keyboards would put aiogram on the page's cold start; a test builds the real main menu and signed-out keyboard and holds the page to their labels. tests/test_diary_web.py drives five spending failures — a wrong password, an expired one, an account with no pupil, an unreadable answer and our own crash — and checks each page says the link is spent, names the buttons, never says «попробуйте ещё раз», and that the link really answers 410 afterwards. All five and the label test failed on the old module; the kept-ticket guard passes on both, as it should. docs/bot.md says it in a sentence. Not covered: the 410 page for a class unbound since the link was made still says «Попросите у администратора класса новую ссылку», and the 503 page for a server with the diary switched off still points at the bot; neither is a ticket this attempt spent, and both are left as they were. Closes #193 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/bot.md | 3 ++ server/app/api/diary_web.py | 42 ++++++++++++------ server/tests/test_diary_web.py | 80 ++++++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 14 deletions(-) diff --git a/docs/bot.md b/docs/bot.md index e79b6dc0..03018209 100644 --- a/docs/bot.md +++ b/docs/bot.md @@ -540,6 +540,9 @@ server instead of saying «попробуйте ещё раз» under «логи account the diary accepted but that lists no pupil is a `403` that spends it — the password was judged — and says «В этой учётной записи нет ученика», with a new link for a parent's or a pupil's account, instead of «ответил непонятно» and a link that fails the same way. +Whatever else it says, a page after a spent ticket ends on «Эта ссылка уже израсходована…» +and the way to the next one, «📒 Мой дневник» → «🔐 Войти в дневник»; the crash page used to +say «Попробуйте ещё раз» over a link that then answered `410` (#193). The session is stored encrypted (`DIARY_SECRET`, `app/crypto.py`). Without that key the whole feature refuses at the door rather than falling back to diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index 5b58b817..61d7ed86 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -132,8 +132,20 @@ def _page(title: str, body: str, status: int = 200) -> HTMLResponse: ) -#: What to do next when the ticket is gone: there is no way back but the bot. -_ASK_AGAIN = "Вернитесь в бота и запросите ссылку заново." +#: Where a new link comes from: there is no way back but the bot. The buttons +#: are named because «запросите ссылку заново» left the reader to find where, +#: and the nearest thing to hand — the browser's back button, or the card in +#: the chat with the old link on it — opens a link that answers 410. +#: Copied from `bot/keyboards.main_menu` and `bot/diary_keyboard`, not imported: +#: that would put aiogram on this page's cold start. A test holds the two to +#: the same words. +_ASK_AGAIN = "Новую ссылку даст бот: «📒 Мой дневник» → «🔐 Войти в дневник»." + +#: What to say when *this attempt* spent the ticket. Every such page used to +#: end on a sentence a reader could take for «try again» — the crash page said +#: exactly «Попробуйте ещё раз» — and the same link then answered 410 (#193). +#: So it says first that the link is used up, and only then where to get one. +_SPENT = f"Эта ссылка уже израсходована — войти по ней ещё раз не получится. {_ASK_AGAIN}" #: What to do next when the ticket survived, because the failure was the #: diary's. Said out loud, because a page that only reports a problem reads as @@ -364,18 +376,19 @@ async def sign_in_submit( verdict = _why(error, binding) if verdict.keep_ticket: await _unspend(session, ticket_id) - return _closed( - verdict.message, - status=verdict.status, - note=verdict.note or (_TRY_AGAIN if verdict.keep_ticket else _ASK_AGAIN), - ) + note = verdict.note or _TRY_AGAIN + else: + # Whatever else the verdict advises, a spent ticket always ends on + # _SPENT: advice without it reads as «fix that and press again». + note = f"{verdict.note} {_SPENT}" if verdict.note else _SPENT + return _closed(verdict.message, status=verdict.status, note=note) except Exception: # noqa: BLE001 - never let an upstream shape reach the page log.exception("diary sign-in failed") # The ticket stays spent. This catches everything, including whatever # we might raise *after* the upstream has already judged the password, # so it cannot be told apart from an attempt — and an attempt is what # the ticket pays for. - return _closed("Что-то пошло не так. Попробуйте ещё раз.", status=500) + return _closed("Что-то пошло не так.", status=500, note=_SPENT) opened.class_id = ticket.class_id await session.commit() @@ -397,9 +410,10 @@ class _Verdict(NamedTuple): #: True when the failure was the diary's rather than the person's, so the #: ticket goes back and the same link still opens the form. keep_ticket: bool - #: What to do next, when neither «попробуйте ещё раз» nor «запросите - #: ссылку заново» is true. Chosen by `keep_ticket` alone, the Госуслуги - #: refusal told the family to retry what it had just said cannot work. + #: What to do next, beyond what the ticket decides. For a kept ticket it + #: replaces «попробуйте ещё раз»: chosen by `keep_ticket` alone, the + #: Госуслуги refusal told the family to retry what it had just said cannot + #: work. For a spent one it goes *before* `_SPENT`, never instead of it. note: str | None = None @@ -458,8 +472,7 @@ def _why(error: DiaryError, binding: Binding) -> _Verdict: error.message, 403, keep_ticket=False, - note="Войдите под учётной записью родителя или ученика — " - "попросите у бота новую ссылку.", + note="Войдите под учётной записью родителя или ученика.", ) if isinstance(error, BadCredentials): # PasswordExpired and any other BadCredentials with its own words keep @@ -489,7 +502,8 @@ def _why(error: DiaryError, binding: Binding) -> _Verdict: return _Verdict( "Дневник ответил непонятно — обычно это технические работы или проверка " "«я не робот». Пароль, скорее всего, ни при чём: откройте " - f"{_site_of(binding)} в браузере, а потом попросите у бота новую ссылку.", + f"{_site_of(binding)} в браузере — если дневник открывается, войдите по " + "новой ссылке.", 502, keep_ticket=False, ) diff --git a/server/tests/test_diary_web.py b/server/tests/test_diary_web.py index 4880ccb7..297d8710 100644 --- a/server/tests/test_diary_web.py +++ b/server/tests/test_diary_web.py @@ -596,3 +596,83 @@ async def test_a_region_that_takes_only_gosuslugi_does_not_say_try_again( row = await session.scalar(select(DiaryLinkCode)) await session.refresh(row) assert row.used_at is None, "nothing looked at the password" + + +# ---- what a spent ticket tells the reader (#193) ---------------------------- + + +def _raises(error: Exception): + async def sign_in(*args, **kwargs): + raise error + + return sign_in + + +@pytest.mark.parametrize( + ("error", "status"), + [ + ("BadCredentials", 401), + ("PasswordExpired", 401), + ("NoStudents", 403), + ("UnexpectedResponse", 502), + ("RuntimeError", 500), + ], +) +async def test_a_page_after_a_spent_ticket_says_it_is_spent_and_where_the_next_one_is( + web, ticket, session, monkeypatch, error, status +): + """#193. Every failure that keeps the ticket spent used to end on words a + reader could take for «press again» — the crash page said «Попробуйте ещё + раз» outright — and the same link then answered 410. The page now says + the link is used up, and names the bot's buttons that make a new one.""" + from app.providers.diary import errors + + raised = RuntimeError("boom") if error == "RuntimeError" else getattr(errors, error)() + monkeypatch.setattr(from_app.diary_service, "sign_in", _raises(raised)) + + page = await web.post( + f"/diary/signin/{ticket}", data={"login": "parent", "password": "correct"} + ) + + assert page.status_code == status + assert "попробуйте ещё раз" not in page.text.casefold() + assert "уже израсходована" in page.text + assert "«📒 Мой дневник» → «🔐 Войти в дневник»" in page.text + # And it is true: the link the page is talking about is gone. + again = await web.post( + f"/diary/signin/{ticket}", data={"login": "parent", "password": "correct"} + ) + assert again.status_code == 410 + + +async def test_a_page_after_a_kept_ticket_does_not_call_it_spent( + web, upstream, ticket, LOGIN_PATH +): + """The other half: a diary that did not answer hands the ticket back, and + telling that reader to go to the bot would cost a trip for nothing.""" + upstream.routes[LOGIN_PATH] = _refuses + + page = await web.post( + f"/diary/signin/{ticket}", data={"login": "parent", "password": "correct"} + ) + + assert page.status_code == 503 + assert "израсходована" not in page.text + assert "ещё действует" in page.text + + +def test_the_buttons_the_page_names_are_the_bots_own(): + """The page quotes the path to a new link, and cannot import it — that + would put aiogram on its cold start. So the words are held here: renaming + either button without the page would send people looking for one that + is not there.""" + from app.bot.diary_keyboard import signed_out_keyboard + from app.bot.keyboards import main_menu + from app.models import Role + + def labels(markup) -> set[str]: + return {button.text for row in markup.inline_keyboard for button in row} + + assert "📒 Мой дневник" in labels(main_menu(Role.VIEWER, diary_provider="petersburg")) + assert "🔐 Войти в дневник" in labels(signed_out_keyboard(can_sign_in=True)) + assert "«📒 Мой дневник» → «🔐 Войти в дневник»" in from_app._ASK_AGAIN From fda30ba8950525768ff228330c0b121388e38420 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:48:11 +0300 Subject: [PATCH 14/43] =?UTF-8?q?Read=20=C2=ABtoday=C2=BB=20for=20an=20unr?= =?UTF-8?q?eadable=20=C2=AB=D0=A1=D0=B5=D1=82=D0=B5=D0=B2=D0=BE=D0=B9=20?= =?UTF-8?q?=D0=B3=D0=BE=D1=80=D0=BE=D0=B4=C2=BB=20session=20in=20Moscow,?= =?UTF-8?q?=20not=20on=20the=20host's=20clock?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A NetSchool session whose credential will not parse, or names a region the allow-list no longer serves, opens as a dead connection whose every call is SessionExpired. Its `today()` is still asked first — the diary routes size the range they read from it before the call that expires the row — and it was `datetime.now().date()`, the server's naive clock. Vercel runs in UTC, so from 00:00 to 03:00 Moscow time that was yesterday. A live connection already read its region's zone; the dead one has no region, so it now reads the zone `NetSchoolProvider.zone` falls back to for an unknown region — `app.timezones.resolve(None)`, Moscow — which is also what Petersburg's diary and a class with no zone fall back to. tests/test_netschool_client.py freezes the clock at 00:30 on 8 September in Moscow (21:30 UTC on the 7th) and opens both kinds of dead credential; both answered the 7th on the old code and answer the 8th now. Not covered: the consequence was a range a day early on a session about to be expired anyway, so nothing a reader could see changes. One naive read is left in the server, and it is not this issue's: `bot/handlers/diary.py` falls back to `Date.today()` when `school_class.tz` is None, which it never is — `SchoolClass.tz` always resolves to a zone — so the branch is unreachable rather than wrong, and it belongs to the bot's owner to remove. Closes #198 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/providers/netschool/provider.py | 6 +++- server/tests/test_netschool_client.py | 35 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/server/app/providers/netschool/provider.py b/server/app/providers/netschool/provider.py index 551b5f97..c901a755 100644 --- a/server/app/providers/netschool/provider.py +++ b/server/app/providers/netschool/provider.py @@ -375,7 +375,11 @@ class _DeadConnection: credential = "" def today(self) -> Date: - return datetime.now().date() + # The routes size their range from this before the first call raises, + # so it is a real «today». There is no region to read a zone from, so + # it is the zone `NetSchoolProvider.zone` falls back to — never the + # host's clock, which on a UTC server is yesterday until 03:00 Moscow. + return datetime.now(resolve(None)).date() async def _dead(self, *a, **k): # noqa: ANN002, ANN003, ARG002 raise SessionExpired diff --git a/server/tests/test_netschool_client.py b/server/tests/test_netschool_client.py index d34807ca..6085dc87 100644 --- a/server/tests/test_netschool_client.py +++ b/server/tests/test_netschool_client.py @@ -182,6 +182,41 @@ def handler(request: httpx.Request) -> httpx.Response: assert region is not None +@pytest.mark.parametrize( + "credential", + [ + "not json at all", + json.dumps({"v": 1, "region": "atlantis", "school_id": 1, "at": "a", "cookies": {}}), + ], +) +def test_a_dead_session_reads_today_in_moscow_not_on_the_servers_clock( + monkeypatch, credential +): + """#198. A credential that will not parse, or names a region no longer + served, still answers «today» — and it read the server's naive clock, + which on a UTC host is yesterday from 00:00 to 03:00 Moscow time. It has + no region to take a zone from, so it takes the one `NetSchoolProvider.zone` + falls back to for exactly that case.""" + from datetime import UTC, date, datetime + + from app.providers.netschool import provider as nsprovider + + class Frozen(datetime): + @classmethod + def now(cls, tz=None): + # 00:30 on 8 September in Moscow; the naive answer is a UTC host's. + moment = datetime(2026, 9, 7, 21, 30, tzinfo=UTC) + return moment.astimezone(tz) if tz is not None else moment.replace(tzinfo=None) + + monkeypatch.setattr(nsprovider, "datetime", Frozen) + + connection = NetSchoolProvider().open(credential) + + assert type(connection).__name__ == "_DeadConnection" + assert NetSchoolProvider().zone(None) == "Europe/Moscow" + assert connection.today() == date(2026, 9, 8) + + async def test_two_families_cookies_never_meet_on_the_shared_client(monkeypatch): cookies_seen: list[str | None] = [] From 5e8c31fc9a7e7c56db346f48337cf3974b4d33a6 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:50:37 +0300 Subject: [PATCH 15/43] Hold the diary's picked target in its state, and give its handles one owner each MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DiaryViewModel kept seven mutable fields beside its StateFlow, each written wherever it happened to be needed. They were not all the same kind of thing, and they now live where their kind says. `chosen`, the diary picked on the form until a sign-in to it lands, is the screen's own and lives exactly as long as the rest of the screen's state, so it is a field of DiaryUiState. The sign-out that rebuilds the state forgets it with everything else, which is what the separate `chosen = null` there did. The other six are not state — nothing on the screen draws them — and each now has one private holder that alone changes it, with a comment saying why it is not in the state: - `loadJob` and `startRefresh` are JobSlots: launching cancels the job before, and `running` is the job while it is active. The checks read exactly as before (`isActive != true` is `running == null`). - `periods` is a PeriodMemo, a term per pupil asked for once and forgotten on the two occasions it was cleared before: a landed sign-in and a sign-out. - `storedTarget`, `boundTarget` and `onboarding` are the last word of three flows the view model is handed, in one `Heard` value written only by `hear`, from their collectors. They stay out of DiaryUiState on purpose: a sign-out resets that wholesale, and the class's binding is a distinctUntilChanged flow that will not say it again, so keeping it there would send the next sign-in to Petersburg instead of the class's diary. The holders are declared above `init`, as the fields were, because on Main.immediate the collectors launched there run before `init` returns. No behaviour changes. The diary's view model tests (94, in ten classes) pass unchanged. Refs #209 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../lessons/ui/diary/DiaryUiState.kt | 8 + .../lessons/ui/diary/DiaryViewModel.kt | 200 +++++++++++++----- 2 files changed, 150 insertions(+), 58 deletions(-) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt index 23a2e99b..5824ecdb 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryUiState.kt @@ -61,6 +61,14 @@ data class DiaryUiState( val signInTarget: DiaryTarget = DiaryTarget.petersburg(""), val place: DiaryPlace? = null, val picking: Boolean = false, + /** + * The diary picked on this screen, until a sign-in to it lands — the first + * of [signInTarget]'s sources. Here rather than beside the view model's + * other bookkeeping because it is the screen's own and lives exactly as + * long as the rest of this state: a sign-out forgets it with everything + * else. + */ + val chosen: DiaryTarget? = null, val signingOut: Boolean = false, val students: List<DiaryStudent> = emptyList(), val studentsLoading: Boolean = false, diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index 57cef171..97fbf9af 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -21,6 +21,7 @@ import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.Clock import java.time.Instant import java.time.LocalDate +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope @@ -64,7 +65,7 @@ class DiaryViewModel( binding: Flow<DiaryBinding?> = flowOf(null), private val describe: suspend (DiaryTarget) -> DiaryPlace? = { null }, private val clock: Clock = Clock.systemUTC(), - /** The shell's hold: the first run owns the screen; see [onboarding]. */ + /** The shell's hold: the first run owns the screen; see [Heard.onboarding]. */ held: Flow<Boolean> = flowOf(false), ) : ViewModel() { @@ -73,37 +74,27 @@ class DiaryViewModel( ) val uiState: StateFlow<DiaryUiState> = state.asStateFlow() + // What follows is everything this class holds beside [state], and none of + // it is state: nothing on the screen draws a job, a memo or the last word + // of a flow. Each is a private holder that alone changes what it holds, + // declared above `init` because the collectors there can reach them before + // `init` has returned. + /** Cancelled and replaced whenever the pupil, the week or the tab changes. */ - private var loadJob: Job? = null + private val loadJob = JobSlot(viewModelScope) /** The home's start refresh while it runs; see [refreshOnStart]. */ - private var startRefresh: Job? = null + private val startRefresh = JobSlot(viewModelScope) /** Asked for once per pupil: terms do not change while a screen is open. */ - private val periods = mutableMapOf<Long, DiaryPeriod?>() - - /** A diary picked on this screen, until a sign-in to it lands. */ - private var chosen: DiaryTarget? = null - - /** What a bare `401` left, and what the class's join said; see [DiaryUiState.signInTarget]. */ - private var storedTarget: DiaryTarget? = null - private var boundTarget: DiaryTarget? = null + private val periods = PeriodMemo() /** - * The first run holds the screen, and its import is the one reading the - * diary — pupils included. - * - * This view model is the activity's, so one made by an earlier diary home - * (or by «Настройки → Дневник» on a class phone) is still collecting when a - * later first run signs in. It used to take that session for its own: it - * read the pupils, wrote the first of two as the stored choice — the key - * the import asks before it offers its chooser, so a family with two - * children was never asked — and kept that child in memory even when the - * chooser won, so the home opened on the pupil nobody picked. While held - * it loads nothing; on the release it reads the pupils and the choice the - * import stored, as a home opened for the first time would. + * The latest from the flows this view model is handed besides the session; + * see [Heard]. Replaced by [hear], from their collectors below, and + * nowhere else. */ - private var onboarding = false + private var heard = Heard() init { viewModelScope.launch { @@ -144,15 +135,15 @@ class DiaryViewModel( ) } settleTarget() - if (session != null && state.value.students.isEmpty() && !onboarding) loadStudents() + if (session != null && state.value.students.isEmpty() && !heard.onboarding) loadStudents() } } viewModelScope.launch { held.distinctUntilChanged().collect { holding -> - onboarding = holding + hear { copy(onboarding = holding) } if (holding) { // What an earlier session left running is not the new one's. - loadJob?.cancel() + loadJob.cancel() state.update { it.copy(students = emptyList(), selectedStudentId = null, studentsLoading = false) } } else if (state.value.session != null && state.value.students.isEmpty()) { loadStudents() @@ -161,7 +152,7 @@ class DiaryViewModel( } viewModelScope.launch { repository.target.collect { target -> - storedTarget = target + hear { copy(storedTarget = target) } settleTarget() } } @@ -169,18 +160,28 @@ class DiaryViewModel( binding.map { it?.targetFor(login = "") } .distinctUntilChanged() .collect { target -> - boundTarget = target + hear { copy(boundTarget = target) } settleTarget() } } } + /** The one place [heard] is written. */ + private fun hear(change: Heard.() -> Heard) { + heard = heard.change() + } + /** * Works out [DiaryUiState.signInTarget] again, and what the catalog says * about it when that changed. */ private fun settleTarget() { - val target = signInTargetOf(chosen, state.value.session, storedTarget, boundTarget) + val target = signInTargetOf( + state.value.chosen, + state.value.session, + heard.storedTarget, + heard.boundTarget, + ) if (target == state.value.signInTarget && state.value.place != null) return val sameDiary = state.value.signInTarget.sameDiaryAs(target) state.update { it.copy(signInTarget = target, place = if (sameDiary) it.place else null) } @@ -210,8 +211,7 @@ class DiaryViewModel( * said yes, which is when the repository writes the session and its target. */ fun choose(target: DiaryTarget) { - chosen = target - state.update { it.copy(picking = false, signInError = null) } + state.update { it.copy(chosen = target, picking = false, signInError = null) } settleTarget() } @@ -228,7 +228,10 @@ class DiaryViewModel( state.update { it.copy(signingIn = true, signInError = null) } // Read again rather than taken from the state: the stored target // is a DataStore read that may not have reached the collector yet. - val known = chosen ?: state.value.session?.target ?: repository.target.first() ?: boundTarget + val known = state.value.chosen + ?: state.value.session?.target + ?: repository.target.first() + ?: heard.boundTarget val target = known?.copy(login = login.trim()) ?: DiaryTarget.petersburg(login.trim()) val result = repository.signIn(target, password) val problem = result.exceptionOrNull()?.let { DiarySignInProblem.of(it) } @@ -246,11 +249,10 @@ class DiaryViewModel( ) } if (problem == null) { - chosen = null // The pupils are re-read rather than kept: the same phone may // have signed in as a different parent. - periods.clear() - state.update { it.copy(students = emptyList(), selectedStudentId = null) } + periods.forget() + state.update { it.copy(chosen = null, students = emptyList(), selectedStudentId = null) } loadStudents() } } @@ -262,8 +264,9 @@ class DiaryViewModel( viewModelScope.launch { state.update { it.copy(signingOut = true) } repository.signOut() - periods.clear() - chosen = null + periods.forget() + // A fresh state, which forgets the diary picked on the form with + // everything else; what [heard] holds is not the screen's to forget. state.update { DiaryUiState( ready = true, @@ -331,12 +334,11 @@ class DiaryViewModel( * already on screen are redrawn from the save when it lands. */ fun refreshOnStart(refresh: suspend () -> Result<Boolean>) { - if (startRefresh?.isActive == true) return - val job = viewModelScope.launch { runCatching { refresh() } } - startRefresh = job + if (startRefresh.running != null) return + val job = startRefresh.launch { runCatching { refresh() } } viewModelScope.launch { job.join() - if (loadJob?.isActive != true && state.value.student != null) reload() + if (loadJob.running == null && state.value.student != null) reload() } } @@ -345,7 +347,7 @@ class DiaryViewModel( * so the caller knows the save may have changed under it. */ private suspend fun awaitStartRefresh(): Boolean { - val running = startRefresh?.takeIf { it.isActive } ?: return false + val running = startRefresh.running ?: return false running.join() return true } @@ -366,8 +368,7 @@ class DiaryViewModel( } private fun loadStudents(force: Boolean = false) { - loadJob?.cancel() - loadJob = viewModelScope.launch { loadStudentsNow(force) } + loadJob.launch { loadStudentsNow(force) } } /** @@ -429,8 +430,7 @@ class DiaryViewModel( } private fun reload(force: Boolean = false) { - loadJob?.cancel() - loadJob = viewModelScope.launch { load(force) } + loadJob.launch { load(force) } } /** @@ -566,18 +566,16 @@ class DiaryViewModel( * when the diary cannot answer, since a term from last week is a far better * window than none. */ - private suspend fun currentPeriod(studentId: Long, force: Boolean): DiaryPeriod? { - if (!force && periods.containsKey(studentId)) return periods[studentId] - val saved = runCatching { cache.periods(studentId).first() }.getOrNull() - val period = if (!force && saved != null && diaryIsFresh(saved.loadedAt, clock.instant())) { - saved.periods.firstOrNull { it.isCurrent } - } else { - repository.periods(studentId).getOrNull()?.firstOrNull { it.isCurrent } - ?: saved?.periods?.firstOrNull { it.isCurrent } + private suspend fun currentPeriod(studentId: Long, force: Boolean): DiaryPeriod? = + periods.of(studentId, force) { + val saved = runCatching { cache.periods(studentId).first() }.getOrNull() + if (!force && saved != null && diaryIsFresh(saved.loadedAt, clock.instant())) { + saved.periods.firstOrNull { it.isCurrent } + } else { + repository.periods(studentId).getOrNull()?.firstOrNull { it.isCurrent } + ?: saved?.periods?.firstOrNull { it.isCurrent } + } } - periods[studentId] = period - return period - } // -- corrections -------------------------------------------------------- // @@ -804,3 +802,89 @@ private val DiaryCachedWeek.savedAt: Instant? val homework = homeworkLoadedAt ?: return null return minOf(lessons, homework) } + +/** + * One coroutine at a time: launching another cancels the one before. + * + * A handle, not state. Nothing draws a job — what a load does is drawn, through + * the flags it writes into [DiaryUiState] — and a `Job` in a data class that + * the screen compares on every emission would be a value that is never equal + * to anything but itself. + */ +private class JobSlot(private val scope: CoroutineScope) { + + private var job: Job? = null + + /** The job in the slot while it runs; `null` once it has finished or before any. */ + val running: Job? get() = job?.takeIf { it.isActive } + + fun launch(block: suspend CoroutineScope.() -> Unit): Job { + job?.cancel() + return scope.launch(block = block).also { job = it } + } + + fun cancel() { + job?.cancel() + } +} + +/** + * The term each pupil is in, asked for once: terms do not change while a + * screen is open. + * + * A memo, not state. Nothing draws a term — what is drawn is the range cut from + * it, [DiaryUiState.gradeRange] — and it lives as long as the account rather + * than the screen: [forget] runs when a sign-in lands and when the diary is + * signed out of, the two moments the pupils it is keyed on can stop being this + * phone's. + */ +private class PeriodMemo { + + private val periods = mutableMapOf<Long, DiaryPeriod?>() + + /** The remembered term, unless [force] or there is none yet; then [read]'s, remembered. */ + suspend fun of(studentId: Long, force: Boolean, read: suspend () -> DiaryPeriod?): DiaryPeriod? { + if (!force && periods.containsKey(studentId)) return periods[studentId] + return read().also { periods[studentId] = it } + } + + fun forget() { + periods.clear() + } +} + +/** + * What the view model last heard from the flows it is handed besides the + * session. + * + * Not in [DiaryUiState], and deliberately. None of the three is the screen's + * to reset: they belong to the repository, the class and the shell, and each + * flow says when it changes. The state is reset wholesale by a sign-out, and + * the binding kept there would be forgotten by the one call after which it + * matters most — its flow does not say it again, so the next sign-in would go + * to Petersburg rather than to the class's diary. Nor does the screen draw + * any of them: what they decide is drawn, as [DiaryUiState.signInTarget] and + * as pupils loaded or not. + * + * @property storedTarget what a bare `401` left; see [DiaryUiState.signInTarget]. + * @property boundTarget what the class's join said; see [DiaryUiState.signInTarget]. + */ +private data class Heard( + val storedTarget: DiaryTarget? = null, + val boundTarget: DiaryTarget? = null, + /** + * The first run holds the screen, and its import is the one reading the + * diary — pupils included. + * + * This view model is the activity's, so one made by an earlier diary home + * (or by «Настройки → Дневник» on a class phone) is still collecting when a + * later first run signs in. It used to take that session for its own: it + * read the pupils, wrote the first of two as the stored choice — the key + * the import asks before it offers its chooser, so a family with two + * children was never asked — and kept that child in memory even when the + * chooser won, so the home opened on the pupil nobody picked. While held + * it loads nothing; on the release it reads the pupils and the choice the + * import stored, as a home opened for the first time would. + */ + val onboarding: Boolean = false, +) From ae77bd00917c21cb6c557721ae449b30fbb899d1 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:51:42 +0300 Subject: [PATCH 16/43] Spend a phone invite with one conditional update, so two deliveries cannot both redeem it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit claim_phone_invites read the pending invites, granted the membership and then assigned used_by and used_at before committing. A webhook Telegram believes went unanswered is delivered again, and the two deliveries run side by side: both read the invite unused, and both wrote it. The same account was answered «Доступ выдан» twice, or the slower delivery died on the membership's unique key; a second account on the number got a BotUser of its own from an invite worth one. The invite is now spent before anything is granted, by UPDATE ... WHERE id = :id AND used_by IS NULL and its row count, the shape device_invites.burn and diary_link.claim already have. The later statement waits on the earlier's lock, re-checks the row, matches nothing, and that delivery grants nothing. The condition is on used_by rather than used_at because used_by is what this table calls used: it is what the pending query filters on and what PhoneInvite.is_used reads, and both columns are only ever written together, here. tests/test_roles.py holds the second claim right after its read, in a session of its own, until the first has committed, for the same account and for another one. Both went red on the old code (both claims granted); both are green now, with one BotUser and the invite spent by the winner. Not covered: the losing delivery returns an empty list, so the handler answers it «Приглашений для этого номера не найдено» — beside the «Доступ выдан» the winning delivery sent. The sentence lives in bot/handlers/start.py, outside this change. The race itself is driven on SQLite; the Postgres row lock it relies on is the one burn relies on, and neither has been run against Postgres from a test. Closes #194 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/bot/roles.py | 23 +++++++++++++-- server/tests/test_roles.py | 59 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/server/app/bot/roles.py b/server/app/bot/roles.py index 079fbc6f..29d15c9a 100644 --- a/server/app/bot/roles.py +++ b/server/app/bot/roles.py @@ -17,9 +17,11 @@ from datetime import UTC, datetime from sqlalchemy import select +from sqlalchemy import update as sa_update from sqlalchemy.ext.asyncio import AsyncSession from app.config import get_settings +from app.db import rows_affected from app.models import BotUser, PhoneInvite, Role, SchoolClass from app.security import normalise_phone @@ -125,12 +127,31 @@ async def claim_phone_invites( ) ) + now = datetime.now(UTC).replace(tzinfo=None) granted: list[tuple[SchoolClass, Role]] = [] for invite in invites: school_class = await session.get(SchoolClass, invite.class_id) if school_class is None: continue + # Spent before anything is granted, by one conditional UPDATE, exactly + # as `device_invites.burn` spends a phone's code: the read above is not + # a claim. A webhook Telegram believes went unanswered is delivered + # again, and the two deliveries both read this invite unused; assigning + # `used_by` and committing let both through. The same account was then + # answered «Доступ выдан» twice, or the slower delivery died on the + # membership's unique key, and a second account on the number got a + # membership of its own from an invite worth one. Here the later + # statement waits on the earlier's lock, re-checks the row after it, + # and matches nothing, so that delivery grants nothing. + spent = await session.execute( + sa_update(PhoneInvite) + .where(PhoneInvite.id == invite.id, PhoneInvite.used_by.is_(None)) + .values(used_by=telegram_id, used_at=now) + ) + if rows_affected(spent) != 1: + continue + membership = await get_membership(session, telegram_id, invite.class_id) if membership is None: membership = BotUser( @@ -147,8 +168,6 @@ async def claim_phone_invites( membership.username = username membership.full_name = full_name - invite.used_by = telegram_id - invite.used_at = datetime.now(UTC).replace(tzinfo=None) # The role they now hold, not the one the invite named. The rule above # keeps the higher of the two, so an invite below somebody's existing # role changes nothing — but the caller draws the main menu from what diff --git a/server/tests/test_roles.py b/server/tests/test_roles.py index b2ada883..f3637329 100644 --- a/server/tests/test_roles.py +++ b/server/tests/test_roles.py @@ -3,9 +3,13 @@ from __future__ import annotations +import asyncio + import pytest +from sqlalchemy import select from app.bot.roles import can_grant, claim_phone_invites, get_role, is_env_owner +from app.db import SessionLocal from app.models import BotUser, PhoneInvite, Role from app.security import normalise_phone @@ -101,6 +105,61 @@ async def test_an_invite_can_only_be_claimed_once(session, school_class): assert await get_role(session, 666, school_class.id) is None +@pytest.mark.parametrize( + "second_account", + [555, 666], + ids=["the same update delivered twice", "another account on the number"], +) +async def test_two_claims_in_flight_spend_an_invite_once( + session, school_class, second_account +): + """Both claims read the invite live; only one of them may spend it. + + A webhook Telegram thinks went unanswered is delivered again, and the two + deliveries run side by side. Redeeming as read, assign, commit let both + read the invite unused and both write it: here the same account is granted + twice, and a second account gets a `BotUser` of its own from an invite + worth one. The second claim is held right after its read, + in a session of its own, until the first has committed — the one + interleaving that decides it, driven deterministically rather than hoped + for from two tasks racing. + """ + session.add( + PhoneInvite(class_id=school_class.id, phone="79001234567", role=Role.EDITOR) + ) + await session.commit() + + async with SessionLocal() as overlapping: + read = asyncio.Event() + written = asyncio.Event() + real_scalars = overlapping.scalars + + async def read_then_hold(*args, **kwargs): + rows = await real_scalars(*args, **kwargs) + if not read.is_set(): + read.set() + await written.wait() + return rows + + overlapping.scalars = read_then_hold + second_claim = asyncio.create_task( + claim_phone_invites(overlapping, second_account, "+79001234567", None, None) + ) + await read.wait() + first = await claim_phone_invites(session, 555, "+79001234567", None, None) + written.set() + second = await second_claim + + assert [bool(first), bool(second)] == [True, False], ( + "one invite, one winner: the claim that lost the race grants nothing" + ) + async with SessionLocal() as after: + members = list(await after.scalars(select(BotUser))) + invite = await after.scalar(select(PhoneInvite)) + assert [(m.telegram_id, m.role) for m in members] == [(555, Role.EDITOR)] + assert invite is not None and invite.used_by == 555 + + async def test_claiming_never_downgrades_an_existing_role(session, school_class): session.add(BotUser(telegram_id=555, class_id=school_class.id, role=Role.ADMIN)) session.add( From d37f94ad187f6d501eceaf271f41f3c5b9559b89 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:53:57 +0300 Subject: [PATCH 17/43] Hand the diary home's start refresh to its view model instead of reading Graph The shell's LifecycleStartEffect was the one composable in :app that reached into `Graph` itself, for `diaryImport.refreshIfStale`. Every other read of the graph is at an entry point: the application, and the view-model factories, which is where this app hands its view models what they are built from. DiaryViewModel now takes the refresh as a constructor parameter, its factory supplies `container.diaryImport.refreshIfStale()`, and `refreshOnStart` runs it when handed nothing, so the shell calls `refreshOnStart()`. The refresh is the same call on the same container, still only from the diary home's start effect, still reading `diaryImport` at the moment it runs. The explicit argument stays for the test that times the refresh against the screen's own load. The DiaryPickerViewModel factory, the one read of `Graph` in a file of composables, says that it is the entry point. TabOrderTest's header said HomeShell was private; the split made it internal, and what keeps it out of a JVM test is the graph its factories read. After this, `grep -rn 'Graph\.' app/src/main` finds LessonsApplication and view-model factories and nothing else. Closes #209 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../com/lumenpearson/lessons/navigation/HomeShell.kt | 7 ++++--- .../lumenpearson/lessons/ui/diary/DiaryPickerPage.kt | 3 +++ .../lumenpearson/lessons/ui/diary/DiaryViewModel.kt | 10 +++++++++- .../lumenpearson/lessons/navigation/TabOrderTest.kt | 4 ++-- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt index 87b2ceb3..3e59b18b 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/HomeShell.kt @@ -40,7 +40,6 @@ import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R -import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.repository.AppSettings import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.designsystem.component.LessonsFloatingToolbar @@ -207,10 +206,12 @@ internal fun HomeShell( // home comes to the front, the week is read again if the saved copy is // stale. Here and nowhere else — not in the application, a receiver or the // worker — because a read is what keeps the server's copy of the session - // alive, and that has to mean somebody opened the app (G4). + // alive, and that has to mean somebody opened the app (G4). What does the + // reading is handed to the view model by its factory, which is where + // `Graph` is read: the shell is a screen, not an entry point. if (diaryViewModel != null) { LifecycleStartEffect(diaryViewModel) { - diaryViewModel.refreshOnStart { Graph.container.diaryImport.refreshIfStale() } + diaryViewModel.refreshOnStart() onStopOrDispose { } } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt index 397f9adf..d0f533e4 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt @@ -446,6 +446,9 @@ class DiaryPickerViewModel( ) companion object { + // The one read of `Graph` in this file, and an entry point rather than + // a screen reaching past its parameters: the page takes this view model + // as an argument, and only its default is built here. val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val container = Graph.container diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index 97fbf9af..6796cadc 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -67,6 +67,13 @@ class DiaryViewModel( private val clock: Clock = Clock.systemUTC(), /** The shell's hold: the first run owns the screen; see [Heard.onboarding]. */ held: Flow<Boolean> = flowOf(false), + /** + * What [refreshOnStart] runs when it is handed nothing: + * `DiaryImport.refreshIfStale`, from the factory. A parameter rather than + * something the diary home reads for itself, so that `Graph` is read where + * view models are built and not from inside a composable. + */ + private val refreshIfStale: suspend () -> Result<Boolean> = { Result.success(false) }, ) : ViewModel() { private val state = MutableStateFlow( @@ -333,7 +340,7 @@ class DiaryViewModel( * the week the refresh just saved is fresh, and the load finds it so. Rows * already on screen are redrawn from the save when it lands. */ - fun refreshOnStart(refresh: suspend () -> Result<Boolean>) { + fun refreshOnStart(refresh: suspend () -> Result<Boolean> = refreshIfStale) { if (startRefresh.running != null) return val job = startRefresh.launch { runCatching { refresh() } } viewModelScope.launch { @@ -762,6 +769,7 @@ class DiaryViewModel( binding = container.sessionRepository.session.map { it?.diary }, describe = { target -> diaryPlaceOf(container.regionLookup.catalog(), target) }, held = container.shellMode.state.map { it.held }, + refreshIfStale = { container.diaryImport.refreshIfStale() }, ) } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/TabOrderTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/TabOrderTest.kt index f418b7cd..f3d8293e 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/TabOrderTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/TabOrderTest.kt @@ -9,8 +9,8 @@ import org.junit.Test /** * Rearranging the bar, and the reader who must not be moved by it. * - * The shell cannot be composed from a JVM test — `HomeShell` is private and - * builds three view models off `Graph`, which wants DataStore, Room and + * The shell cannot be composed from a JVM test — `HomeShell` builds its view + * models from their factories, off `Graph`, which wants DataStore, Room and * Retrofit — so what is held here is the half that can be wrong quietly: which * way round the permutation goes, and that it is still a permutation * afterwards. The gesture that produces it has its own tests in From 787c6c320ef2737a58f43dc0dde621c61a6d4d99 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 14:57:49 +0300 Subject: [PATCH 18/43] Stop a class code minting phones past three hundred, and tell the phone why MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `POST /api/v1/join` counts only failed attempts, so a caller holding a real class code could mint device tokens for ever — each one a live read token for the class, and a row on the admin's device list, until 180 days of silence pruned it. The class code now stops at `MAX_DEVICES_PER_CLASS` live devices (300) and is answered with `409` and a Russian `detail`, minting nothing. The constant's comment says how the number was reached: thirty-odd pupils with a phone each and up to two parents', plus teachers, is about 120, and a row outlives its phone — a reinstall or a new phone joins again and leaves the old token live — so doubling for that residue gives ~250. A revoked device is a tombstone and does not count. Like the invite-only `403`, the `409` is forgiven by the throttle: the caller found a real code, and counting it would lock a whole school's address out of every other class. A personal code from the bot is not refused: it is minted one phone at a time for a member the bot knows, with a name in the journal, and it is the way in left to a family if somebody has filled the class through the shared code. On the phone, `JoinFailure` (`:core:data`) classifies the `409` as `ClassFull` — left as a `Rejected` it read «Не удалось подключиться: HTTP 409 …» — and `JoinError.ClassFull` (`:app`) words it: the code is right, take a personal code in the bot («📱 Подключить телефон»), or ask the admin to switch old phones off in «⚙️ Класс» → «📱 Устройства». The English twin keeps the bot's labels in Russian, as the invite-only sentence does; the comment above them now says labels rather than label. docs/api.md says all of this and lists the `409`. Tests: server/tests/test_join_device_cap.py — the bound, its 409 not counted past the throttle's own limit, revoked rows, per class, and a personal code into a full class; the three that assert the bound failed without the check. JoinFailureTest's 409 case failed with the mapping taken out; JoinErrorTest and JoinErrorTextTest hold the case and its sentence. Not covered: a burst of joins that all count before any commits can pass the bound by the burst's size, once — after it every join counts past it. The bot's «📱 Устройства» page shows the oldest fifteen with buttons, so an admin facing a class filled by a script can revoke the newest rows only from the app's device sheet, one by one; there is no «revoke every anonymous phone». Nothing here was run on a device. Closes #199 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../lessons/ui/join/JoinScreen.kt | 1 + .../lessons/ui/join/JoinViewModel.kt | 11 ++ .../app/src/main/res/values-en/strings.xml | 5 +- android/app/src/main/res/values/strings.xml | 1 + .../lessons/ui/join/JoinErrorTest.kt | 6 + .../lessons/ui/join/JoinErrorTextTest.kt | 14 ++ .../core/data/repository/JoinFailure.kt | 20 ++- .../core/data/repository/JoinFailureTest.kt | 21 ++- docs/api.md | 10 ++ server/app/api/public.py | 45 +++++- server/tests/test_join_device_cap.py | 134 ++++++++++++++++++ 11 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 server/tests/test_join_device_cap.py diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt index 7801f57b..8ae57536 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt @@ -355,6 +355,7 @@ internal fun JoinError?.asText(): String? = when (this) { JoinError.UnknownCode -> correctedString(R.string.join_error_unknown_code) JoinError.NoServer -> correctedString(R.string.join_error_no_server) JoinError.InviteOnly -> correctedString(R.string.join_error_invite_only) + JoinError.ClassFull -> correctedString(R.string.join_error_class_full) is JoinError.TooManyAttempts -> minutes ?.let { pluralStringResource(R.plurals.join_error_too_many_wait, it, it) } ?: correctedString(R.string.join_error_too_many) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt index 08cc3798..9fe1581e 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt @@ -48,6 +48,16 @@ sealed interface JoinError { */ data object InviteOnly : JoinError + /** + * The code is real and the class already holds as many phones as the class + * code will let in (#199). + * + * Its own case for the reason [InviteOnly] is: the answer is not on this + * screen. A personal code from the bot still gets in, and an admin can make + * room by switching old phones off; «проверьте код» would help with neither. + */ + data object ClassFull : JoinError + /** * Too many failed attempts from this address; [minutes] is how long the * throttle says to wait, rounded up, or null when it would not say. @@ -84,6 +94,7 @@ sealed interface JoinError { /** What the repository answered, as something the screen can word. */ fun of(failure: Throwable): JoinError = when (val classified = JoinFailure.of(failure)) { JoinFailure.InviteOnly -> InviteOnly + JoinFailure.ClassFull -> ClassFull JoinFailure.UnknownCode -> UnknownCode is JoinFailure.TooManyAttempts -> TooManyAttempts( // Rounded up, and never to zero: «подождите 0 минут» is an diff --git a/android/app/src/main/res/values-en/strings.xml b/android/app/src/main/res/values-en/strings.xml index 6b2f6139..3ca03c0d 100644 --- a/android/app/src/main/res/values-en/strings.xml +++ b/android/app/src/main/res/values-en/strings.xml @@ -62,12 +62,13 @@ The phone keeps an access key and copies of the timetable and the diary, so the <string name="join_error_generic">Could not join. Check the code and your network connection.</string> <string name="join_error_unknown_code">No such code. Check it with whoever gave it to you.</string> <!-- - The bot's button label stays in Russian here and in strings_admin.xml, - and it is the only Cyrillic in values-en/ on purpose: the bot has no + The bot's button labels stay in Russian here and in strings_admin.xml, + and they are the only Cyrillic in values-en/ on purpose: the bot has no English interface, so a translated label would name a button that does not exist on the screen the reader is being sent to. --> <string name="join_error_invite_only">This class admits phones by personal invite only. Take your own code from the bot: menu → “📱 Подключить телефон”.</string> + <string name="join_error_class_full">Too many phones are connected to this class for its code to admit another. Take your own code from the bot: menu → “📱 Подключить телефон” — or ask the class admin to switch old phones off under “⚙️ Класс” → “📱 Устройства”.</string> <string name="join_error_too_many">Too many attempts. Wait a little and try again.</string> <plurals name="join_error_too_many_wait"> <item quantity="one">Too many attempts. Try again in %1$d minute.</item> diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 58d71c0b..470511c3 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -54,6 +54,7 @@ <string name="join_error_generic">Не удалось подключиться. Проверьте код и подключение к сети.</string> <string name="join_error_unknown_code">Такого кода нет. Проверьте его у того, кто его дал.</string> <string name="join_error_invite_only">Этот класс подключает телефоны только по личному приглашению. Возьмите личный код в боте: меню → «📱 Подключить телефон».</string> + <string name="join_error_class_full">К классу подключено столько телефонов, что код класса больше не пускает новые. Возьмите личный код в боте: меню → «📱 Подключить телефон» — или попросите администратора класса отключить старые телефоны в «⚙️ Класс» → «📱 Устройства».</string> <string name="join_error_too_many">Слишком много попыток. Подождите и попробуйте снова.</string> <plurals name="join_error_too_many_wait"> <item quantity="one">Слишком много попыток. Попробуйте через %1$d минуту.</item> diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt index 32e576f9..fd09fad7 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt @@ -25,6 +25,12 @@ class JoinErrorTest { assertEquals(JoinError.InviteOnly, JoinError.of(JoinFailure.InviteOnly)) } + /** #199: the code is right, so the screen must not say to check it. */ + @Test + fun `a full class is not a wrong code`() { + assertEquals(JoinError.ClassFull, JoinError.of(JoinFailure.ClassFull)) + } + @Test fun `an unknown code still is one`() { assertEquals(JoinError.UnknownCode, JoinError.of(JoinFailure.UnknownCode)) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt index 07dc4823..53f81c62 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt @@ -47,6 +47,20 @@ class JoinErrorTextTest { compose.onNodeWithText("📱 Подключить телефон", substring = true).assertIsDisplayed() } + /** + * #199: both ways in that are left, by the bot's own button names — a + * personal code, which the bound does not count, and an admin making room. + */ + @Test + fun `a full class points at a personal code and at the admin's device list`() { + show(JoinError.ClassFull) + + compose.onNodeWithText("код класса больше не пускает", substring = true).assertIsDisplayed() + compose.onNodeWithText("«📱 Подключить телефон»", substring = true).assertIsDisplayed() + compose.onNodeWithText("«⚙️ Класс» → «📱 Устройства»", substring = true).assertIsDisplayed() + compose.onNodeWithText("Проверьте", substring = true).assertDoesNotExist() + } + @Test fun `an unknown code is the one that sends them back to check it`() { show(JoinError.UnknownCode) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt index eed4369f..d6dbaa40 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt @@ -38,6 +38,17 @@ sealed class JoinFailure(message: String, cause: Throwable? = null) : /** `404`: no class and no live invite answers to this code. */ data object UnknownCode : JoinFailure("No class or invite answers to this code") + /** + * `409`: a real class code for a class that already holds as many phones + * as the class code will let in (#199). + * + * Its own case for the reason [InviteOnly] is: the code is right, so + * «проверьте код» is the wrong advice, and the ways in that are left — a + * personal code from the bot, or an admin switching old phones off — are + * not on this screen. + */ + data object ClassFull : JoinFailure("This class holds as many phones as its code admits") + /** * `429`: the throttle has stopped counting and started refusing. * @@ -84,14 +95,15 @@ sealed class JoinFailure(message: String, cause: Throwable? = null) : /** * The rule, over a status alone. * - * None of the three named codes needs the server's `detail` to be read: - * `POST /join` raises exactly one `403`, one `404` and one `429`, so - * the status is the whole answer, and a message we would have to match - * on is a Russian sentence somebody will reword. + * None of the four named codes needs the server's `detail` to be read: + * `POST /join` raises exactly one `403`, one `404`, one `409` and one + * `429`, so the status is the whole answer, and a message we would have + * to match on is a Russian sentence somebody will reword. */ fun ofStatus(code: Int, reason: Throwable? = null): JoinFailure = when (code) { 403 -> InviteOnly 404 -> UnknownCode + 409 -> ClassFull 429 -> TooManyAttempts(retryAfterSeconds = retryAfterOf(reason)) else -> Rejected(code = code, reason = reason) } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailureTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailureTest.kt index 7f11af7b..e89e41b2 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailureTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailureTest.kt @@ -12,8 +12,11 @@ import retrofit2.HttpException import retrofit2.Response /** - * The three refusals `POST /api/v1/join` can give to a code that was typed in - * correctly, and why none of them may be the same sentence as another. + * The refusals `POST /api/v1/join` can give to a code that was typed in + * correctly, and why none of them may be the same sentence as another. The + * fourth, a `409` for a class already holding as many phones as its code + * admits (#199), is the [InviteOnly][JoinFailure.InviteOnly] shape again: a + * right code whose way forward is in the bot. * * A `404` means no class answers to this code, and the thing to do about it is * to check the code with whoever handed it out. A `403` means the code names a @@ -43,6 +46,20 @@ class JoinFailureTest { assertEquals(JoinFailure.UnknownCode, failure) } + /** + * #199: the code is right and the class is full. Left as a [JoinFailure.Rejected] + * it reached the screen as «Не удалось подключиться: HTTP 409 error» — + * English, and silent about the two ways in that are left. + */ + @Test + fun `a 409 is a full class, not a wrong code or a server fault`() { + val failure = JoinFailure.of( + httpError(409, """{"detail":"К классу подключено слишком много телефонов"}"""), + ) + + assertEquals(JoinFailure.ClassFull, failure) + } + @Test fun `a 429 carries the wait the server put a number on`() { val failure = JoinFailure.of( diff --git a/docs/api.md b/docs/api.md index db9e59d4..470f815a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -60,6 +60,15 @@ Failed joins are rate-limited per client address (thirty per fifteen minutes, counted in the database so the limit survives serverless cold starts); a blocked client gets `429` with `Retry-After`. +Successful joins are not counted, so it is the class that bounds them: once a class holds +300 live devices — a revoked one is a tombstone and does not count — its class code is +answered with `409` and a Russian sentence in `detail`, and mints nothing. That `409` is not +a failed attempt for the limiter either, for the reason the invite-only `403` below is not. +A personal code from the bot still joins a full class: it is minted one phone at a time for +a member the bot knows, and it is the way in left to a family if somebody has used the +class code to fill the class. The number is generous on purpose — `MAX_DEVICES_PER_CLASS` +in `api/public.py` says how it was reached — and an admin makes room by revoking old phones. + ### Who lets a phone in: the class code or the bot A class has a join mode — `join_mode`, either `open` or `invite` — and it decides what the @@ -99,6 +108,7 @@ to the log. | `401` | Missing, malformed, unknown or revoked token — **the client must drop its session**, not merely report it | | `403` | The device is not linked, or its account lacks the role (`detail` says which). On `/join` it is the one refusal below that is not about the code being wrong: the class takes personal invites only | | `404` | Join code, class, homework, task or event does not exist - or is not this class's | +| `409` | On `/join`: the class already holds as many live phones as its class code admits. The code is right; a personal code from the bot still joins | | `422` | Parameter out of range or body invalid | | `429` | Too many failed join attempts | diff --git a/server/app/api/public.py b/server/app/api/public.py index ba0778df..af4db9e0 100644 --- a/server/app/api/public.py +++ b/server/app/api/public.py @@ -16,7 +16,7 @@ from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response, status -from sqlalchemy import select, text +from sqlalchemy import func, select, text from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession @@ -112,6 +112,20 @@ # joining from one school NAT is never blocked by each other's successes. join_limiter = JoinThrottle(limit=30, window=900.0) +# The most live phones the class code will put into one class (#199). The +# throttle counts only failures, so without this a caller holding a real code +# could mint read tokens for ever, each one alive until 180 days of silence. +# +# Generous on purpose, because the refusal lands on a real family: thirty-odd +# pupils, each with a phone of their own and up to two parents', and the +# teachers who read the class, come to about 120 — and a row outlives the phone +# it was minted for, since a reinstall, a cleared app or a new phone each join +# again and leave the old token live until `cron.DEVICE_TOKEN_TTL` prunes it. +# Doubling for that residue gives ~250; 300 is that with room to spare. A class +# that really does reach it has an admin who can switch old phones off, and a +# personal code from the bot is not counted against it at all. +MAX_DEVICES_PER_CLASS = 300 + def _forwarded_list(request: Request, name: str) -> str: """Every line of a repeated list header, joined back into the one list. @@ -331,6 +345,17 @@ def _drift_detail(revision: str | None) -> str: return "Схема базы и схема кода расходятся." +async def _live_devices(session: AsyncSession, class_id: int) -> int: + """Phones that can still read the class. A revoked row is a tombstone kept + so its token goes on failing, and holds no phone.""" + count = await session.scalar( + select(func.count()) + .select_from(DeviceToken) + .where(DeviceToken.class_id == class_id, DeviceToken.revoked.is_(False)) + ) + return count or 0 + + @router.post("/join", response_model=JoinResponse) async def join( request: Request, @@ -391,6 +416,24 @@ async def join( # The one answer that stays counted: the attempt `admit` wrote is it. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown join code") + if invite is None and await _live_devices(session, school_class.id) >= MAX_DEVICES_PER_CLASS: + # Only the class code is bounded. A personal code is minted by the bot + # for a member it knows, one phone at a time, with a name in the + # journal: it is not what the bound is against, and it is the way in + # left to a family when somebody has filled the class through the + # shared code. Not counted against the throttle, for the reason the + # 403 above is not — a real code, not a guess. A burst of joins that + # all counted before any committed can pass the bound by its own size, + # and no further: after it, every join counts past it. + await join_limiter.forgive(session, attempt) + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=( + "К классу подключено слишком много телефонов. Возьмите личный код в боте " + "(«📱 Подключить телефон») или попросите администратора отключить старые телефоны" + ), + ) + # Spent before the token is minted, not after: the update is what makes # "one code, one phone" true against a second request that read the same # live row, and a token minted first would be a token already handed out diff --git a/server/tests/test_join_device_cap.py b/server/tests/test_join_device_cap.py new file mode 100644 index 00000000..8a04f66a --- /dev/null +++ b/server/tests/test_join_device_cap.py @@ -0,0 +1,134 @@ +"""#199: how many phones the class code can let into one class. + +Every ``POST /join`` mints a row, and the throttle counts only failures — so a +caller who holds a real class code could mint tokens for ever, each one a live +read token for the class until 180 days of silence prune it. The class code now +stops at ``MAX_DEVICES_PER_CLASS`` live devices and answers ``409`` with a +Russian sentence. + +Three things are held here beside the bound itself. The ``409`` is not a failed +attempt for the throttle, for the reason the invite-only ``403`` is not: this +caller found a real code, and counting it would lock a whole school NAT out of +every other class. A revoked device is a tombstone, not a phone, and does not +count. And a personal code from the bot still joins a full class: it is minted +only for a member the bot knows, one phone at a time, with a name in the +journal — it is not what the bound is against, and it is the way in that is +left when somebody has filled the class through the shared code. +""" + +from __future__ import annotations + +import httpx +import pytest +from httpx import ASGITransport +from sqlalchemy import func, select + +from app.api.public import MAX_DEVICES_PER_CLASS, join_limiter +from app.fsm_storage import FsmRecord # noqa: F401 - registers fsm_states before create_all +from app.main import app +from app.models import DeviceToken, JoinAttempt, SchoolClass +from app.security import hash_token +from app.services import device_invites + +FULL_DETAIL = ( + "К классу подключено слишком много телефонов. Возьмите личный код в боте " + "(«📱 Подключить телефон») или попросите администратора отключить старые телефоны" +) + + +@pytest.fixture +async def client(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac + + +async def _join(client, code: str) -> httpx.Response: + return await client.post("/api/v1/join", json={"code": code, "device_name": "pytest"}) + + +async def _fill(session, klass: SchoolClass, count: int, *, revoked: bool = False) -> None: + """``count`` devices already in ``klass``, as earlier joins would have left them.""" + session.add_all( + DeviceToken( + token_hash=hash_token(f"{klass.id}-{revoked}-{n}"), + class_id=klass.id, + device_name=f"phone {n}", + revoked=revoked, + ) + for n in range(count) + ) + await session.commit() + + +async def _live(session, klass: SchoolClass) -> int: + return await session.scalar( + select(func.count()) + .select_from(DeviceToken) + .where(DeviceToken.class_id == klass.id, DeviceToken.revoked.is_(False)) + ) + + +async def _attempts(session) -> int: + return await session.scalar(select(func.count()).select_from(JoinAttempt)) + + +async def test_the_class_code_joins_up_to_the_bound_and_no_further( + client, session, school_class +): + await _fill(session, school_class, MAX_DEVICES_PER_CLASS - 1) + + last = await _join(client, "TEST42") + assert last.status_code == 200, last.text + assert await _live(session, school_class) == MAX_DEVICES_PER_CLASS + + refused = await _join(client, "TEST42") + assert refused.status_code == 409 + assert refused.json()["detail"] == FULL_DETAIL + # Nothing minted: the refusal is the whole point. + assert await _live(session, school_class) == MAX_DEVICES_PER_CLASS + + +async def test_a_full_class_is_not_counted_against_the_caller(client, session, school_class): + """Past the throttle's own limit, and still a 409 rather than a 429 — and + the school next door, behind the same address, still joins its own class.""" + await _fill(session, school_class, MAX_DEVICES_PER_CLASS) + other = SchoolClass(name="9Б", join_code="OTHER42") + session.add(other) + await session.commit() + + for _ in range(join_limiter.limit + 5): + assert (await _join(client, "TEST42")).status_code == 409 + + assert await _attempts(session) == 0 + assert (await _join(client, "OTHER42")).status_code == 200 + + +async def test_revoked_devices_are_not_phones(client, session, school_class): + """A revoked row is kept as a tombstone so its token keeps failing; it holds + no phone, so switching old phones off is how an admin makes room.""" + await _fill(session, school_class, MAX_DEVICES_PER_CLASS, revoked=True) + await _fill(session, school_class, MAX_DEVICES_PER_CLASS - 1) + + assert (await _join(client, "TEST42")).status_code == 200 + + +async def test_the_bound_is_per_class(client, session, school_class): + other = SchoolClass(name="9Б", join_code="OTHER42") + session.add(other) + await session.commit() + await _fill(session, other, MAX_DEVICES_PER_CLASS) + + assert (await _join(client, "TEST42")).status_code == 200 + assert (await _join(client, "OTHER42")).status_code == 409 + + +async def test_a_personal_code_still_joins_a_full_class(client, session, school_class): + """The way in that is left when the class code has been used to fill it.""" + await _fill(session, school_class, MAX_DEVICES_PER_CLASS) + code = await device_invites.mint(session, telegram_id=4242, class_id=school_class.id) + + response = await _join(client, code) + + assert response.status_code == 200, response.text + assert await _live(session, school_class) == MAX_DEVICES_PER_CLASS + 1 From 8b023163e8f512ac0aed37290e67e770118f186d Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 15:02:17 +0300 Subject: [PATCH 19/43] Serve the interactive API docs and their schema locally, and not on Vercel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FastAPI mounts /docs, /redoc and /openapi.json by default, and app/main.py left them on everywhere. The code is public, so the schema reveals little, but it is surface nobody on the production server needs: the phone is written against docs/api.md, not against a schema it fetches, and nothing in the repository — app, tests or documents — asks for any of the three. The construction now passes `None` for all three when `Settings.behind_vercel` — the platform's own `VERCEL`, the same signal `get_settings` refuses to start on — and the usual paths otherwise, so `uvicorn --reload` on a laptop keeps them. tests/test_api_docs.py asks both halves. Locally the three paths answer 200. For Vercel, a fresh interpreter imports the real `app.main` with `VERCEL` and every setting a deployment must have, and asks the three paths and `/api/v1/health` over ASGI: the health check answers 200, so the app is alive, and the three answer 404. With the switch taken out of the construction the Vercel half failed on 200s, and the local half passed both ways, as it should. A subprocess rather than a reload, because `app` is built once at import and every later test in the worker holds it. Not covered: `GET /` still answers `{"docs": "/docs"}`, which on Vercel now names a 404; it was left because this change was asked to stay inside the FastAPI construction. A compose or VPS deployment keeps the docs, as it keeps every other local default — `VERCEL` is the only production signal the server trusts. Generating the schema warns about a duplicate operation id for the cron tick (registered for GET and POST); that predates this change. Closes #200 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/main.py | 10 +++++ server/tests/test_api_docs.py | 76 +++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 server/tests/test_api_docs.py diff --git a/server/app/main.py b/server/app/main.py index 2d04349b..eaf8c388 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -113,11 +113,21 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: await close_container() +# The interactive docs and the schema they are drawn from, locally and never on +# the production server (#200): nobody there needs them — the app is written +# against docs/api.md, not against a schema it fetches — and each is surface. +# The signal is the one `get_settings` refuses to start on, Vercel's own +# `VERCEL`, never a guess at "this looks like production". A compose or VPS +# deployment keeps them, as it keeps every other local default. +_api_docs = not get_settings().behind_vercel app = FastAPI( title="Lessons", version="0.1.0", description="School diary API and Telegram admin bot", lifespan=lifespan, + openapi_url="/openapi.json" if _api_docs else None, + docs_url="/docs" if _api_docs else None, + redoc_url="/redoc" if _api_docs else None, ) # At module scope rather than in the lifespan, because `setup_dishka` installs diff --git a/server/tests/test_api_docs.py b/server/tests/test_api_docs.py new file mode 100644 index 00000000..823e08da --- /dev/null +++ b/server/tests/test_api_docs.py @@ -0,0 +1,76 @@ +"""#200: FastAPI's interactive docs and schema, locally and not on Vercel. + +The production half is asked of the real module in a fresh interpreter, because +``app.main.app`` is built once, at import, from the settings of the process that +imported it — and this suite's process is deliberately not a Vercel one. +Reloading the module here instead would rebuild the app every later test in +the worker holds, under settings none of them expect. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +import httpx +from httpx import ASGITransport + +from app.main import app + +SERVER = Path(__file__).resolve().parents[1] +DOC_PATHS = ("/openapi.json", "/docs", "/redoc") + + +async def test_a_local_server_serves_its_docs(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + for path in DOC_PATHS: + assert (await client.get(path)).status_code == 200, path + + +#: What a Vercel deployment is started with: everything `get_settings` refuses +#: to start without, and the platform's own `VERCEL`. Nothing connects — the +#: engine is lazy and ``/api/v1/health`` opens no connection by design. +_VERCEL_ENV = { + "VERCEL": "1", + "DATABASE_URL": "postgresql+asyncpg://user:secret@db.invalid:5432/lessons", + "BOT_TOKEN": "123456:not-a-real-token", + "WEBHOOK_SECRET": "not-a-real-secret", + "RUN_BOT": "false", + "OWNER_IDS": "1000", + "TIMEZONE": "Europe/Moscow", +} + +_ASK_AS_VERCEL = """ +import asyncio, json +import httpx +from app.main import app + +async def ask(): + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + paths = {paths!r} + ("/api/v1/health",) + return {{path: (await client.get(path)).status_code for path in paths}} + +print(json.dumps(asyncio.run(ask()))) +""" + + +def test_a_vercel_deployment_serves_no_docs_and_still_answers(): + result = subprocess.run( + [sys.executable, "-c", _ASK_AS_VERCEL.format(paths=DOC_PATHS)], + cwd=str(SERVER), + env={**os.environ, **_VERCEL_ENV}, + capture_output=True, + text=True, + timeout=120, + ) + + assert result.returncode == 0, result.stderr + statuses = json.loads(result.stdout.strip().splitlines()[-1]) + # The control first: a 404 from an app that answers nothing proves nothing. + assert statuses.pop("/api/v1/health") == 200, result.stdout + assert statuses == dict.fromkeys(DOC_PATHS, 404), result.stdout From 64225cdb0d9d8eed035cd9f25e362f11fff25b77 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 15:17:29 +0300 Subject: [PATCH 20/43] Seal the class and diary bearers in the preferences file with a key the Android Keystore holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both bearers sat in DataStore as plain strings: the class token, often a write token since personal connect codes exist, and the diary session, which opens a child's marks. Backup already left the file out; a rooted phone, or anything that got a copy of the app's data, read them as text. The owner decided on 27 September to encrypt both at rest with an AndroidKeyStore AES-GCM key and no new dependency, re-encrypting what an older install wrote, and accepted that a lost key means joining again. What is stored now is `gcm1:` and the base64 of an AES-256-GCM seal (IV length, IV, ciphertext and tag). The colon is what tells a sealed value from a bearer: every token the server issues is token_urlsafe, whose alphabet has none, so a value without one is a bearer an older install wrote and is read as it stands, and a colon behind a prefix this build does not know opens to nothing rather than being sent. - TokenVault seals on the way into the file and opens on the way out. Opening is remembered for the life of the process, failures included: one Keystore call per sealed value per process, never one per read, and a key that is gone is asked once rather than on every emission. - LessonsPreferences reads every token through `opened`, which opens them on the IO dispatcher before anything maps the emission, so the binder call never runs on the collecting thread. The request credentials are opened there, when CredentialsSnapshot is refreshed; the interceptors still read a field (#203). Writes run on IO too, because DataStore runs the transform in the caller's context and a join seals inside it. Only the new token is sealed: the others are carried over as stored. - TokenSealing is a DataStore migration: it seals whatever an older install left bare before the first read of a process is served, asks first whether anything is bare (idempotent by construction), rewrites the membership list record by record on the JSON so a newer build's fields and an undecodable record survive, and never throws, because an exception out of a migration is an exception out of every read. - A token that will not open (another phone, a wiped Keystore, damage) reads as no token everywhere at once: the membership drops out of `session`, `sessions`, the shell mode and the credentials, and the diary session reads the way a bare 401 leaves it, target kept. The phone lands on the join screen or the diary's form, as one that never had the token would, and a join replaces the dead record by class. - A Keystore that cannot seal at all leaves the bearer as it arrived, the one plaintext this writes, rather than a phone that can never join; the migration asks again on the next start. Tests: the cipher's framing runs real AES-GCM on the JVM with the key held in memory (MemoryKeys), so a tag that does not verify is a real failure. SealedTokensTest covers the file never holding a bearer, the round trip through every reader, a join leaving the other classes' sealed tokens untouched, the migration (sealing, idempotence, the flat keys of a pre-list install, unreadable records kept), a Keystore that cannot seal, a lost key landing on the diary's form or the first screen and a re-join recovering, one open per value however often the file is read, and a later build's format never sent. Each of six mutations of the fix fails at least one of them. The tests that build LessonsPreferences now hand it a vault, and MemoryStore moved to a support file they share. The privacy policy said the keys sit on the phone unencrypted, in three places in each language; it says what is sealed now, what is not, the fallback, and that the encryption has not been checked on a device. Edition 2, effective 27 September. Not covered: AndroidKeystoreKeys is written, never run on a device — nothing here can execute the AndroidKeyStore, so the key generation, the IV the Keystore picks and the deletion of an unrecoverable entry are what its documentation describes and nothing more. The GitHub token in its own preferences file is still plaintext; #201 is about the two bearers. A record whose token will not open stays in the file, invisible, until a join of that class or a sign-out replaces it. Closes #201 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../data/datastore/AndroidKeystoreKeys.kt | 63 ++++ .../core/data/datastore/LessonsPreferences.kt | 105 ++++-- .../core/data/datastore/Memberships.kt | 70 +++- .../core/data/datastore/TokenSealing.kt | 77 +++++ .../lessons/core/data/datastore/TokenVault.kt | 181 +++++++++++ .../data/datastore/RequestCredentialsTest.kt | 48 +-- .../core/data/datastore/SealedTokensTest.kt | 300 ++++++++++++++++++ .../core/data/datastore/StoreTestSupport.kt | 83 +++++ .../data/repository/ServerStatusReadTest.kt | 3 +- .../core/data/repository/ShellModeTest.kt | 14 +- docs/legal/legal.json | 4 +- docs/legal/privacy.en.md | 6 +- docs/legal/privacy.ru.md | 9 +- 13 files changed, 882 insertions(+), 81 deletions(-) create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenSealing.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/SealedTokensTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/StoreTestSupport.kt diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt new file mode 100644 index 00000000..2cd5bd80 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt @@ -0,0 +1,63 @@ +package com.lumenpearson.lessons.core.data.datastore + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.KeyStore +import java.security.UnrecoverableKeyException +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +/** + * The bearers' key, kept by the AndroidKeyStore under [alias] (#201). + * + * **Written, never run on a device.** Nothing in this repository can execute + * it: the unit tests run on a JVM with no AndroidKeyStore provider, and there + * is no emulator in CI. Every decision about what a missing or broken key + * *costs* lives in [TokenVault] and is tested there with a key held in memory; + * what is left here is the platform's API, used the way its documentation + * shows. + * + * AES-256 for GCM, nothing else asked of it: + * + * * **No user authentication.** The widget and the sync worker open the class + * token with the screen off and nobody holding the phone; a key that needed + * a recent unlock would stop every background sync. + * * **No StrongBox.** It is missing on most of the phones this app runs on, + * and where it exists it is slow enough to be felt on a cold start; the + * ordinary Keystore already keeps the key out of the app's process. + * + * A key that cannot be read back is deleted rather than kept. That is only + * `UnrecoverableKeyException` — the entry is there and will never work again — + * and what it costs is what a lost key costs anyway: every sealed token opens + * to nothing and the phone signs in again, and the next seal makes a key that + * does work. A failure of any other kind is left alone and thrown, because it + * may be the Keystore having a bad moment rather than the key being gone. + */ +internal class AndroidKeystoreKeys(private val alias: String) : AesGcmTokenCipher.Keys { + + override fun existing(): SecretKey? { + val store = KeyStore.getInstance(PROVIDER).apply { load(null) } + return try { + store.getKey(alias, null) as? SecretKey + } catch (_: UnrecoverableKeyException) { + store.deleteEntry(alias) + null + } + } + + override fun create(): SecretKey { + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER) + generator.init( + KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build(), + ) + return generator.generateKey() + } + + private companion object { + const val PROVIDER = "AndroidKeyStore" + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt index 460d0e0e..0af1eb95 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt @@ -42,12 +42,16 @@ import com.lumenpearson.lessons.core.model.ThemeMode import com.lumenpearson.lessons.core.model.TodayLayout import com.lumenpearson.lessons.core.model.WeekStart import java.io.IOException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext @@ -65,6 +69,9 @@ private val Context.lessonsDataStore: DataStore<Preferences> by preferencesDataS // the install. Replacing the file loses what was in it, which is what a // corrupt file has already done. corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() }, + // Seals whatever bearer an older install left bare, before the first read + // of the process is served; see [TokenSealing]. + produceMigrations = { listOf(TokenSealing(TokenVault.platform)) }, ) /** @@ -74,14 +81,23 @@ private val Context.lessonsDataStore: DataStore<Preferences> by preferencesDataS * screens, they are both tiny, and a single file means a single fsync and a * single flow to observe. * + * The two bearers in it are sealed ([TokenVault], #201): every write seals the + * one it stores, every read that hands out a [Session] or a [DiarySession] + * opens them, and nothing else here ever sees one. + * * @param dataStore the app's one file on a phone. A test hands in a store of * its own, which is the only reason this is not built from the context here. + * @param vault what seals and opens the bearers — the phone's Keystore, or a + * key held in memory in a test. + * @param io where the Keystore is asked; see [opened]. */ internal class LessonsPreferences( private val dataStore: DataStore<Preferences>, + private val vault: TokenVault, + private val io: CoroutineDispatcher = Dispatchers.IO, ) : DiarySessionStore, ShellModeSource, SettingsStore { - constructor(context: Context) : this(context.applicationContext.lessonsDataStore) + constructor(context: Context) : this(context.applicationContext.lessonsDataStore, TokenVault.platform) /** * A corrupt or unreadable file must not take the app down: it degrades to @@ -92,13 +108,28 @@ internal class LessonsPreferences( if (cause is IOException) emit(emptyPreferences()) else throw cause } + /** + * The same emissions with every bearer in them already opened, on [io]. + * + * Everything that reads a token reads through this, and only that: opening + * one is a Keystore call, a binder transaction that would otherwise run on + * whatever thread collects — the main one, for a screen. Here it runs once + * per sealed value per process (the vault remembers), before anything maps + * the emission, and the mappings downstream find it remembered. The settings + * and the rest of the file hold no token and stay on [preferences]. + */ + private val opened: Flow<Preferences> = preferences + .onEach { it.openEveryToken(vault) } + .flowOn(io) + /** * What the OkHttp interceptors read — the address and both bearers, held in * memory; see [CredentialsSnapshot]. Every [write] brings it up to date * before returning, and [followCredentials] keeps it there for writes made - * through another instance. + * through another instance. Its bearers are opened here, when it is + * refreshed, and never per request. */ - val credentials = CredentialsSnapshot { preferences.first().requestCredentials() } + val credentials = CredentialsSnapshot { opened.first().requestCredentials() } /** Runs for as long as the file can emit; the container launches it once. */ suspend fun followCredentials() = credentials.follow(preferences) @@ -112,23 +143,29 @@ internal class LessonsPreferences( * edit has landed: a caller cancelled between the two would leave the next * request signed for the class it had just left, for as long as the * follower took to hear about it. + * + * On [io], because DataStore runs the transform in the caller's context and + * two of them ask the Keystore: sealing the bearer a join or a sign-in + * stores, and the mode [settleColdStart] reads. */ private suspend fun write(transform: suspend (MutablePreferences) -> Unit) { - dataStore.edit(transform) - withContext(NonCancellable) { credentials.refresh() } + withContext(io) { + dataStore.edit(transform) + withContext(NonCancellable) { credentials.refresh() } + } } /** The class being shown, or `null` when this device is in none. */ - val session: Flow<Session?> = preferences.map { it.activeMembership() }.distinctUntilChanged() + val session: Flow<Session?> = opened.map { it.openActiveMembership(vault) }.distinctUntilChanged() /** Every class this device has joined, in the order they were joined. */ - val sessions: Flow<List<Session>> = preferences.map { it.memberships() }.distinctUntilChanged() + val sessions: Flow<List<Session>> = opened.map { it.openMemberships(vault) }.distinctUntilChanged() override val settings: Flow<AppSettings> = preferences.map { it.toSettings() }.distinctUntilChanged() - suspend fun currentSession(): Session? = preferences.first().activeMembership() + suspend fun currentSession(): Session? = opened.first().openActiveMembership(vault) - suspend fun currentSessions(): List<Session> = preferences.first().memberships() + suspend fun currentSessions(): List<Session> = opened.first().openMemberships(vault) override suspend fun currentSettings(): AppSettings = preferences.first().toSettings() @@ -139,10 +176,14 @@ internal class LessonsPreferences( * rather than appending: the join code is how a pupil recovers from a * revoked device, and doing that must not leave the same class listed * twice, nor move it to the bottom of a list the user has got used to. + * + * Only the new token is sealed. The others are carried over as they are + * stored, so a join never re-seals — or asks the Keystore about — a class + * it is not about. */ suspend fun addSession(value: Session) { write { prefs -> - prefs.writeMemberships(prefs.memberships().withMembership(value)) + prefs.writeMemberships(prefs.memberships().withMembership(value.copy(token = vault.seal(value.token)))) prefs.activate(value.classId) } } @@ -234,13 +275,13 @@ internal class LessonsPreferences( // is called. override val diarySession: Flow<DiarySession?> = - preferences.map { it.toDiarySession() }.distinctUntilChanged() + opened.map { it.openDiarySession(vault) }.distinctUntilChanged() override suspend fun currentDiarySession(): DiarySession? = - preferences.first().toDiarySession() + opened.first().openDiarySession(vault) override suspend fun writeDiarySession(value: DiarySession) { - write { it.putDiarySession(value) } + write { it.putDiarySession(value.copy(token = vault.seal(value.token))) } } /** A bare `401`; see [dropDiaryToken]. */ @@ -275,12 +316,12 @@ internal class LessonsPreferences( // the diary are both in it, so the mode never has to be assembled from two // flows that can be caught between a write and its echo. - override val state: Flow<ShellState> = preferences.map { it.shellState() }.distinctUntilChanged() + override val state: Flow<ShellState> = opened.map { it.shellState(vault) }.distinctUntilChanged() - override suspend fun current(): ShellState = preferences.first().shellState() + override suspend fun current(): ShellState = opened.first().shellState(vault) - override val syncArming: Flow<SyncArming> = preferences - .map { prefs -> syncArmingFor(prefs.shellState().mode, prefs.toSettings().syncIntervalMinutes) } + override val syncArming: Flow<SyncArming> = opened + .map { prefs -> syncArmingFor(prefs.shellState(vault).mode, prefs.toSettings().syncIntervalMinutes) } .distinctUntilChanged() override suspend fun hold() { @@ -295,7 +336,7 @@ internal class LessonsPreferences( // Read and written in the one transaction, so a join landing between // a separate read and write cannot have its hold taken away. write { prefs -> - if (prefs.shellState().mode == ShellMode.NONE) prefs.remove(ShellKeys.ONBOARDING_HELD) + if (prefs.shellState(vault).mode == ShellMode.NONE) prefs.remove(ShellKeys.ONBOARDING_HELD) } return current() } @@ -492,11 +533,14 @@ internal class LessonsPreferences( * The two bearers stay two fields: one can be present while the other is * absent, and an interceptor that took the wrong one would send a class * token to a family's diary. + * + * Both opened: what the file holds is sealed, and a sealed value sent as a + * bearer is a `401` that signs the phone out of a class it is still in. */ private fun Preferences.requestCredentials(): RequestCredentials = RequestCredentials( baseUrl = toSettings().baseUrl, - classToken = activeMembership()?.token, - diaryToken = toDiarySession()?.token, + classToken = openActiveMembership(vault)?.token, + diaryToken = openDiarySession(vault)?.token, ) /** @@ -705,9 +749,15 @@ internal object ShellKeys { val ONBOARDING_HELD = booleanPreferencesKey("onboarding_held") } -/** [shellModeOf] and the hold, from one emission; see [ShellModeSource]. */ -internal fun Preferences.shellState(): ShellState = ShellState( - mode = shellModeOf(activeMembership(), toDiaryTarget()), +/** + * [shellModeOf] and the hold, from one emission; see [ShellModeSource]. + * + * The class is the one whose token opens: a phone whose key is gone holds + * sealed tokens it cannot use, and is in no class — so it opens on the join + * screen, or on the diary's, exactly as a phone that never had the token would. + */ +internal fun Preferences.shellState(vault: TokenVault): ShellState = ShellState( + mode = shellModeOf(openActiveMembership(vault), toDiaryTarget()), held = this[ShellKeys.ONBOARDING_HELD] ?: false, ) @@ -747,7 +797,11 @@ internal fun Preferences.toDiaryTarget(): DiaryTarget? { return DiaryTarget.petersburg(login) } -/** Our bearer, the login and the target, in one transaction. */ +/** + * Our bearer, the login and the target, in one transaction. The bearer is + * written as it is handed in, so the caller seals it first — see + * `LessonsPreferences.writeDiarySession`. + */ internal fun MutablePreferences.putDiarySession(value: DiarySession) { this[DiaryKeys.TOKEN] = value.token this[DiaryKeys.LOGIN] = value.login @@ -783,6 +837,9 @@ internal fun MutablePreferences.dropDiary() { * when its target is one this build cannot read (see [toDiaryTarget]): a bearer * sent for an account the app cannot name would be answered for somebody the * screens cannot say. + * + * The token is the one stored, sealed since #201; [openDiarySession] is the + * one to read for a bearer. */ internal fun Preferences.toDiarySession(): DiarySession? { val token = this[DiaryKeys.TOKEN]?.takeIf { it.isNotBlank() } ?: return null diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt index dd6f99db..614cfba6 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt @@ -9,8 +9,11 @@ import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.Session import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.jsonArray @@ -92,7 +95,10 @@ private val membershipJson = Json { } /** - * Every membership, in the order they were joined. + * Every membership, in the order they were joined — **with each token as it is + * stored**, which since #201 is sealed. This is the view the writes work on, so + * that re-joining one class rewrites nothing about the others' tokens; anything + * that needs a bearer reads [openMemberships] instead. * * Decoded **one record at a time**, which is the whole point of the list being * an array of small objects. Decoding it as a list would make any single @@ -132,12 +138,70 @@ internal fun Preferences.memberships(): List<Session> { * which is the state a half-finished write or a hand-edited file can leave: the * phone is in classes, so it shows one, rather than claiming to be in none. */ -internal fun Preferences.activeMembership(): Session? { - val all = memberships() +internal fun Preferences.activeMembership(): Session? = activeAmong(memberships()) + +/** Which of [all] is on screen, by the rule [activeMembership] describes. */ +private fun Preferences.activeAmong(all: List<Session>): Session? { val active = this[MembershipKeys.ACTIVE_CLASS_ID] return all.firstOrNull { it.classId == active } ?: all.firstOrNull() } +/** + * Every membership whose token this phone can open, with the token as the + * bearer it is. + * + * One that will not open is left out, exactly as a record with no token is: + * its key is gone — restored onto another phone, a wiped Keystore — and the + * only cure is the join code, which is what a phone in no class is shown. It is + * not deleted from the file here; the next write of the list, which that join + * is, replaces it by class. + */ +internal fun Preferences.openMemberships(vault: TokenVault): List<Session> = + memberships().mapNotNull { stored -> vault.open(stored.token)?.let { stored.copy(token = it) } } + +/** + * [activeMembership] among the ones that open, so a class whose token is lost + * is never the one on screen: the next class is, or none. + */ +internal fun Preferences.openActiveMembership(vault: TokenVault): Session? = activeAmong(openMemberships(vault)) + +/** + * The list [raw] with every token still stored bare sealed through [vault], or + * `null` when there is nothing to seal — or nothing readable to seal it in. + * + * Record by record, on the JSON itself rather than through [memberships]: a + * record this build cannot decode, or one carrying fields a newer build wrote, + * is rewritten with its token sealed and everything else exactly as it was. + * Decoding and re-encoding would drop what this build does not know, and the + * migration that calls this runs on every install. + */ +internal fun sealedMembershipList(raw: String, vault: TokenVault): String? { + val array = runCatching { membershipJson.parseToJsonElement(raw).jsonArray }.getOrNull() ?: return null + var changed = false + val sealed = array.map { element -> + val record = element as? JsonObject ?: return@map element + val token = (record["token"] as? JsonPrimitive)?.takeIf { it.isString }?.content + if (token == null || !isBare(token)) return@map element + val stored = vault.seal(token) + if (stored == token) return@map element + changed = true + JsonObject(record + ("token" to JsonPrimitive(stored))) + } + return if (changed) JsonArray(sealed).toString() else null +} + +/** Whether [raw] holds a record whose token is still stored bare; see [sealedMembershipList]. */ +internal fun membershipListHoldsBareToken(raw: String): Boolean { + val array = runCatching { membershipJson.parseToJsonElement(raw).jsonArray }.getOrNull() ?: return false + return array.any { element -> + val token = ((element as? JsonObject)?.get("token") as? JsonPrimitive)?.takeIf { it.isString }?.content + token != null && isBare(token) + } +} + +/** A token written before #201: present, and not sealed. */ +internal fun isBare(token: String?): Boolean = !token.isNullOrBlank() && !TokenVault.isSealed(token) + /** * The one membership the app used to hold, in four flat keys. * diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenSealing.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenSealing.kt new file mode 100644 index 00000000..4d509663 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenSealing.kt @@ -0,0 +1,77 @@ +package com.lumenpearson.lessons.core.data.datastore + +import androidx.datastore.core.DataMigration +import androidx.datastore.preferences.core.MutablePreferences +import androidx.datastore.preferences.core.Preferences +import com.lumenpearson.lessons.core.data.repository.DiarySession + +/** + * Seals the bearers an install wrote before #201, the first time the file is + * opened in a process. + * + * A DataStore migration rather than a step in `LessonsPreferences`, because it + * is DataStore's own answer to «before anything reads this file»: it runs on + * the store's scope, off the main thread, before the first value is served, and + * whatever reads the file afterwards finds the tokens sealed. It asks first + * ([shouldMigrate]), and what it asks is whether any token is still bare — so + * it is idempotent by construction, and on every start after the first it costs + * a look at three keys. + * + * **It never throws.** An exception out of a migration is an exception out of + * every read of the file, and the preferences' read side degrades only an + * `IOException` to defaults; anything else would be a crash at launch, for + * ever. A token the Keystore will not seal stays as it is (see + * [TokenVault.seal]), and the next start asks again. + */ +internal class TokenSealing(private val vault: TokenVault) : DataMigration<Preferences> { + + override suspend fun shouldMigrate(currentData: Preferences): Boolean = + runCatching { currentData.holdsBareToken() }.getOrDefault(false) + + override suspend fun migrate(currentData: Preferences): Preferences = + runCatching { currentData.toMutablePreferences().apply { sealBareTokens(vault) }.toPreferences() } + .getOrDefault(currentData) + + override suspend fun cleanUp() = Unit +} + +/** Whether any bearer in the file is still stored as it arrived. */ +internal fun Preferences.holdsBareToken(): Boolean = + isBare(this[MembershipKeys.TOKEN]) || + isBare(this[DiaryKeys.TOKEN]) || + this[MembershipKeys.SESSIONS]?.let(::membershipListHoldsBareToken) == true + +/** + * Seals every bearer still stored bare, where it stands: the list's records in + * place, the four flat keys an install from before the list holds as they are + * (writing the list is a join's business, not a migration's), and the diary's. + */ +internal fun MutablePreferences.sealBareTokens(vault: TokenVault) { + this[MembershipKeys.TOKEN]?.takeIf(::isBare)?.let { this[MembershipKeys.TOKEN] = vault.seal(it) } + this[DiaryKeys.TOKEN]?.takeIf(::isBare)?.let { this[DiaryKeys.TOKEN] = vault.seal(it) } + this[MembershipKeys.SESSIONS] + ?.let { sealedMembershipList(it, vault) } + ?.let { this[MembershipKeys.SESSIONS] = it } +} + +/** + * [toDiarySession] with its bearer opened, or `null` when it will not open — + * which reads the way a bare `401` leaves the store: the target is still there, + * so the family is asked to sign in to the same diary again. + */ +internal fun Preferences.openDiarySession(vault: TokenVault): DiarySession? = + toDiarySession()?.let { stored -> vault.open(stored.token)?.let { stored.copy(token = it) } } + +/** + * Opens every token in one emission of the file, so that whatever maps it next + * finds each one already remembered. + * + * This is where the Keystore is actually asked, and it is called only from a + * flow running on the IO dispatcher — `LessonsPreferences.opened` — so that the + * binder call is never made on the thread that collects, which for the screens + * is the main one. + */ +internal fun Preferences.openEveryToken(vault: TokenVault) { + openMemberships(vault) + this[DiaryKeys.TOKEN]?.let(vault::open) +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt new file mode 100644 index 00000000..d1ea1b75 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt @@ -0,0 +1,181 @@ +package com.lumenpearson.lessons.core.data.datastore + +import java.security.GeneralSecurityException +import java.util.Base64 +import java.util.concurrent.ConcurrentHashMap +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * The two bearers as the preferences file holds them: sealed with a key that + * never leaves the phone (#201). + * + * The class token and the diary session are each a working credential — the + * first is often a write token since personal connect codes exist, the second + * opens a child's marks — and the file they live in is plain protobuf that a + * rooted phone, or anything that gets a copy of the app's data, reads as text. + * Backup already leaves the file out; this is the half backup cannot do. + * + * What is written is `gcm1:` and the base64 of [AesGcmTokenCipher]'s output. + * The colon is what tells the two kinds of value apart, and it can: every + * bearer the server issues is `secrets.token_urlsafe`, whose alphabet has no + * colon, so a stored value without one is a bearer written before this class + * existed — it is read as it stands, and [TokenSealing] seals it the first time + * the file is opened — and a value with one is sealed. A colon behind a prefix + * this build does not know is a format from a later build, and opens to nothing + * rather than being sent as a bearer. + * + * **Opening is remembered, for the life of the process, failures included.** + * The Keystore is a binder call per operation, and the preferences emit on + * every write of every setting; without the memory each emission would be a + * round trip per token, and a key that is gone would be asked again on every + * one of them. With it, each sealed value costs one call in a process, and a + * value that would not open stays unopened until the next process — which is + * how a lost key becomes «sign in again» and never a loop. What is remembered is + * the bearer itself, which the interceptors already hold in memory anyway. + * + * Nothing here is ever called per request: the interceptors read + * `CredentialsSnapshot`, and what fills it opens the tokens on the IO + * dispatcher, before it maps the file — see `LessonsPreferences.opened`. + */ +internal class TokenVault(private val cipher: TokenCipher) { + + /** What each sealed value opened to, or `null` for one that would not. */ + private val opened = ConcurrentHashMap<String, Opened>() + + private class Opened(val token: String?) + + /** + * The value to write in place of [token]. + * + * A key that cannot be used at all leaves the bearer as it arrived rather + * than refusing to store it. Refusing would turn a phone whose Keystore is + * broken into one that can never join a class or sign in to a diary, and + * the bearer would still have been in memory; written bare, it is exactly + * what every install held before this existed, and [TokenSealing] tries + * again on the next start. It is the one plaintext this class ever writes. + */ + fun seal(token: String): String { + if (isSealed(token)) return token + val sealed = try { + SEALED_PREFIX + Base64.getEncoder().encodeToString(cipher.seal(token.toByteArray(Charsets.UTF_8))) + } catch (_: Exception) { + return token + } + // Remembered at once, so the refresh that follows the write does not + // ask the Keystore for what this call has just handed it. + opened[sealed] = Opened(token) + return sealed + } + + /** + * The bearer [stored] holds, or `null` when it holds none this phone can + * read — its key is gone, it was sealed on another phone, it was damaged, + * or it is in a format from a later build. Every caller reads `null` the + * way it reads a token that was never written, which is what makes a lost + * key a sign-in rather than a crash. + */ + fun open(stored: String): String? { + if (!isSealed(stored)) return stored + opened[stored]?.let { return it.token } + val token = if (stored.startsWith(SEALED_PREFIX)) { + try { + String(cipher.open(Base64.getDecoder().decode(stored.substring(SEALED_PREFIX.length))), Charsets.UTF_8) + } catch (_: Exception) { + null + } + } else { + null + } + // Two readers can race to the same value; the first answer stands. + val first = opened.putIfAbsent(stored, Opened(token)) ?: return token + return first.token + } + + companion object { + /** What every sealed value starts with; the `1` is the format of what follows. */ + const val SEALED_PREFIX = "gcm1:" + + /** Whether [stored] is sealed rather than a bearer; see the class notes on the colon. */ + fun isSealed(stored: String): Boolean = ':' in stored + + /** + * The phone's vault, one per process: every `LessonsPreferences` shares + * it, so the alarms' own instances open nothing the container's has not. + */ + val platform: TokenVault by lazy { TokenVault(AesGcmTokenCipher(AndroidKeystoreKeys(KEY_ALIAS))) } + + /** The Keystore entry's name. A new one would orphan every sealed token. */ + private const val KEY_ALIAS = "lessons.bearers" + } +} + +/** + * Seals and opens a token's bytes. + * + * An interface for one reason: the implementation that matters needs the + * AndroidKeyStore, which exists on a phone and nowhere else — not on the JVM + * these tests run on, and not in Robolectric either. Everything that decides + * what a sealed or unopenable value *means* is in [TokenVault] and tested + * there; this is the part that is only bytes. + */ +internal interface TokenCipher { + + /** @throws Exception of any kind when the key cannot be used; [TokenVault] decides what it costs. */ + fun seal(plaintext: ByteArray): ByteArray + + /** @throws Exception of any kind when [sealed] does not open with the key this phone holds. */ + fun open(sealed: ByteArray): ByteArray +} + +/** + * AES-GCM under a key somebody else holds: one byte of IV length, the IV, then + * the ciphertext with its tag. + * + * The IV is the cipher's own. AndroidKeyStore refuses one chosen by the caller + * unless the key is made to allow it, and a random one per seal is what GCM + * needs anyway; the length is written rather than assumed so the format does + * not depend on which provider produced it. The tag is what makes a damaged or + * foreign value fail to open instead of opening to garbage that would then be + * sent as a bearer. + */ +internal class AesGcmTokenCipher(private val keys: Keys) : TokenCipher { + + /** Where the key lives — the AndroidKeyStore on a phone ([AndroidKeystoreKeys]). */ + interface Keys { + + /** + * The key, or `null` when there is none. Never a new one: opening with + * a key made on the spot could only fail, and would replace nothing. + */ + fun existing(): SecretKey? + + /** A new key under the same name, replacing whatever stood there. */ + fun create(): SecretKey + } + + override fun seal(plaintext: ByteArray): ByteArray { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, keys.existing() ?: keys.create()) + val iv = cipher.iv + return byteArrayOf(iv.size.toByte()) + iv + cipher.doFinal(plaintext) + } + + override fun open(sealed: ByteArray): ByteArray { + val key = keys.existing() ?: throw GeneralSecurityException("No key to open a sealed token with") + val ivSize = sealed.firstOrNull()?.toInt() ?: throw GeneralSecurityException("Empty sealed token") + if (ivSize !in IV_SIZES || sealed.size < 1 + ivSize + TAG_BITS / 8) { + throw GeneralSecurityException("Not a sealed token") + } + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, sealed, 1, ivSize)) + return cipher.doFinal(sealed, 1 + ivSize, sealed.size - 1 - ivSize) + } + + private companion object { + const val TRANSFORMATION = "AES/GCM/NoPadding" + const val TAG_BITS = 128 + val IV_SIZES = 12..16 + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt index 63d19e41..4aef4f4c 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt @@ -1,26 +1,16 @@ package com.lumenpearson.lessons.core.data.datastore -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.Preferences -import androidx.datastore.preferences.core.emptyPreferences import com.lumenpearson.lessons.core.data.network.NetworkModule import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.Session import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.emitAll -import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeout import mockwebserver3.Dispatcher import mockwebserver3.MockResponse @@ -54,6 +44,8 @@ import org.junit.Test class RequestCredentialsTest { private lateinit var server: MockWebServer + private val keys = MemoryKeys() + private val vault = testVault(keys) private val scopes = mutableListOf<CoroutineScope>() @Before @@ -71,7 +63,7 @@ class RequestCredentialsTest { @Test fun `requests are signed from memory, not from the preferences`() = runBlocking { val store = MemoryStore() - val preferences = LessonsPreferences(store) + val preferences = LessonsPreferences(store, vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(7, "token-7")) val client = NetworkModule.okHttpClient(preferences.credentials::current) @@ -98,13 +90,13 @@ class RequestCredentialsTest { @Test fun `the first request after a cold start carries what was stored before it`() = runBlocking { val lastProcess = MemoryStore() - LessonsPreferences(lastProcess).apply { + LessonsPreferences(lastProcess, vault).apply { updateSettings { it.copy(baseUrl = server.url("/").toString()) } addSession(session(7, "token-7")) writeDiarySession(DiarySession(login = "parent", token = "diary-1")) } - val preferences = LessonsPreferences(MemoryStore(lastProcess.value)) + val preferences = LessonsPreferences(MemoryStore(lastProcess.value), testVault(keys)) val client = NetworkModule.okHttpClient(preferences.credentials::current) assertEquals("Bearer token-7", authorizationOn(client, "/api/v1/bundle")) @@ -118,7 +110,7 @@ class RequestCredentialsTest { */ @Test fun `a switch of class signs the very next request`() = runBlocking { - val preferences = LessonsPreferences(MemoryStore()) + val preferences = LessonsPreferences(MemoryStore(), vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(1, "token-1")) preferences.addSession(session(2, "token-2")) @@ -142,7 +134,7 @@ class RequestCredentialsTest { @Test fun `a new server address takes the very next request`() = runBlocking { answering(MockWebServer()).use { other -> - val preferences = LessonsPreferences(MemoryStore()) + val preferences = LessonsPreferences(MemoryStore(), vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } val client = NetworkModule.okHttpClient(preferences.credentials::current) authorizationOn(client, "/api/v1/warmup") @@ -159,7 +151,7 @@ class RequestCredentialsTest { /** Two accounts, two bearers: signing out of one leaves the other signing. */ @Test fun `the diary bearer follows its own sign-in and sign-out, and only its own`() = runBlocking { - val preferences = LessonsPreferences(MemoryStore()) + val preferences = LessonsPreferences(MemoryStore(), vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(7, "token-7")) val client = NetworkModule.okHttpClient(preferences.credentials::current) @@ -181,8 +173,8 @@ class RequestCredentialsTest { @Test fun `a write through another instance reaches the copy through the store`() = runBlocking { val store = MemoryStore() - val preferences = LessonsPreferences(store) - val elsewhere = LessonsPreferences(store) + val preferences = LessonsPreferences(store, vault) + val elsewhere = LessonsPreferences(store, vault) preferences.addSession(session(1, "token-1")) preferences.addSession(session(2, "token-2")) assertEquals("token-2", preferences.credentials.current().classToken) @@ -220,24 +212,4 @@ class RequestCredentialsTest { } start() } - - /** - * DataStore's contract without its file — one value, edits one at a time, - * every change emitted — counting each time anybody starts reading it. - */ - private class MemoryStore(initial: Preferences = emptyPreferences()) : DataStore<Preferences> { - private val state = MutableStateFlow(initial) - private val turn = Mutex() - val reads = AtomicInteger() - - val value: Preferences get() = state.value - - override val data: Flow<Preferences> = flow { - reads.incrementAndGet() - emitAll(state) - } - - override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences = - turn.withLock { transform(state.value).toPreferences().also { state.value = it } } - } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/SealedTokensTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/SealedTokensTest.kt new file mode 100644 index 00000000..91d789ff --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/SealedTokensTest.kt @@ -0,0 +1,300 @@ +package com.lumenpearson.lessons.core.data.datastore + +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.mutablePreferencesOf +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.DiaryTargetCodec +import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.ShellMode +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** + * The two bearers at rest (#201): sealed on the way into the file, opened on + * the way out, and a key that is gone costing a sign-in rather than the app. + * + * The Keystore itself cannot run here, so the key is held in memory + * ([MemoryKeys]) under the same [AesGcmTokenCipher] a phone runs: the + * ciphertext is real, and so is a tag that will not verify. The store is + * [MemoryStore], because none of this is about files. + */ +class SealedTokensTest { + + private val samara = DiaryTarget.netschool("samara", 1234, "Школа № 5", "ivanova", "Europe/Samara") + + // -- the round trip ------------------------------------------------------- + + @Test + fun `a bearer is never written to the file as it arrived`() = runBlocking { + val store = MemoryStore() + val preferences = LessonsPreferences(store, testVault()) + + preferences.addSession(session(7, "token-7")) + preferences.addSession(session(9, "token-9")) + preferences.writeDiarySession(DiarySession(login = "ivanova", token = "diary-1", target = samara)) + + val onDisk = store.value.asMap().values.joinToString(" | ") + listOf("token-7", "token-9", "diary-1").forEach { bearer -> + assertFalse("$bearer is in the file as it arrived: $onDisk", bearer in onDisk) + } + assertTrue(store.value[DiaryKeys.TOKEN]!!.startsWith(TokenVault.SEALED_PREFIX)) + } + + @Test + fun `what is sealed opens to the same bearers for every reader`() = runBlocking { + val keys = MemoryKeys() + val store = MemoryStore() + val preferences = LessonsPreferences(store, testVault(keys)) + preferences.addSession(session(7, "token-7")) + preferences.addSession(session(9, "token-9")) + preferences.writeDiarySession(DiarySession(login = "ivanova", token = "diary-1", target = samara)) + + // A new process: a new vault remembering nothing, over the same key. + val next = LessonsPreferences(MemoryStore(store.value), testVault(keys)) + + assertEquals(listOf("token-7", "token-9"), next.currentSessions().map { it.token }) + assertEquals("token-9", next.currentSession()?.token) + assertEquals("token-9", next.session.first()?.token) + assertEquals("diary-1", next.currentDiarySession()?.token) + assertEquals("diary-1", next.diarySession.first()?.token) + assertEquals("token-9", next.credentials.current().classToken) + assertEquals("diary-1", next.credentials.current().diaryToken) + assertEquals(ShellMode.CLASS, next.current().mode) + } + + @Test + fun `joining one class leaves the others' sealed tokens as they were`() = runBlocking { + val store = MemoryStore() + val preferences = LessonsPreferences(store, testVault()) + preferences.addSession(session(7, "token-7")) + val sealedSeventh = store.value.memberships().single().token + + preferences.addSession(session(9, "token-9")) + preferences.addSession(session(9, "token-9-again")) + + assertEquals(sealedSeventh, store.value.memberships().first { it.classId == 7L }.token) + assertEquals("token-9-again", preferences.currentSession()?.token) + } + + @Test + fun `the cipher opens only what its own key sealed, and only intact`() { + val keys = MemoryKeys() + val cipher = AesGcmTokenCipher(keys) + val sealed = cipher.seal("token-7".toByteArray()) + + assertArrayEquals("token-7".toByteArray(), cipher.open(sealed)) + + val damaged = sealed.copyOf().also { it[it.size - 1] = (it[it.size - 1].toInt() xor 1).toByte() } + assertRefused { cipher.open(damaged) } + assertRefused { AesGcmTokenCipher(MemoryKeys().also { it.create() }).open(sealed) } + keys.lose() + assertRefused { cipher.open(sealed) } + assertNotEquals( + "a random IV per seal: the same bearer never seals to the same bytes twice", + cipher.seal("token-7".toByteArray()).toList(), + cipher.seal("token-7".toByteArray()).toList(), + ) + } + + // -- an install from before sealing ---------------------------------------- + + @Test + fun `a bearer written before sealing is sealed on the first read, and only once`() = runBlocking { + val keys = MemoryKeys() + val vault = testVault(keys) + val before = mutablePreferencesOf( + MembershipKeys.SESSIONS to """[{"classId":7,"className":"7А","token":"token-7"}]""", + DiaryKeys.TOKEN to "diary-1", + DiaryKeys.LOGIN to "parent@example.com", + ) + val sealing = TokenSealing(vault) + + assertTrue(sealing.shouldMigrate(before)) + val after = sealing.migrate(before) + + assertFalse("token-7" in after.asMap().values.joinToString()) + assertFalse("diary-1" in after.asMap().values.joinToString()) + assertFalse("nothing is left to seal, so the next start does nothing", sealing.shouldMigrate(after)) + assertEquals("sealing twice changes nothing", after, sealing.migrate(after)) + + val read = LessonsPreferences(MemoryStore(after), testVault(keys)) + assertEquals("token-7", read.currentSession()?.token) + assertEquals("diary-1", read.currentDiarySession()?.token) + } + + @Test + fun `an install from before the list has its one token sealed where it stands`() = runBlocking { + val keys = MemoryKeys() + val before = mutablePreferencesOf( + MembershipKeys.TOKEN to "old-token", + MembershipKeys.CLASS_ID to 7L, + MembershipKeys.CLASS_NAME to "7А", + ) + + val after = TokenSealing(testVault(keys)).migrate(before) + + assertTrue(after[MembershipKeys.TOKEN]!!.startsWith(TokenVault.SEALED_PREFIX)) + assertNull("writing the list is a join's business, not the migration's", after[MembershipKeys.SESSIONS]) + assertEquals("old-token", LessonsPreferences(MemoryStore(after), testVault(keys)).currentSession()?.token) + } + + @Test + fun `sealing leaves everything this build cannot read exactly as it was`() = runBlocking { + val before = mutablePreferencesOf( + MembershipKeys.SESSIONS to + """[{"classId":1,"className":"7А","token":"t1","somethingNew":42},""" + + """{"classId":"not a number","token":"t2"},""" + + """"not even an object"]""", + ) + + val after = TokenSealing(testVault()).migrate(before)[MembershipKeys.SESSIONS]!! + + assertTrue("a newer build's field survives", "\"somethingNew\":42" in after) + assertTrue("a record this build cannot decode keeps its class id", "\"not a number\"" in after) + assertTrue("…and what is not a record at all stays", "\"not even an object\"" in after) + assertFalse("but no bearer is left bare in any of them", "\"t1\"" in after || "\"t2\"" in after) + } + + @Test + fun `a Keystore that cannot seal costs the sealing, never the token or the start`() = runBlocking { + val vault = TokenVault(BrokenCipher) + val before = mutablePreferencesOf(DiaryKeys.TOKEN to "diary-1", DiaryKeys.LOGIN to "parent") + val sealing = TokenSealing(vault) + + val after = sealing.migrate(before) + + assertEquals("the value stays, readable", "diary-1", after[DiaryKeys.TOKEN]) + assertTrue("and the next start asks again", sealing.shouldMigrate(after)) + + val preferences = LessonsPreferences(MemoryStore(), vault) + preferences.addSession(session(7, "token-7")) + assertEquals("a join still works", "token-7", preferences.credentials.current().classToken) + } + + // -- a key that is gone ---------------------------------------------------- + + /** + * A restore onto another phone, a wiped Keystore: the tokens are in the + * file and nothing can open them. The phone lands where a phone with no + * token lands — the join screen, or the diary's own form — and a join puts + * it back in a class. + */ + @Test + fun `a lost key costs the sign-in, not the app`() = runBlocking { + val keys = MemoryKeys() + val store = MemoryStore() + LessonsPreferences(store, testVault(keys)).apply { + addSession(session(7, "token-7")) + writeDiarySession(DiarySession(login = "ivanova", token = "diary-1", target = samara)) + } + keys.lose() + + val preferences = LessonsPreferences(MemoryStore(store.value), testVault(keys)) + + assertNull(preferences.currentSession()) + assertEquals(emptyList<Session>(), preferences.currentSessions()) + assertNull(preferences.session.first()) + assertNull(preferences.currentDiarySession()) + assertEquals( + "the diary's target outlives its bearer, as after a bare 401: its form asks again", + samara, + preferences.currentDiaryTarget(), + ) + assertEquals(ShellMode.DIARY, preferences.current().mode) + assertNull(preferences.credentials.current().classToken) + assertNull(preferences.credentials.current().diaryToken) + + preferences.addSession(session(7, "token-7-again")) + assertEquals("token-7-again", preferences.currentSession()?.token) + assertEquals("token-7-again", preferences.credentials.current().classToken) + assertEquals(ShellMode.CLASS, preferences.current().mode) + } + + @Test + fun `with no class and no diary, a lost key lands on the first screen`() = runBlocking { + val keys = MemoryKeys() + val store = MemoryStore() + LessonsPreferences(store, testVault(keys)).addSession(session(7, "token-7")) + keys.lose() + + assertEquals(ShellMode.NONE, LessonsPreferences(MemoryStore(store.value), testVault(keys)).current().mode) + } + + /** One Keystore call per value per process — never one per read, and never a loop. */ + @Test + fun `a token that will not open is asked about once, however often the file is read`() = runBlocking { + val keys = MemoryKeys() + val store = MemoryStore() + LessonsPreferences(store, testVault(keys)).apply { + addSession(session(7, "token-7")) + writeDiarySession(DiarySession(login = "ivanova", token = "diary-1", target = samara)) + } + keys.lose() + val cipher = CountingCipher(AesGcmTokenCipher(keys)) + val preferences = LessonsPreferences(MemoryStore(store.value), TokenVault(cipher)) + + repeat(10) { + preferences.currentSession() + preferences.currentDiarySession() + preferences.current() + preferences.credentials.refresh() + preferences.session.first() + } + + assertEquals("the class token and the diary's, once each", 2, cipher.opens.get()) + } + + @Test + fun `a bearer that opens is asked about once too, and one just sealed not at all`() = runBlocking { + val keys = MemoryKeys() + val cipher = CountingCipher(AesGcmTokenCipher(keys)) + val preferences = LessonsPreferences(MemoryStore(), TokenVault(cipher)) + + preferences.addSession(session(7, "token-7")) + repeat(10) { + preferences.currentSession() + preferences.credentials.refresh() + } + + assertEquals(1, cipher.seals.get()) + assertEquals("the vault remembers what it sealed", 0, cipher.opens.get()) + } + + @Test + fun `a value sealed by a later build opens to nothing, and is never sent as a bearer`() = runBlocking { + val prefs: Preferences = mutablePreferencesOf( + MembershipKeys.SESSIONS to """[{"classId":7,"className":"7А","token":"gcm9:AAAA"}]""", + DiaryKeys.TOKEN to "gcm9:BBBB", + DiaryKeys.TARGET to DiaryTargetCodec.encode(samara), + ) + + val preferences = LessonsPreferences(MemoryStore(prefs), testVault()) + + assertNull(preferences.credentials.current().classToken) + assertNull(preferences.credentials.current().diaryToken) + assertFalse("the migration does not touch it either", prefs.holdsBareToken()) + } + + // ------------------------------------------------------------------------- + + private fun session(classId: Long, token: String) = + Session(classId = classId, className = "$classId«А»", school = null, token = token) + + private fun assertRefused(block: () -> Unit) { + try { + block() + } catch (_: Exception) { + return + } + fail("opened what it should have refused") + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/StoreTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/StoreTestSupport.kt new file mode 100644 index 00000000..390d6822 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/StoreTestSupport.kt @@ -0,0 +1,83 @@ +package com.lumenpearson.lessons.core.data.datastore + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import java.util.concurrent.atomic.AtomicInteger +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * DataStore's contract without its file — one value, edits one at a time, + * every change emitted — counting each time anybody starts reading it. + * + * Not the file because what the tests here ask is about values, and + * DataStore's file layer cannot replace a file on Windows, where they run too. + */ +internal class MemoryStore(initial: Preferences = emptyPreferences()) : DataStore<Preferences> { + private val state = MutableStateFlow(initial) + private val turn = Mutex() + val reads = AtomicInteger() + + val value: Preferences get() = state.value + + override val data: Flow<Preferences> = flow { + reads.incrementAndGet() + emitAll(state) + } + + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences = + turn.withLock { transform(state.value).toPreferences().also { state.value = it } } +} + +/** + * The AndroidKeyStore's part, played by the JVM's own AES provider. + * + * Real AES-GCM through the same [AesGcmTokenCipher] the phone runs — only the + * place the key is kept differs — so a test here seals and opens actual + * ciphertext, and a tag that does not verify is a real failure rather than a + * fake's say-so. [lose] is a wiped Keystore; a second instance is another phone. + */ +internal class MemoryKeys : AesGcmTokenCipher.Keys { + + @Volatile + private var key: SecretKey? = null + + override fun existing(): SecretKey? = key + + override fun create(): SecretKey = + KeyGenerator.getInstance("AES").apply { init(256) }.generateKey().also { key = it } + + /** What a wiped Keystore, or a restore onto another phone, leaves behind. */ + fun lose() { + key = null + } +} + +/** A cipher that counts what it is asked, around a real one. */ +internal class CountingCipher(private val inner: TokenCipher) : TokenCipher { + val seals = AtomicInteger() + val opens = AtomicInteger() + + override fun seal(plaintext: ByteArray): ByteArray = inner.seal(plaintext).also { seals.incrementAndGet() } + + override fun open(sealed: ByteArray): ByteArray { + opens.incrementAndGet() + return inner.open(sealed) + } +} + +/** A Keystore that will do nothing at all — the one that cannot even make a key. */ +internal object BrokenCipher : TokenCipher { + override fun seal(plaintext: ByteArray): ByteArray = throw IllegalStateException("Keystore unavailable") + override fun open(sealed: ByteArray): ByteArray = throw IllegalStateException("Keystore unavailable") +} + +/** A vault over a key of its own, or over [keys] when two vaults must share one. */ +internal fun testVault(keys: MemoryKeys = MemoryKeys()): TokenVault = TokenVault(AesGcmTokenCipher(keys)) diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt index f97916b3..b52fa2e2 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatusReadTest.kt @@ -4,6 +4,7 @@ import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.emptyPreferences import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences +import com.lumenpearson.lessons.core.data.datastore.testVault import com.lumenpearson.lessons.core.data.network.LessonsApi import com.lumenpearson.lessons.core.data.network.dto.BundleDto import com.lumenpearson.lessons.core.data.network.dto.DeviceMeDto @@ -43,7 +44,7 @@ class ServerStatusReadTest { fun `asking for the server's status suspends on the preferences instead of blocking`() = runTest { val answer = CompletableDeferred<Unit>() val repository = SessionRepositoryImpl( - preferences = LessonsPreferences(SlowStore(answer)), + preferences = LessonsPreferences(SlowStore(answer), testVault()), api = NoCallsApi, cache = NoCache, ioDispatcher = StandardTestDispatcher(testScheduler), diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt index 839d5e61..ef23b245 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt @@ -4,6 +4,7 @@ import androidx.datastore.preferences.core.mutablePreferencesOf import com.lumenpearson.lessons.core.data.datastore.DiaryKeys import com.lumenpearson.lessons.core.data.datastore.ShellKeys import com.lumenpearson.lessons.core.data.datastore.shellState +import com.lumenpearson.lessons.core.data.datastore.testVault import com.lumenpearson.lessons.core.data.datastore.writeMemberships import com.lumenpearson.lessons.core.data.diary.MemoryDiaryStore import kotlinx.coroutines.test.runTest @@ -23,6 +24,7 @@ class ShellModeTest { private val session = Session(classId = 7, className = "7A", school = null, token = "class-token") private val samara = DiaryTarget.netschool("samara", 1234, "School 5", "ivanova", "Europe/Samara") + private val vault = testVault() @Test fun `a class outranks a diary`() { @@ -38,7 +40,7 @@ class ShellModeTest { @Test fun `nothing stored is none`() { assertEquals(ShellMode.NONE, shellModeOf(null, null)) - assertEquals(ShellState(ShellMode.NONE, held = false), mutablePreferencesOf().shellState()) + assertEquals(ShellState(ShellMode.NONE, held = false), mutablePreferencesOf().shellState(vault)) } /** A bare `401` drops the bearer and keeps the target: the family belongs on their diary's form. */ @@ -47,7 +49,7 @@ class ShellModeTest { val prefs = mutablePreferencesOf( DiaryKeys.TARGET to DiaryTargetCodec.encode(samara), ) - assertEquals(ShellMode.DIARY, prefs.shellState().mode) + assertEquals(ShellMode.DIARY, prefs.shellState(vault).mode) } @Test @@ -56,7 +58,7 @@ class ShellModeTest { DiaryKeys.TOKEN to "diary-token", DiaryKeys.LOGIN to "parent@example.com", ) - assertEquals(ShellMode.DIARY, prefs.shellState().mode) + assertEquals(ShellMode.DIARY, prefs.shellState(vault).mode) } /** #151: leaving the last class with a diary signed in lands on the diary, where its sign-out is. */ @@ -64,11 +66,11 @@ class ShellModeTest { fun `leaving the last class with a diary signed in is diary mode`() { val prefs = mutablePreferencesOf(DiaryKeys.TARGET to DiaryTargetCodec.encode(samara)) prefs.writeMemberships(listOf(session)) - assertEquals(ShellMode.CLASS, prefs.shellState().mode) + assertEquals(ShellMode.CLASS, prefs.shellState(vault).mode) prefs.writeMemberships(emptyList()) - assertEquals(ShellMode.DIARY, prefs.shellState().mode) + assertEquals(ShellMode.DIARY, prefs.shellState(vault).mode) } @Test @@ -76,7 +78,7 @@ class ShellModeTest { val prefs = mutablePreferencesOf(ShellKeys.ONBOARDING_HELD to true) prefs.writeMemberships(listOf(session)) - assertEquals(ShellState(ShellMode.CLASS, held = true), prefs.shellState()) + assertEquals(ShellState(ShellMode.CLASS, held = true), prefs.shellState(vault)) } /** #152: a cold start in no class must not arm the periodic class sync again. */ diff --git a/docs/legal/legal.json b/docs/legal/legal.json index f1b206fe..b89af465 100644 --- a/docs/legal/legal.json +++ b/docs/legal/legal.json @@ -1,6 +1,6 @@ { - "edition": 1, - "effective": "2026-09-25", + "edition": 2, + "effective": "2026-09-27", "files": { "terms": { "ru": "terms.ru.md", diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index e9bb8642..15be13d1 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -41,7 +41,7 @@ You type the server's address into the app yourself. If it leads to a server som - The server's address, the app's settings and, if you signed in to GitHub from the app, the GitHub key and your account name there. - Crash reports, only if you turned them on: up to five files with the phone's model, the Android and app versions, a description of the error and the app's latest log lines. -The keys, the login and the settings sit in the app's settings files **unencrypted**. The databases, the settings files and the crash reports are excluded from Google backup and from transfer to a new phone: a report stays on this phone until you send it yourself. That crash reports really are kept out of the backup has not yet been checked on a device. +The app keeps the class and diary access keys encrypted, with a key that Android holds in its protected store (the Android Keystore) and never hands out. If that key is lost — after the app's data is moved to another phone, say, or the store is reset — you will have to join the class and sign in to the diary again. The login, the GitHub key and the settings sit in the app's settings files **unencrypted**. The databases, the settings files and the crash reports are excluded from Google backup and from transfer to a new phone: a report stays on this phone until you send it yourself. That crash reports really are kept out of the backup has not yet been checked on a device. The phone never stores the diary password. The session the diary hands out after sign-in is held only in memory, never written down, and forgotten as soon as the phone has handed it to the server or the sign-in is abandoned. @@ -110,7 +110,7 @@ The app does not sign in to Gosuslugi or to My School: it opens the system's pag - **The diary's system**, after sign-in, sees the server's address using your session, not your phone's. - **The operator** holds the key the sessions are encrypted with, and so can technically open your diary. The encryption protects against whoever gets the database without the key, not against the operator. - **Telegram** keeps in the chat history whatever the bot sent you from the diary — marks, homework, timetable. -- **Whoever holds your phone:** the diary access key sits on it unencrypted, and the app opens the diary without a password until you sign out. +- **Whoever holds your phone:** the diary access key on it is encrypted, but the app decrypts it itself and opens the diary without a password until you sign out. - **Everyone whose diary account shows the same pupil** — the other parent, the pupil in their own account, and any other account in which the diary shows that pupil — sees in the app the corrections made for that pupil, whoever made them, and can change or reset them. Beyond the corrections, they see only what the diary shows their own account. ## Keeping the session open @@ -193,7 +193,7 @@ A parent who wants the server to delete their child's data can write to the oper - The access keys of phones and diaries and the one-time codes — for signing in from the bot and for connecting a phone — are kept by the server only as SHA-256 hashes. The class code is kept as it is: the bot shows it to admins. - The server encrypts the diary session (Fernet: AES-128-CBC with HMAC) with a key the operator sets. Without that key the diary does not run on the server at all, rather than keeping sessions unencrypted. -- The app itself encrypts nothing on the phone: there, the data is protected only by whatever protects the phone itself. +- On the phone the app encrypts only the class and diary access keys (AES-256-GCM, with a key from the Android Keystore). If the phone's key store does not work, it keeps them unencrypted, as it used to, and tries again to encrypt them at every start. Everything else — the copies of the timetable and the diary, the login, the settings — is protected only by whatever protects the phone itself. The encryption of the keys has not yet been checked on a device. **HTTPS depends on the address you typed.** The app also accepts `http://` addresses, for servers on a school's local network. At such an address everything between the phone and the server travels in the clear: the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in. Anybody on the same network can intercept it and open your diary. The app warns you about this before you sign in to a diary, but does not forbid it. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index 136048ed..f9d62e21 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -20,7 +20,8 @@ in legal.json. Before adding a promise, check it against what this code does not do: the password does cross the server on the bot's sign-in page and from older apps; the data is not in Russia; the operator holds the key and can read the diary; leaving a class deletes - nothing on the server; the phone encrypts nothing itself; an http:// server address + nothing on the server; the phone encrypts the two access keys and nothing else, and keeps + them bare where its Keystore does not work; an http:// server address carries everything in the clear; the keep-alive runs for up to 30 days after the last use, not only while somebody is active; a correction to the diary is the child's rather than the account's, so every account whose diary lists that pupil reads, changes and @@ -66,7 +67,7 @@ - Адрес сервера, настройки приложения и, если вы входили в GitHub из приложения, ключ GitHub и имя вашей учётной записи там. - Отчёты о сбоях — только если вы их включили: до пяти файлов с моделью телефона, версиями Android и приложения, описанием ошибки и последними записями о работе приложения. -Ключи, логин и настройки лежат в файлах настроек приложения **без шифрования**. Базы данных, файлы настроек и отчёты о сбоях исключены из резервной копии Google и из переноса на новый телефон: отчёт остаётся на этом телефоне, пока вы сами его не отправите. Что отчёты о сбоях действительно не попадают в копию, на устройстве пока не проверялось. +Ключи доступа к классам и к дневнику приложение хранит зашифрованными — ключом, который Android держит в своём защищённом хранилище (Android Keystore) и не выдаёт наружу. Если этот ключ пропадёт — например, после переноса данных приложения на другой телефон или сброса хранилища, — к классу придётся подключиться, а в дневник войти заново. Логин, ключ GitHub и настройки лежат в файлах настроек приложения **без шифрования**. Базы данных, файлы настроек и отчёты о сбоях исключены из резервной копии Google и из переноса на новый телефон: отчёт остаётся на этом телефоне, пока вы сами его не отправите. Что отчёты о сбоях действительно не попадают в копию, на устройстве пока не проверялось. Пароль от дневника телефон не сохраняет нигде. Сессию, которую дневник выдаёт после входа, телефон держит только в памяти, не записывая, и забывает, как только передал её серверу или вход отменён. @@ -135,7 +136,7 @@ - **Система дневника** после входа видит, что вашей сессией пользуется адрес сервера, а не вашего телефона. - **Оператор** держит ключ, которым зашифрованы сессии, и поэтому технически может открыть ваш дневник. Шифрование защищает от того, к кому попадёт база данных без ключа, а не от оператора. - **Telegram** хранит в истории чата то, что бот прислал вам из дневника, — оценки, задания, расписание. -- **Тот, у кого в руках ваш телефон:** ключ доступа к дневнику лежит на нём без шифрования, и приложение открывает дневник без пароля, пока вы из него не вышли. +- **Тот, у кого в руках ваш телефон:** ключ доступа к дневнику на нём зашифрован, но приложение само его расшифровывает и открывает дневник без пароля, пока вы из него не вышли. - **Все, чья учётная запись дневника показывает того же ученика**, — второй родитель, сам ученик в своей учётной записи и любая другая, в которой дневник его покажет, — видят в приложении правки, сделанные для этого ученика, кем бы они ни были сделаны, и могут их изменить или сбросить. Помимо правок им видно только то, что дневник показывает их собственной учётной записи. ## Поддержание сеанса @@ -218,7 +219,7 @@ - Ключи доступа телефона и дневника и одноразовые коды — для входа из бота и для подключения телефона — сервер хранит только в виде хеша SHA-256. Код класса хранится как есть: бот показывает его администраторам. - Сессию дневника сервер шифрует (Fernet: AES-128-CBC с HMAC) ключом, который задаёт оператор. Без ключа дневник на сервере не работает вовсе, а не хранит сессии открыто. -- Приложение само ничего не шифрует на телефоне: там данные защищены лишь тем, чем защищён сам телефон. +- На телефоне приложение шифрует только ключи доступа к классам и к дневнику (AES-256-GCM, ключом из Android Keystore). Если хранилище ключей на телефоне не работает, оно хранит их без шифрования, как раньше, и пробует зашифровать при каждом запуске. Всё остальное — копии расписания и дневника, логин, настройки — защищено лишь тем, чем защищён сам телефон. Шифрование ключей на устройстве пока не проверялось. **HTTPS зависит от адреса, который вы ввели.** Приложение принимает и адреса `http://` — ради серверов в локальной сети школы. По такому адресу всё, что идёт между телефоном и сервером, передаётся открытым текстом: ключи доступа к классу и к дневнику, название телефона, расписание и сессия дневника, которую телефон передаёт серверу при входе. Любой в той же сети может её перехватить и открыть ваш дневник. Приложение предупреждает об этом перед входом в дневник, но не запрещает. From 13247d12152597cfa9fc72127b1d66eeb7813f90 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 15:18:11 +0300 Subject: [PATCH 21/43] Make the README and HANDOVER.md say what production and GitHub say now MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README's honest status still said `/api/v1/warmup` had not been read since #61, and that the badge on «О приложении» had never met a real server. HANDOVER.md's opening, and #186's record, said the opposite: on 26 September 2026 production's deployment of `bd7c816` answered `{"status":"ok","api_version":1,"schema":"0017"}` through the Vercel connector, and the badge said «Сервер: база и код разошлись», correctly, against a local server on the emulator. The README now says both, with the date, and that the read was one request rather than a measurement. What else had been overtaken, each checked on GitHub or in git first: - HANDOVER.md, «And the work has a tracker now»: «#109–#127 open, which are the whole of what is left» and «Thirty-three have been filed since». Six of those have closed (#110, #114–#117, #119), and 75 issues have been filed since #127, not 33. - Section 5 sent the reader to #114–#117 as open issues and to #156 for a phone's backup; #186's merge closed all five. It asked for the warmup answer as the cheapest sign a migration met its code, which was read. It said the widget's corners and #83's widget work had never been on a launcher, while #186 and #189 put the widget on the emulator's; and «Nothing from the last batch» meant #62, not #189. The README's own widget bullet contradicted its emulator paragraph the same way. - Section 7 said #119 and #156 «close with» #186, which merged; asked for an APK «after #140 merges», which merged on 26 September; and said one line of milestone 10's description was behind, when #160–#165 and the audit's #190–#211 are all on it and milestone 9's is further behind. Its request to drop the `Teleport auto-stash` moved to docs/history.md, «Moved out of section 7»: `git stash list` is empty and `refs/stash` is gone. Who dropped it is not known here. - The milestone table gains #190–#211 on milestone 10, and the `github-pr` skill's copy of rows 9 and 10, which HANDOVER.md says is the same table, is brought level with it and with GitHub. test_schema_version.py's comment said the README was left out of the warmup-answer check because it quoted #61's answer on purpose. It quotes the answer of 26 September now, and the exclusion still holds for the same reason in a new form — a dated answer is a record, and the next revision must not make the README claim a read nobody made — so the comment says that instead. No code changed. Left for the close-out: the opening still names #189 as the open pull request and #174 and #188 as meant to close. #189 merged as `938e59f` on 27 September at 09:54 UTC and both issues closed with it, and rewriting the opening is the close-out's job. CLAUDE.md's milestone paragraph («holds issues #109–#117») was not touched: its other sections are being rewritten on other branches. Refs #211 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/skills/github-pr/SKILL.md | 4 +- HANDOVER.md | 81 ++++++++++++++++------------- README.md | 43 ++++++++------- docs/history.md | 13 ++++- server/tests/test_schema_version.py | 4 +- 5 files changed, 86 insertions(+), 59 deletions(-) diff --git a/.claude/skills/github-pr/SKILL.md b/.claude/skills/github-pr/SKILL.md index f7260b9f..23ab0368 100644 --- a/.claude/skills/github-pr/SKILL.md +++ b/.claude/skills/github-pr/SKILL.md @@ -77,8 +77,8 @@ matched pull request's body in full. | 6 | `v0.6.0 — Dishka DI, scrolling text, in-app guide from the repo` | PRs #60–#74; issues #96, #97, #99, #101, #103, #104 | | 7 | `Dependencies — dependabot bumps` | every dependabot bump; deliberately not a version, and open for good | | 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | PRs #75–#85, #128; issues #98, #100, #105–#108 | -| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | PRs #129, #133, #134; issues #109–#117, #130–#132 — **open**, the first whose work needs an emulator or a phone | -| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | PR #140; issues #135–#139, #141, #145–#160 — **open**, the one being worked on | +| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | PRs #129, #133, #134, #186, #187, #189; issues #109–#117, #130–#132, #167–#185, #188 — **open**, the first whose work needs an emulator or a phone | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | PR #140; issues #135–#139, #141, #145–#165, #190–#211 — **open**, the one being worked on | All ten were renamed on 25 September 2026: every title now names what the version delivered, and each description names its pull requests and issues. A title quoted from diff --git a/HANDOVER.md b/HANDOVER.md index 90cf6bd6..2a1f7226 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -123,17 +123,22 @@ Vercel can go in one. **Until #128 there were no issues in this repository at all** — the milestones were the only grouping the history had, and everything else lived in this document's prose. Forty-two issues were opened in one go: **#86–#108 closed**, describing what was built and -what each bug sweep found, and **#109–#127 open**, which are the whole of what is left. +what each bug sweep found, and **#109–#127 open**, which were then the whole of what was +left. Six of those have closed since: #114–#117 and #119 at #186's merge, and #110 at +#187's. The forward half is worth reading before planning anything: **#109** is the epic this section describes, **#118–#122** are the owner's alone, and **#126** collects the four small things carried deliberately, so that a later session does not re-discover a decision as if it were an oversight. -**Thirty-three have been filed since.** #130 was the survey #134 closed, and #131 and #132 +**Seventy-five have been filed since.** #130 was the survey #134 closed, and #131 and #132 the two defects #133 closed. #135 is the owner's decision about the second diary; #136–#139 and #141 are the work #140 carries; #142–#144 are its deliberate follow-ups, on no milestone; and #145–#165 are the defects found on its branch, each filed before its fix. +#167–#185 are what #186's walk on an emulator found and what the owner asked for that +night, and #188 what #189 found; all twenty are closed. #190–#211 are the external audit of +27 September 2026, on milestone 10. Labels are `type:` (feature, bug, chore, research, decision, epic), `area:`, `status:` (now, next, someday, done) and `needs:` (device, owner). **A session cannot create a GitHub @@ -332,7 +337,7 @@ maps them. The | 7 | `Dependencies — dependabot bumps` | `Dependencies` | open, for good | every dependabot bump; deliberately not a version | | 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | `v0.7.0 — Оптимизация` | closed | PRs #75–#85, #128; issues #98, #100, #105–#108 | | 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | `v0.8.0 — On a device` | open | PRs #129, #133, #134, #186, #187, #189; issues #109–#117, #130–#132, #167–#185, #188 — the first whose work needs an emulator or a phone, and #186 the first done on one | -| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140 (merged); issues #135–#139, #141, #145–#165 | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140 (merged); issues #135–#139, #141, #145–#165, #190–#211 (the external audit of 27 September) | **#142, #143 and #144 are on no milestone, deliberately**: two follow-ups and a decision that #140 left alone on purpose, which belong to whichever version takes them up. @@ -356,13 +361,14 @@ This is the main thing worth knowing: **all of this work is proved by tests and else.** **Most of this section is now also an issue**, which is where it should be worked from: -#113 the widget's sizes, #114 the arranging gesture, #115 the correction mode, #116 two -classes on one phone, #117 the upgrade path, #111 what the ribbon's shader costs, #121 the -real diary. They are children of **#109**, the epic for moving this work to a machine with a -device on it. #140's additions below belong to #121 where they need a live diary and to -#156 where they need a phone's backup; the rest wait for the first APK built after its -merge. The prose here is kept because it says *why* each one is unverifiable, which an issue -title cannot. +#113 the widget's sizes, #111 what the ribbon's shader costs and #121 the real diary are +open; #114 the arranging gesture, #115 the correction mode, #116 two classes on one phone +and #117 the upgrade path were closed by #186's walk on an emulator, and what only a phone +can add to them stays below. They are children of **#109**, the epic for moving this work to +a machine with a device on it. #140's additions below belong to #121 where they need a live +diary; #156, the backup, closed on the same emulator walk, and a phone's own backup is its +bullet below. The rest wait for an APK on a phone. The prose here is kept because it says +*why* each one is unverifiable, which an issue title cannot. **#186 looked at a good part of this on an emulator** (26–27 September 2026; its section, «…the first walk of the app on a device», in `docs/history.md` now, has the detail). The @@ -440,7 +446,8 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i has felt: whether the wobble is plausible, whether half a slot is the right threshold under a real thumb, whether a hold that picks the tab up at once is too eager for someone who only meant to look, and whether the haptic lands where the mode opens. **The APK built for #84 predates the fix and does not - rearrange anything**; the first install worth an evening is one built after #85 merges. + rearrange anything**; the first install worth an evening is one built after #186, as + section 7 says, because #181 made the gesture one touch. - **The drag is driven from a test now, and how far it goes is the whole reason it can be.** #84 left it undriven on the ground that Robolectric reports its own densities, so a synthetic swipe of «half a slot» measures the environment. True, and it hid a defect for a @@ -481,9 +488,11 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i has seen: whether the concentric corner reads as concentric, whether a marquee that never stops is pleasant rather than merely readable, and whether stepping a month with the arrows surprises somebody who has just switched «День» into its list mode. -- **The widget's new corners have never been on a launcher**, which is the only place they - exist. #82 derives every inner radius from the size class's own padding, and the five - tests reproduce that arithmetic and nothing else — no test draws a widget. What nobody has +- **The widget's new corners have been on a launcher only on an emulator's, and nobody judged + them there**: #186 and #189 had the widget on the Pixel launcher at a few sizes, and #113 + stays open for the corner radii. A launcher is the only place they exist. #82 derives every + inner radius from the size class's own padding, and the five tests reproduce that + arithmetic and nothing else — no test draws a widget. What nobody has seen: whether the gap now reads as even at 8 dp of padding *and* at 16, whether the 6 dp floor is tight enough to still look like a corner on the widest rungs, and how any of it sits against a launcher's own widget rounding. Below API 31 the question does not arise — @@ -499,15 +508,18 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i app settings #188 now redraws on, and every render in that check was forced with a reinstall; - any launcher but the emulator's. -- **Nothing of #83's widget work has been seen on a launcher either, and that is the surface - this batch changed most.** The font-scale division, the two weights that stop the trailing +- **#83's widget work has been on a launcher only on an emulator's, and that is the surface + #83 changed most.** #186 put the widget there at four sizes and two font scales, where the + 2×2 and, at the larger scale, the 2×1 still cut their text (#174, fixed by #189 and seen + again there, above). The font-scale division, the two weights that stop the trailing detail starving the subject, and the outer box that gives the seven day chips their gaps are all proved by tests that reproduce the arithmetic and the budgets — no test draws a widget. Worse for confidence: **two of the claims are about what Glance does with a modifier chain, and they come from reading its translator rather than from pixels** — that `applyModifiers` folds every padding into one `setViewPadding` on the background's own view, and that a container keeps ten children. What nobody has seen: whether the largest - system font now fits the rung it lands on, whether the chips read as seven days, and + system font fits the rung it lands on at the sizes #186 did not use, whether the chips read + as seven days, and whether the subject keeps its width beside a long teacher's name. Below API 31 the corner half of this does not arise at all — `cornerRadius` is a no-op there. - **`docker compose up` has never been run.** There is no Docker in this environment, so @@ -530,8 +542,9 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i would not compile normally throws in-process instead of logging from the render thread. - **The reported term defect is fixed against tests, not against the class that reported it.** The server fix needs no new APK, so the first real check is that class's next sync - after the deploy, and `/api/v1/warmup` answering `"schema":"0014"` or later is the - cheapest sign that the migration and the code actually met. + after the deploy, and no batch since has recorded one. The cheapest sign that the + migration and the code met is in: production's `/api/v1/warmup` answered + `"schema":"0017"` on 26 September 2026, read through the Vercel connector. - **There is one `androidTest` in the project, and it is about one gesture.** Until #187 there was none, because until #186 no session had an emulator: the cloud containers have no `/dev/kvm`. `ToolbarOnDeviceTest` (#110) drags the tab bar's arranging gesture at a @@ -620,8 +633,9 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i claiming twice on one date, but nobody has run two ticks at once; the export's round trip is verified by computing both sides, which is all it claims. -- **Nothing from the last batch has been seen moving, or wrapping.** Robolectric composes - the marquee but advances no animation and reads no frame, so what is proven is that a line +- **Nothing from #62, the batch that stopped text being cut off, has been seen moving, or + wrapping.** Robolectric composes the marquee but advances no animation and reads no + frame, so what is proven is that a line which fits is laid out exactly as before, that a line which does not stays inside its box rather than pushing the row apart, and that the whole string is present either way. That it actually scrolls — and reads well doing so — needs the APK. The same for the other @@ -1017,7 +1031,8 @@ All of this is beyond an agent's reach: it needs a phone, a key or a live servic environment, #120 the external cron and `DADATA_TOKEN`, #121 the real diary, #122 the widget's tick cadence and the diary credential's bound, #135 the second diary, #144 a default server for a fresh install. Each carries the label `needs:owner`. #119 (`/api/v1/warmup` and -`/start`) and #156 (the backup) were answered by #186 and close with it. +`/start`) and #156 (the backup) were answered by #186 and closed at its merge on 26 September +2026. **Give the release keystore its passwords, on your machine and nowhere else.** The keystore handed over during #186 is PKCS12 and came without them, so nothing was signed @@ -1034,11 +1049,6 @@ so each batch with a device in it costs two or three. The emulator refused to start once below 2 GB, and the AVD's Quick Boot image alone is 8.5 GB. The worktrees under `.claude/worktrees/` each carry their own Gradle build directories. -**Drop the `Teleport auto-stash` when convenient** (`stash@{0}`, over `c26eace`). It holds -what the IDE generated rather than work — #187's section, «…the first instrumented tests…», -lists it — and -nothing in a session here drops a stash it did not make. - **Restart Android Studio once, when it is free.** Three changes wait for it, because the IDE rewrites those files on exit: `server/.venv` as the Python SDK, the root module as a Python one (which quiets «Unsupported Modules Detected»), and the third-party «Python Portable» @@ -1048,16 +1058,17 @@ is already in place (see «…the first walk of the app on a device», the secti **The tenth milestone exists, and #140 is on it.** The owner created `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` on 25 September and renamed -the other nine the same day. One line of it is behind: its description names issues -#145–#159, and #160 is on it too. A milestone's description is the owner's to edit; nothing -in a session here can. +the other nine the same day. Its description is behind: it names issues #145–#159, and +#160–#165 are on it too, as are the external audit's #190–#211 of 27 September. The ninth's +is further behind — it names PRs #129, #133 and #134 only. A milestone's description is the +owner's to edit; nothing in a session here can. **Sign in once, for real, from a phone — it is the one question #140 cannot answer about -itself.** Build an APK from `main` after #140 merges, install it on a phone in no class, and -take the diary path twice: a «Сетевой город» region that takes a password, and Петербург. -Whether the import arrives, or the phone says the diary refused the session from our -server's address — the `409` — decides whether the phone-registered path works for that -diary at all. It is #121's first live session, for both diaries at once. +itself.** Build an APK from `main`, which has carried #140 since 26 September, install it on +a phone in no class, and take the diary path twice: a «Сетевой город» region that takes a +password, and Петербург. Whether the import arrives, or the phone says the diary refused the +session from our server's address — the `409` — decides whether the phone-registered path +works for that diary at all. It is #121's first live session, for both diaries at once. **Then walk the rest of the first run on that phone.** The class code as the other way in; leaving the last class with a diary signed in, which should land on the diary as the home diff --git a/README.md b/README.md index 84c19c1c..349830ac 100644 --- a/README.md +++ b/README.md @@ -464,25 +464,30 @@ answer there is «off». server, the sync layer, the calendar, the widget and the self-hosted deployment, and every one of them is proved by a test rather than by a screen. -* **None of the widget's fixes has been seen on a launcher.** The three defects behind them - were read off one build on a phone, which is the only pixel evidence in this section; the - fixes themselves — the height divided by the font scale, the two weights that stop a room - number starving the subject, the week strip's gaps — are held by tests that reproduce the - arithmetic, not the rendering. The two claims about what Glance does with a modifier chain - come from reading its translator. -* **The server badge on Настройки → О приложении has never been drawn against a real - server.** It reads `GET /api/v1/warmup` and tells «Сервер на связи», «Сервер: база - и код разошлись», «Сервер не отвечает» and «Адрес сервера не задан» apart in - Robolectric, against a fake. Which of the four a phone shows when pointed at production, - nobody has watched. -* **`/api/v1/warmup` itself has not been read since #61**, when it answered - `{"status":"ok","api_version":1,"schema":"0013"}`. Production is at `0017` since 26 - September 2026, 12:26 UTC: `0015`, `0016` and `0017` went on together before #140's - merge, and `0017` found no diary correction to rewrite. Once #140 has deployed it should - say `0017`. That one request is the cheapest check - of whether the migrations and the code that needs them actually met — but the deployment - previews sit behind Vercel's protection, and nobody has made the check against production - either. +* **The widget's fixes have been on a launcher only on an emulator's.** The three defects + behind them were read off one build on a phone, which is the only pixel evidence from a + phone in this section. #186 put the widget on the emulator's Pixel launcher at four sizes + and two font scales, where the 2×2 and, at the larger scale, the 2×1 still cut their text + (#174, fixed in #189 and looked at again there). The fixes themselves — the height + divided by the font scale, the two weights that stop a room number starving the subject, + the week strip's gaps — are held by tests that reproduce the arithmetic, not the + rendering. The two claims about what Glance does with a modifier chain come from reading + its translator. +* **The server badge on Настройки → О приложении has been drawn against a real server + once, on an emulator** (#186): «Сервер: база и код разошлись», correctly, from a local + server whose database `create_all` had built. It reads `GET /api/v1/warmup` and tells + «Сервер на связи», «Сервер: база и код разошлись», «Сервер не отвечает» and «Адрес + сервера не задан» apart in Robolectric, against a fake. Which of the four a phone shows + when pointed at production, nobody has watched. +* **`/api/v1/warmup` was last read on 26 September 2026**, at 17:05 UTC, after #140 had + deployed: the production deployment of `bd7c816` answered + `{"status":"ok","api_version":1,"schema":"0017"}`, so the migrations and the code that + needs them met. Production is at `0017` since 12:26 UTC that day: `0015`, `0016` and + `0017` went on together before #140's merge, and `0017` found no diary correction to + rewrite. The per-deployment URLs sit behind Vercel's protection, so the request went + through the Vercel connector, which carries the owner's access; the production alias is + not behind it. It is one request, not a measurement, and the next migration needs it read + again. * **`docker compose up` has not been run.** There is no Docker in this environment: the compose file was parsed and its dependency conditions asserted. The `migrate` service and the revisions now in the image are written and never watched coming up. diff --git a/docs/history.md b/docs/history.md index f3777c0e..532cfbf9 100644 --- a/docs/history.md +++ b/docs/history.md @@ -3562,8 +3562,9 @@ index. The sweep changed no code and ran no gate — there was nothing to run. What `HANDOVER.md`'s «Left to the owner» asked for and got, or recorded as already decided: the warmup request, answered on 26 September 2026 together with the bot's `/start`, which closed #119; the report from #79; the calendar's year scroll, decided and built in #78; the -milestones' tidy-up; items 1, 1a and 1b of its numbered list; and item 5, the correction -mode's walk, which #186 made on an emulator and which closed #115. +milestones' tidy-up; items 1, 1a and 1b of its numbered list; item 5, the correction +mode's walk, which #186 made on an emulator and which closed #115; and, at the end, the +stash it asked the owner to drop, which was gone by the afternoon. **Open `/api/v1/warmup` in a browser — it is the one thing that settles whether the schema and the code that needs it actually met**, and it is outstanding since #61. It cannot be @@ -3623,3 +3624,11 @@ and there is no `gh` CLI. this); that pressing a sentence with a number in it — «12,4 МБ» under updates — shows the pattern `%1$s МБ` in the editor rather than the sum; and that inside the editor itself a long press does nothing. + +*Later the same day the stash was gone — `git stash list` empty, no `refs/stash` in the +repository — so the request to drop it moved here too. Who dropped it is not recorded.* + +**Drop the `Teleport auto-stash` when convenient** (`stash@{0}`, over `c26eace`). It holds +what the IDE generated rather than work — #187's section, «…the first instrumented tests…», +lists it — and +nothing in a session here drops a stash it did not make. diff --git a/server/tests/test_schema_version.py b/server/tests/test_schema_version.py index 5a9cebab..02269018 100644 --- a/server/tests/test_schema_version.py +++ b/server/tests/test_schema_version.py @@ -88,7 +88,9 @@ def test_the_constant_the_app_ships_is_the_real_migration_head(): re.compile(r"expects `(\d{4})`"), ) #: The answer `/warmup` gives when all is well, as the reference documents -#: print it. Only under docs/: the README quotes an answer from #61 on purpose. +#: print it. Only under docs/: the README quotes the last answer production +#: gave, with its date, and a dated answer is a record rather than a claim +#: about the head — the next revision must not make it say what nobody read. _WARMUP_OK = re.compile(r'"status": ?"ok"[^}\n]*"schema": ?"(\d{4})"') From c7d88ab4cbd281d5dc3a8074fb8141831749d60a Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 15:18:20 +0300 Subject: [PATCH 22/43] Say what the import guard's history really was, with its dates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docstring said six sibling imports «lived here for months» under a guard that reported them green, in a repository whose first commit is from 9 September. `git log -S` says what happened: six lines in five files (test_bot_views, test_bot_calendar, test_bot_editor twice, test_bot_diary, test_diary_web) came in on 12 and 13 September; the guard arrived on 21 September at 18:20 UTC, seventeen minutes after test_holidays.py's `from tests.test_api import _token` turned CI red; and the six went on 22 September at 07:28 UTC, when 77bf213 moved the fakes into conftest.py. Under the guard, that is thirteen hours, not months. Two neighbouring claims were inexact in the same way and are corrected: the `tests.` import did not ship on the commit this test arrived with but seventeen minutes before it, and under `--import-mode=importlib` what dies is each of the five files, with a ModuleNotFoundError naming the sibling rather than `tests`. The second was checked on a two-file probe under pytest 9.1.1 — the bare sibling import passes under the default `prepend` mode and fails at collection under `importlib` with «No module named 'test_a'» — not on the tree at 77bf213^ itself. (77bf213's own body said three of the files would die; nothing reproduces that number.) Comment-only; the three tests in the file pass unchanged. Closes #211 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/tests/test_test_imports.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/tests/test_test_imports.py b/server/tests/test_test_imports.py index 86146197..f6d776ea 100644 --- a/server/tests/test_test_imports.py +++ b/server/tests/test_test_imports.py @@ -6,21 +6,25 @@ *collection* on CI, which runs the bare `pytest`. The whole file errors, and it errors on a line that has nothing to do with what the file tests. -That shipped, in this repository, on the commit this test arrived with. The -import looked ordinary, the suite was green locally, and the failure said -«ModuleNotFoundError: No module named 'tests'» about a directory that is -plainly there. +That shipped, in this repository, on 21 September 2026: `test_holidays.py` +borrowed `_token` that way, CI went red, and this test arrived seventeen +minutes later with the fix. The import looked ordinary, the suite was green +locally, and the failure said «ModuleNotFoundError: No module named 'tests'» +about a directory that is plainly there. **And then this test went on saying «no test module may import another one» while five of them did.** It matched only the `tests.`-prefixed spelling; the -bare `from test_bot_handlers import FakeState` was invisible to it, and six -such lines lived here for months under a guard that reported them green. They +bare `from test_bot_handlers import FakeState` was invisible to it. Six such +lines, in five files, had been here since 12 and 13 September, and for the +last thirteen hours of that — until the fakes they borrowed moved into +`conftest.py` on 22 September — under a guard that reported them green. They worked, which is what made them invisible: under the default `prepend` import mode pytest puts *this directory* on `sys.path` before importing a test module, so a sibling resolves by bare name. Under `--import-mode=importlib`, which pytest now recommends and which is one line of `pyproject.toml` away, -nothing is added to `sys.path` at all and all six die at collection with the -very message quoted above. The rule was right; the matcher was narrower than +nothing is added to `sys.path` at all, and each of the five files dies at +collection with the same `ModuleNotFoundError`, naming the sibling where the +one above named `tests`. The rule was right; the matcher was narrower than the sentence describing it, which is the same defect as a test asserting a substring of the line it means to pin. From 9181796469849a09efea18869a3b269e97e703f4 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 15:20:53 +0300 Subject: [PATCH 23/43] Read the Kotlin with detekt, and fail CI on any finding the code did not already have Nothing checked the Kotlin statically (#210). detekt 2.0.0-alpha.6 now reads every module's sources: the newest release on Maven Central and the Plugin Portal, and the first line of detekt that supports both AGP 9's built-in Kotlin and Kotlin 2.4; the catalog header names where each fact came from. It is applied in each of the five build files, the way compose-stability.conf already is, with one config at android/config/detekt/detekt.yml built on detekt's defaults. What differs from them is only what argues with how Compose is written, each entry scoped to an annotation so the rule still holds everywhere else, each with its reason in the file: FunctionNaming and LongMethod skip a @Composable, TooManyFunctions does not count one, TopLevelPropertyNaming accepts the PascalCase constants the Compose API guidelines ask for (141 of the tree's 171), and MagicNumber skips a @Preview. The findings the code has today - 576, under 488 baseline entries - are recorded in a detekt-baseline.xml per module, so they pass and a new one fails. A baseline entry names the file, so the branches that split SettingsScreen, WeekScreen, LessonsApp and DiaryViewModel will orphan some of them; `./gradlew detektBaseline` rewrites all five in one command, and docs/build.md says when to run it and when not to. Plain detekt, without type resolution: the type-resolved tasks take their classpath from each variant's compilation, so they compile every module they depend on, debug and release, before analysing anything. What that costs is written down rather than hidden: 93 of detekt's 213 rules need types and do not run, LongParameterList, UnusedImport and UnusedPrivateFunction among them. CI runs it as a step of its own after the build rather than as a fourth task in the one invocation: that invocation has no --continue, detekt's tasks depend on nothing and would run first, and one finding would stop the tests from being scheduled at all. Not run through Gradle. The first attempt here died at 14:07 with the machine, which zero-filled the detekt plugin's files it had just put in the shared Gradle module cache (~/.gradle/caches/modules-2/files-2.1/dev.detekt), and every build since fails to parse their POMs; clearing a shared cache is not this branch's to do. The baselines were written by detekt's own command line - the same 2.0.0-alpha.6, its sha1 checked against Maven Central - with the arguments the Gradle task passes. Against them all five modules pass, and a scratch magic number in :core:model failed the check and passed again once removed. Unverified: that `./gradlew detekt` resolves and passes, that `detektBaseline` would write the same files, that the plugin is clean under the configuration cache, and that `test`, assembleDebug and assembleRelease still build with it applied. That neither `test` nor the assembles run detekt - the plugin hangs it on `check` alone - is read from the plugin's source, not observed. Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/skills/gates/SKILL.md | 13 +- .github/workflows/ci.yml | 19 ++ CLAUDE.md | 6 + android/app/build.gradle.kts | 12 + android/app/detekt-baseline.xml | 183 +++++++++++++++ android/build.gradle.kts | 1 + android/config/detekt/detekt.yml | 74 ++++++ android/core/data/build.gradle.kts | 12 + android/core/data/detekt-baseline.xml | 210 ++++++++++++++++++ android/core/designsystem/build.gradle.kts | 15 ++ android/core/designsystem/detekt-baseline.xml | 79 +++++++ android/core/model/build.gradle.kts | 12 + android/core/model/detekt-baseline.xml | 19 ++ android/gradle/libs.versions.toml | 18 ++ android/widget/build.gradle.kts | 12 + android/widget/detekt-baseline.xml | 27 +++ docs/build.md | 60 ++++- 17 files changed, 766 insertions(+), 6 deletions(-) create mode 100644 android/app/detekt-baseline.xml create mode 100644 android/config/detekt/detekt.yml create mode 100644 android/core/data/detekt-baseline.xml create mode 100644 android/core/designsystem/detekt-baseline.xml create mode 100644 android/core/model/detekt-baseline.xml create mode 100644 android/widget/detekt-baseline.xml diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index ddca164b..db0f0592 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -29,8 +29,15 @@ Narrower while iterating: `python -m pytest -q tests/test_schedule.py -k parity` 2. `./gradlew assembleDebug` 3. `./gradlew assembleRelease` — **not optional.** CI builds both on every push, because R8 and resource shrinking are where "worked in debug" stops being true. +4. `./gradlew detekt` — static analysis of the Kotlin, all five modules, about half a + minute. Neither `test` nor the assembles run it, so it is a gate of its own. It fails on + a finding the module's `detekt-baseline.xml` does not hold: fix it, or `@Suppress` it at + the declaration with the reason. Do not regenerate a baseline to make a new finding go + away — `./gradlew detektBaseline` is for after a merge that moves code between files + (`docs/build.md`, "detekt"). -Narrower: `./gradlew :core:model:test --tests '*ScheduleEngineTest*'`. +Narrower: `./gradlew :core:model:test --tests '*ScheduleEngineTest*'`, +`./gradlew :app:detekt`. In a sandbox with no network every Gradle invocation needs `--offline`. @@ -39,8 +46,8 @@ gate.** ## What CI is -`.github/workflows/ci.yml`: ruff, pytest `-n auto`, `./gradlew test`, both assembles. -Nothing else. +`.github/workflows/ci.yml`: ruff, pytest `-n auto`, `./gradlew test`, both assembles, and +`./gradlew detekt` as a step of its own after them. Nothing else. ## Two rules about evidence diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6dcf6eb8..cb527cea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -246,3 +246,22 @@ jobs: name: app-release-unsigned-key path: android/app/build/outputs/apk/release/*.apk if-no-files-found: error + + # Static analysis of the Kotlin (#210): detekt over every module's + # sources, without type resolution, failing on any finding that the + # module's `detekt-baseline.xml` does not already record. docs/build.md, + # "detekt", says what it checks and what it cannot. + # + # A step of its own rather than a fourth task in the invocation above, + # which is where the cost argument would put it. That invocation has no + # `--continue`, and detekt's tasks depend on nothing, so they would run + # first — and one finding would stop Gradle from scheduling the tests at + # all: a style verdict hiding a test verdict. Here it costs the analysis + # itself, under half a minute for the five modules on a laptop, and one + # configuration on the daemon "Test and assemble" left warm. + # + # Last, and `success() || failure()`, so that it still answers on a run + # whose build failed and can never cost a run its APKs. + - name: Detekt + if: success() || failure() + run: ./gradlew detekt diff --git a/CLAUDE.md b/CLAUDE.md index c2ddd6b5..9254b214 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -72,6 +72,12 @@ Android, from `android/`: - `./gradlew :core:model:test --tests '*ScheduleEngineTest*'` — one module, one class - **`./gradlew assembleDebug`** and **`./gradlew assembleRelease`** — CI builds both on every push, because R8 and resource shrinking are where "worked in debug" stops being true +- **`./gradlew detekt`** — static analysis of the Kotlin in all five modules (#210), without + type resolution; fails on any finding the module's `detekt-baseline.xml` does not hold. + Fix a new finding, or `@Suppress` it in place with the reason — the baseline is the past +- `./gradlew detektBaseline` — rewrites all five baselines from the code as it stands; run + it after a merge that moves code between files, because a baseline entry names the file. + `docs/build.md`, "detekt", has the rest - `./gradlew lint` runs the AGP Android lint; CI does not, so do not report it as a gate - `./gradlew :core:designsystem:connectedDebugAndroidTest` — the one instrumented source set (#110), on a running emulator or a connected phone. Not a CI gate: CI has no device, and a diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 57a8c71f..a1c56f5a 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -10,6 +10,18 @@ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.detekt) +} + +detekt { + // What is switched off, and why so little, is written at the top of the + // config; today's findings are this module's `detekt-baseline.xml`. The + // config is named although it sits where the plugin looks by default, + // because the default falls back to detekt's own rules in silence if the + // file ever moves. Named in every module rather than from the root build: + // cross-configuring subprojects is what this build has always avoided. + config.setFrom(rootProject.layout.projectDirectory.file("config/detekt/detekt.yml")) + buildUponDefaultConfig = true } composeCompiler { diff --git a/android/app/detekt-baseline.xml b/android/app/detekt-baseline.xml new file mode 100644 index 00000000..575c72ec --- /dev/null +++ b/android/app/detekt-baseline.xml @@ -0,0 +1,183 @@ +<?xml version="1.0" ?> +<SmellBaseline> + <ManuallySuppressedIssues/> + <CurrentIssues> + <ID>ComplexCondition:SignInPage.kt:!retry && !server && !code && handoff == null</ID> + <ID>ComplexCondition:WeekScreen.kt:!isToday && kind == null && note == null && holiday == null</ID> + <ID>CyclomaticComplexMethod:ClassCardSheet.kt:@Composable private fun SchoolSearchPanel</ID> + <ID>CyclomaticComplexMethod:DayRibbonView.kt:@Composable internal fun DayRibbonView</ID> + <ID>CyclomaticComplexMethod:DiaryAccountPage.kt:@Composable fun DiaryAccountPage</ID> + <ID>CyclomaticComplexMethod:DiaryEditSheet.kt:@Composable internal fun DiaryEditSheet</ID> + <ID>CyclomaticComplexMethod:DiaryProblemText.kt:fun diaryProblemMessage: DiaryProblemMessage</ID> + <ID>CyclomaticComplexMethod:DiaryScreen.kt:@Composable fun DiaryScreen</ID> + <ID>CyclomaticComplexMethod:ImportPage.kt:@Composable internal fun ImportPage</ID> + <ID>CyclomaticComplexMethod:ImportPage.kt:@Composable private fun StageRow</ID> + <ID>CyclomaticComplexMethod:LessonsApp.kt:@Composable private fun HomeShell</ID> + <ID>CyclomaticComplexMethod:ManagementSheets.kt:@Composable fun FormProblem.asText: String</ID> + <ID>CyclomaticComplexMethod:ManagementSheets.kt:@Composable fun ManagementNotice.asText: String</ID> + <ID>CyclomaticComplexMethod:OnboardingScreen.kt:@Composable fun OnboardingScreen</ID> + <ID>CyclomaticComplexMethod:OnboardingViewModel.kt:OnboardingViewModel$private suspend fun entered</ID> + <ID>CyclomaticComplexMethod:OnboardingViewModel.kt:OnboardingViewModel$private suspend fun resolveTarget</ID> + <ID>CyclomaticComplexMethod:ProviderStep.kt:@Composable internal fun ProviderStep</ID> + <ID>CyclomaticComplexMethod:ProviderStep.kt:@Composable private fun ProviderRow</ID> + <ID>CyclomaticComplexMethod:ProviderStep.kt:fun whyLines: List<WhyLine></ID> + <ID>CyclomaticComplexMethod:RegionStep.kt:private fun androidx.compose.foundation.lazy.LazyListScope.schoolAnswer</ID> + <ID>CyclomaticComplexMethod:ReleaseNotes.kt:internal fun parseReleaseNotes: List<NotesBlock></ID> + <ID>CyclomaticComplexMethod:SettingsScreen.kt:@Composable fun SettingsSectionScreen</ID> + <ID>CyclomaticComplexMethod:SignInPage.kt:@Composable internal fun SignInPage</ID> + <ID>CyclomaticComplexMethod:TranslationXml.kt:TranslationXml$fun escape: String</ID> + <ID>CyclomaticComplexMethod:WeekScreen.kt:@Composable private fun MonthCell</ID> + <ID>LongMethod:ClassRows.kt:internal fun LazyListScope.classRows</ID> + <ID>LongMethod:NotificationRows.kt:internal fun LazyListScope.notificationRows</ID> + <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.appearanceRows</ID> + <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.contentRows</ID> + <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.feelRows</ID> + <ID>LongMethod:UpdateRows.kt:internal fun LazyListScope.updateRows</ID> + <ID>LoopWithTooManyJumpStatements:OnboardingFlow.kt:OnboardingFlow$for</ID> + <ID>LoopWithTooManyJumpStatements:ReleaseNotes.kt:for</ID> + <ID>LoopWithTooManyJumpStatements:ResourceTranslationTest.kt:ResourceTranslationTest.Companion$for</ID> + <ID>MagicNumber:BellsSheet.kt:24</ID> + <ID>MagicNumber:BellsSheet.kt:4</ID> + <ID>MagicNumber:BellsSheet.kt:60</ID> + <ID>MagicNumber:ClassCardSheet.kt:3</ID> + <ID>MagicNumber:ClassCardSheet.kt:4</ID> + <ID>MagicNumber:ClassCardSheet.kt:5</ID> + <ID>MagicNumber:DayRibbonView.kt:0.25f</ID> + <ID>MagicNumber:DayRibbonView.kt:0.35f</ID> + <ID>MagicNumber:DayRibbonView.kt:0.5f</ID> + <ID>MagicNumber:DaySheets.kt:3</ID> + <ID>MagicNumber:DaySheets.kt:5</ID> + <ID>MagicNumber:DebugRow.kt:5</ID> + <ID>MagicNumber:DebugSheet.kt:1024</ID> + <ID>MagicNumber:DebugSheet.kt:4</ID> + <ID>MagicNumber:DevicesSheet.kt:4</ID> + <ID>MagicNumber:DevicesSheet.kt:5</ID> + <ID>MagicNumber:DiaryAccountPage.kt:3</ID> + <ID>MagicNumber:DiaryAccountPage.kt:4</ID> + <ID>MagicNumber:DiaryPresentation.kt:3</ID> + <ID>MagicNumber:DiaryPresentation.kt:4</ID> + <ID>MagicNumber:DiaryPresentation.kt:5</ID> + <ID>MagicNumber:DiaryScheduleSection.kt:6</ID> + <ID>MagicNumber:DiaryScreen.kt:3</ID> + <ID>MagicNumber:DiarySignInScreen.kt:4</ID> + <ID>MagicNumber:DocsBlocks.kt:5</ID> + <ID>MagicNumber:DocsScreen.kt:4</ID> + <ID>MagicNumber:Formatting.kt:3</ID> + <ID>MagicNumber:Formatting.kt:4</ID> + <ID>MagicNumber:Formatting.kt:5</ID> + <ID>MagicNumber:Formatting.kt:6</ID> + <ID>MagicNumber:Formatting.kt:60</ID> + <ID>MagicNumber:ImportPage.kt:100</ID> + <ID>MagicNumber:ImportPage.kt:3</ID> + <ID>MagicNumber:JoinScreen.kt:3</ID> + <ID>MagicNumber:JoinScreen.kt:5</ID> + <ID>MagicNumber:JoinViewModel.kt:8</ID> + <ID>MagicNumber:JoinViewModel.kt:JoinError.Companion$59</ID> + <ID>MagicNumber:JoinViewModel.kt:JoinError.Companion$60</ID> + <ID>MagicNumber:ManagementForms.kt:7</ID> + <ID>MagicNumber:NotificationRows.kt:3</ID> + <ID>MagicNumber:NotificationRows.kt:4</ID> + <ID>MagicNumber:NotificationRows.kt:5</ID> + <ID>MagicNumber:NotificationRows.kt:6</ID> + <ID>MagicNumber:OnboardingScreen.kt:3</ID> + <ID>MagicNumber:OnboardingScreen.kt:4</ID> + <ID>MagicNumber:OnboardingScreen.kt:5</ID> + <ID>MagicNumber:RegionFinder.kt:59</ID> + <ID>MagicNumber:RegionFinder.kt:60</ID> + <ID>MagicNumber:RegionStep.kt:3</ID> + <ID>MagicNumber:RibbonSettingsSheet.kt:4</ID> + <ID>MagicNumber:SettingsScreen.kt:3</ID> + <ID>MagicNumber:SettingsScreen.kt:4</ID> + <ID>MagicNumber:SettingsScreen.kt:5</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.ABOUT$5</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.ALERTS$5</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.APPEARANCE$4</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.CONTENT$3</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.DIARY$4</ID> + <ID>MagicNumber:SettingsScreen.kt:SettingsSection.PERMISSIONS$5</ID> + <ID>MagicNumber:SummaryPage.kt:3</ID> + <ID>MagicNumber:SummaryPage.kt:4</ID> + <ID>MagicNumber:SummaryPage.kt:5</ID> + <ID>MagicNumber:TranslationRows.kt:3</ID> + <ID>MagicNumber:TranslationRows.kt:4</ID> + <ID>MagicNumber:TranslationRows.kt:5</ID> + <ID>MagicNumber:UpdateRows.kt:3</ID> + <ID>MagicNumber:UpdateRows.kt:4</ID> + <ID>MagicNumber:UpdateRows.kt:5</ID> + <ID>MagicNumber:WayInStep.kt:3</ID> + <ID>MagicNumber:YearPicker.kt:100</ID> + <ID>MatchingDeclarationName:AboutProvenance.kt:BuildProvenance</ID> + <ID>MatchingDeclarationName:AppPermissions.kt:AppPermission</ID> + <ID>MatchingDeclarationName:DiaryProblemText.kt:DiaryProblemMessage</ID> + <ID>MatchingDeclarationName:JoinTestSupport.kt:JoinRig</ID> + <ID>MatchingDeclarationName:LegalDocumentSheet.kt:LegalLoad</ID> + <ID>MatchingDeclarationName:RootGate.kt:RootScreen</ID> + <ID>MatchingDeclarationName:SettingsScreen.kt:SettingsSection</ID> + <ID>MatchingDeclarationName:SupportSheets.kt:SupportSheetState</ID> + <ID>MaxLineLength:AppCorrections.kt:StringTable$/** `settings_title` for `R.string.settings_title`, or null for anything that cannot be exported as one `<string>`. */</ID> + <ID>MaxLineLength:DiaryPickerViewModelTest.kt:DiaryPickerViewModelTest$private var answer: Result<List<DiarySchool>> = Result.success(listOf(DiarySchool(77, "Школа № 7", "ул. Ленина, 1")))</ID> + <ID>MaxLineLength:DiaryProblemText.kt:if (inClass) R.string.diary_problem_server_refused_session_in_class else R.string.diary_problem_server_refused_session</ID> + <ID>MaxLineLength:DiaryProblemTextTest.kt:DiaryProblemTextTest$assertEquals(Line(R.string.diary_problem_host_timeout, listOf(host)), diaryProblemMessage(DiarySignInProblem.Timeout(host)))</ID> + <ID>MaxLineLength:DiaryProblemTextTest.kt:DiaryProblemTextTest$assertEquals(Line(R.string.diary_problem_server_disabled), diaryProblemMessage(DiarySignInProblem.ServerDisabled))</ID> + <ID>MaxLineLength:DiaryProblemTextTest.kt:DiaryProblemTextTest$assertEquals(Line(R.string.diary_problem_too_many), diaryProblemMessage(DiarySignInProblem.TooManyAttempts(null)))</ID> + <ID>MaxLineLength:DiaryProblemTextTest.kt:DiaryProblemTextTest$assertEquals(Line(R.string.diary_problem_wrong_password), diaryProblemMessage(DiarySignInProblem.WrongPassword(null)))</ID> + <ID>MaxLineLength:ImportRunner.kt:ImportRunner$it.copy(choosing = students.map { student -> StudentUi(student.id, student.shortName, student.className, student.school) })</ID> + <ID>MaxLineLength:ImportRunner.kt:ImportRunner$it.copy(completed = maxOf(it.completed, progress.completed), phase = DiaryImportPhase.CHOOSE_STUDENT)</ID> + <ID>MaxLineLength:JoinScreen.kt:JoinError.InvalidCode -> correctedString(R.string.join_error_invalid_code, ClassCodeLengths.first, ClassCodeLengths.last)</ID> + <ID>MaxLineLength:JoinScreen.kt:text = errorText ?: correctedString(R.string.join_code_hint, ClassCodeLengths.first, ClassCodeLengths.last)</ID> + <ID>MaxLineLength:LegalBuildPropertyTest.kt:LegalBuildPropertyTest$Regex("""assets\.directories \+=\s+rootProject\.layout\.projectDirectory\.dir\("\.\./docs/legal"\)\.asFile\.path""")</ID> + <ID>MaxLineLength:OnboardingCatalog.kt:ProviderPage$get</ID> + <ID>MaxLineLength:OnboardingCatalogTest.kt:OnboardingCatalogTest$val row = providerPageOf(realCatalog, region("volgograd"), school = null).rows.single { it.platform == "tor-myschool" }</ID> + <ID>MaxLineLength:OnboardingFlowTest.kt:OnboardingFlowTest$assertEquals(listOf(IMPORT), OnboardingFlow.resume(ShellMode.DIARY, bindingUsable = false, hasDiarySession = true)?.path)</ID> + <ID>MaxLineLength:OnboardingFlowTest.kt:OnboardingFlowTest$listOf(WELCOME, ACKNOWLEDGEMENT, PREFERENCES, PERMISSIONS, WAY_IN, REGION, SCHOOL, PROVIDER, SIGN_IN, IMPORT, SUMMARY)</ID> + <ID>MaxLineLength:OnboardingRows.kt:container = if (selected) MaterialTheme.colorScheme.rowSelectedContainer else MaterialTheme.colorScheme.rowContainer</ID> + <ID>MaxLineLength:OnboardingViewModel.kt:OnboardingViewModel$set(if (before == OnboardingStep.SCHOOL) OnboardingFlow.back(state) else OnboardingFlow.push(state, OnboardingStep.SCHOOL))</ID> + <ID>MaxLineLength:OnboardingViewModelTest.kt:OnboardingViewModelTest$rig.diarySession = DiarySession(login, "bearer", DiaryTarget.netschool("samara", 239L, "Lyceum 239", login, "Europe/Samara"))</ID> + <ID>MaxLineLength:ProviderStep.kt:correctedString(R.string.onboarding_provider_subtitle, localized(it.regionRu, it.regionEn).orEmpty())</ID> + <ID>MaxLineLength:ProviderStep.kt:val month = surveyMonthText(why.surveyMonth, if (russian) java.util.Locale.forLanguageTag("ru") else java.util.Locale.ENGLISH)</ID> + <ID>MaxLineLength:RegionFinder.kt:is DirectoryProblem.Throttled -> SchoolAnswer.Failed(DirectoryFailure.WAIT, minutesOf(problem.retryAfterSeconds))</ID> + <ID>MaxLineLength:RegionStep.kt:SectionHeader(title = correctedString(R.string.onboarding_region_school_section, search.query.trim()))</ID> + <ID>MaxLineLength:RegionStep.kt:if (search.query.isBlank()) R.string.onboarding_region_all else R.string.onboarding_region_found</ID> + <ID>MaxLineLength:RegionStep.kt:pluralStringResource(R.plurals.onboarding_region_school_count, hit.schools, hit.schools)</ID> + <ID>MaxLineLength:RegionStep.kt:val collator = Collator.getInstance(if (russian) java.util.Locale.forLanguageTag("ru") else java.util.Locale.ENGLISH)</ID> + <ID>MaxLineLength:SignInStep.kt:SignInStep$mutable.update { it.copy(stage = SignInStage.CHECKING, problem = null, dialog = false, sessionHeld = false) }</ID> + <ID>MaxLineLength:SummaryPage.kt:if (settings.settings.debugMode) R.string.onboarding_reports_on else R.string.onboarding_reports_off</ID> + <ID>MaxLineLength:WayInStep.kt:subtitle = correctedString(if (code) R.string.onboarding_way_code_text else R.string.onboarding_way_school_text)</ID> + <ID>MaxLineLength:WayInStep.kt:text = correctedString(if (code) R.string.onboarding_way_code_badge else R.string.onboarding_way_school_badge)</ID> + <ID>NestedBlockDepth:PermissionPromptTest.kt:PermissionPromptTest$@Test fun `every combination resolves to exactly one action`</ID> + <ID>ReturnCount:AppCorrections.kt:AppCorrections$override fun correctionOf: String</ID> + <ID>ReturnCount:BellsSheet.kt:internal fun bellsModeOf: BellsMode</ID> + <ID>ReturnCount:BellsSheet.kt:internal fun decodeBellRows: List<Pair<Int, Int>>?</ID> + <ID>ReturnCount:DeviceClockTest.kt:DeviceClockTest.Companion$fun isExplained: Boolean</ID> + <ID>ReturnCount:DiaryCatalog.kt:internal fun httpsHostOf: String?</ID> + <ID>ReturnCount:DiaryScheduleSection.kt:@Composable private fun DiaryLesson.asTimedLesson: Lesson?</ID> + <ID>ReturnCount:DiaryViewModel.kt:DiaryViewModel$fun resetEdit</ID> + <ID>ReturnCount:DiaryViewModel.kt:DiaryViewModel$fun saveEdit</ID> + <ID>ReturnCount:DiaryViewModel.kt:DiaryViewModel$private suspend fun loadGrades</ID> + <ID>ReturnCount:DiaryViewModel.kt:DiaryViewModel$private suspend fun loadSchedule</ID> + <ID>ReturnCount:DiaryViewModel.kt:DiaryViewModel$private suspend fun loadStudentsNow</ID> + <ID>ReturnCount:ImportRunner.kt:fun stageStateOf: StageState</ID> + <ID>ReturnCount:JoinViewModel.kt:JoinViewModel$fun submit: String?</ID> + <ID>ReturnCount:LinkedSentence.kt:internal fun linkedSentence: AnnotatedString?</ID> + <ID>ReturnCount:MainActivity.kt:private fun Intent.requestedDate: LocalDate?</ID> + <ID>ReturnCount:ManagementForms.kt:fun bellPeriodsProblem: FormProblem?</ID> + <ID>ReturnCount:ManagementForms.kt:fun normaliseSubjectColour: String?</ID> + <ID>ReturnCount:OnboardingCatalog.kt:fun schoolQueryFromHint: String</ID> + <ID>ReturnCount:OnboardingCatalog.kt:private fun shown: Boolean</ID> + <ID>ReturnCount:OnboardingFlow.kt:OnboardingFlow$fun progress: StepProgress?</ID> + <ID>ReturnCount:OnboardingFlow.kt:fun onboardingStateOf: OnboardingState?</ID> + <ID>ReturnCount:OnboardingViewModel.kt:OnboardingViewModel$fun back</ID> + <ID>ReturnCount:SubjectsSheet.kt:internal fun subjectsModeOf: SubjectsMode</ID> + <ID>ReturnCount:TranslationKeys.kt:TranslationKeys$fun entryNameOf: String?</ID> + <ID>TooManyFunctions:DiaryViewModel.kt:DiaryViewModel : ViewModel</ID> + <ID>TooManyFunctions:ManagementForms.kt:com.lumenpearson.lessons.ui.admin.ManagementForms.kt</ID> + <ID>TooManyFunctions:ManagementViewModel.kt:ManagementViewModel : ViewModel</ID> + <ID>TooManyFunctions:OnboardingCatalog.kt:com.lumenpearson.lessons.ui.onboarding.OnboardingCatalog.kt</ID> + <ID>TooManyFunctions:OnboardingFlow.kt:OnboardingFlow</ID> + <ID>TooManyFunctions:OnboardingViewModel.kt:OnboardingViewModel : ViewModel</ID> + <ID>TooManyFunctions:SettingsViewModel.kt:SettingsViewModel : ViewModel</ID> + <ID>TooManyFunctions:WeekViewModel.kt:WeekViewModel : ViewModel</ID> + <ID>UnusedParameter:WeekScreen.kt:date: LocalDate</ID> + <ID>VariableNaming:CorrectionReachTest.kt:CorrectionReachTest$/** * The imports that draw text without asking about corrections. * * `BasicText` is on the classpath, compiles and draws — nothing uses it * today, and nothing stops the next screen from using it either. */ private val OFFENDING_TEXT_IMPORTS = listOf( "import androidx.compose.material3.Text\n", "import androidx.compose.material3.Text as ", "import androidx.compose.foundation.text.BasicText", )</ID> + </CurrentIssues> +</SmellBaseline> diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 67dd6411..79d0f9a8 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -8,4 +8,5 @@ plugins { alias(libs.plugins.kotlin.compose) apply false alias(libs.plugins.kotlin.serialization) apply false alias(libs.plugins.ksp) apply false + alias(libs.plugins.detekt) apply false } diff --git a/android/config/detekt/detekt.yml b/android/config/detekt/detekt.yml new file mode 100644 index 00000000..043778e2 --- /dev/null +++ b/android/config/detekt/detekt.yml @@ -0,0 +1,74 @@ +# detekt, over every Kotlin source set of the five modules (#210). +# +# Every module builds upon detekt's own default configuration +# (`buildUponDefaultConfig = true` in its build file), so this file holds only +# what differs from it, and what differs is short on purpose: the entries below +# are the ones that argue with how Compose is written rather than with how +# this code is written. Everything else is detekt's default, and what the +# defaults find in the code as it stands is recorded, not fixed, in each +# module's `detekt-baseline.xml` — so today's findings pass and a new one does +# not. `./gradlew detektBaseline` rewrites all five; docs/build.md says when. +# +# The build runs detekt without type resolution (docs/build.md says why), and +# in that mode detekt skips every rule that needs the compiler's view of the +# types: 93 of its 213, among them LongParameterList, UnusedImport and +# UnusedPrivateFunction. Two entries below are for such rules and change +# nothing today; they are here so that switching type resolution on does not +# flood every composable with findings that argue with Compose. +# +# Each entry is scoped to an annotation rather than switched off outright, so +# the rule still holds for every function that is not a composable or a +# preview. Without type resolution `ignoreAnnotated` matches the simple name, +# and that is enough: nothing in the tree declares a `Composable` or a +# `Preview` of its own. +# +# The Compose guideline quoted below is androidx's +# compose/docs/compose-api-guidelines.md. + +complexity: + # A composable's body is its layout tree, and a screen's tree is longer than + # sixty lines without being two things. Where one should be split, that is a + # design decision the diff shows, not a line count. + LongMethod: + ignoreAnnotated: ['Composable'] + # Compose asks for the state, the callbacks and the `modifier` as parameters + # of their own, each defaulted where it can be, rather than folded into a + # holder object — which is exactly what this rule would push a composable + # towards. Needs type resolution; inert today (see above). + LongParameterList: + ignoreAnnotated: ['Composable'] + # Compose splits a screen into many small composables, most of them private + # to the screen's file, and that is the advice rather than a smell. Counting + # them would push the other way from LongMethod above. Everything that is + # not a composable — a DAO, a repository, a Retrofit interface — still + # counts. + TooManyFunctions: + ignoreAnnotatedFunctions: ['Composable', 'Preview'] + +naming: + # A composable that returns Unit is named like a type — `LessonRow`, not + # `lessonRow` — which the guideline makes a MUST, and which the compiler + # plugin and every Android tool assume. + FunctionNaming: + ignoreAnnotated: ['Composable'] + # The guideline names a deeply immutable constant in PascalCase — + # `ModeFadeMillis` — in place of CAPITALS_AND_UNDERSCORES, and 141 of this + # tree's 171 top-level `const val`s are written that way. Both spellings + # pass, because the other 30 are the ordinary Kotlin one and the guideline + # allows local consistency with it. detekt's own default already lets a + # PascalCase constant through inside an object; only the top-level pattern + # did not. + TopLevelPropertyNaming: + constantPattern: '[A-Z][_A-Za-z0-9]*' + +style: + # A preview is sample data — `LocalTime.of(9, 40)`, `Duration.ofMinutes(30)`, + # the fifth accent tone — and naming each of those numbers would add + # constants nothing but the preview reads. + MagicNumber: + ignoreAnnotated: ['Preview'] + # A preview is private and called by nothing in the source — Android + # Studio's tooling finds it by the annotation — so to this rule every one of + # them is dead code. Needs type resolution; inert today (see above). + UnusedPrivateFunction: + ignoreAnnotated: ['Preview'] diff --git a/android/core/data/build.gradle.kts b/android/core/data/build.gradle.kts index ef406562..60cf2c4c 100644 --- a/android/core/data/build.gradle.kts +++ b/android/core/data/build.gradle.kts @@ -2,6 +2,18 @@ plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.serialization) alias(libs.plugins.ksp) + alias(libs.plugins.detekt) +} + +detekt { + // What is switched off, and why so little, is written at the top of the + // config; today's findings are this module's `detekt-baseline.xml`. The + // config is named although it sits where the plugin looks by default, + // because the default falls back to detekt's own rules in silence if the + // file ever moves. Named in every module rather than from the root build: + // cross-configuring subprojects is what this build has always avoided. + config.setFrom(rootProject.layout.projectDirectory.file("config/detekt/detekt.yml")) + buildUponDefaultConfig = true } /** A folder of the repository outside `android/`, as the path `directories` takes. */ diff --git a/android/core/data/detekt-baseline.xml b/android/core/data/detekt-baseline.xml new file mode 100644 index 00000000..35807e58 --- /dev/null +++ b/android/core/data/detekt-baseline.xml @@ -0,0 +1,210 @@ +<?xml version="1.0" ?> +<SmellBaseline> + <ManuallySuppressedIssues/> + <CurrentIssues> + <ID>CyclomaticComplexMethod:DiaryImportImpl.kt:DiaryImportImpl$private suspend fun FlowCollector<DiaryImportProgress>.import</ID> + <ID>CyclomaticComplexMethod:DiarySignInProblem.kt:DiarySignInProblem.Companion$private fun ofServer: DiarySignInProblem</ID> + <ID>CyclomaticComplexMethod:GithubRepositoryImpl.kt:GithubRepositoryImpl$override suspend fun openTranslationPullRequest: PullRequestResult</ID> + <ID>CyclomaticComplexMethod:LessonsPreferences.kt:LessonsPreferences$private fun Preferences.toSettings: AppSettings</ID> + <ID>CyclomaticComplexMethod:RegionSearch.kt:RegionSearch$private fun score: RegionMatch?</ID> + <ID>CyclomaticComplexMethod:TimetableRepositoryImpl.kt:TimetableRepositoryImpl$private suspend fun fetchYear: SyncResult</ID> + <ID>LongMethod:BundleJsonTest.kt:BundleJsonTest$@Test fun serverPayload_decodesAndMapsToDomain</ID> + <ID>LongMethod:DiaryImportImpl.kt:DiaryImportImpl$private suspend fun FlowCollector<DiaryImportProgress>.import</ID> + <ID>LongMethod:DtoMappersTest.kt:DtoMappersTest$@Test fun normalDay_mapsEveryFieldAndSortsTheTimeline</ID> + <ID>LongMethod:LessonsPreferences.kt:LessonsPreferences$override suspend fun updateSettings</ID> + <ID>LongMethod:LessonsPreferences.kt:LessonsPreferences$private fun Preferences.toSettings: AppSettings</ID> + <ID>LongMethod:TimetableRepositoryImpl.kt:TimetableRepositoryImpl$private suspend fun fetchYear: SyncResult</ID> + <ID>LoopWithTooManyJumpStatements:DiaryProtocolVectorsTest.kt:DiaryProtocolVectorsTest$for</ID> + <ID>LoopWithTooManyJumpStatements:GithubRepositoryImpl.kt:GithubRepositoryImpl$for</ID> + <ID>LoopWithTooManyJumpStatements:UpstreamDirectory.kt:CatalogUpstreamDirectory$for</ID> + <ID>MagicNumber:DiaryImport.kt:DiaryImportPhase.HOMEWORK$0.25f</ID> + <ID>MagicNumber:DiaryImport.kt:DiaryImportPhase.MARKS$0.25f</ID> + <ID>MagicNumber:DiaryImport.kt:DiaryImportPhase.PERIODS$0.10f</ID> + <ID>MagicNumber:DiaryImport.kt:DiaryImportPhase.SCHEDULE$0.30f</ID> + <ID>MagicNumber:DiaryImport.kt:DiaryImportPhase.STUDENTS$0.10f</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$401</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$404</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$422</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$429</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$502</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$503</ID> + <ID>MagicNumber:DiaryModels.kt:DiaryFailure.Companion$504</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$401</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$403</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$409</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$422</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$429</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$502</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$503</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$504</ID> + <ID>MagicNumber:DiarySignInProblem.kt:DiarySignInProblem.Companion$8</ID> + <ID>MagicNumber:DocsMarkdown.kt:DocsMarkdown$3</ID> + <ID>MagicNumber:EntityMappers.kt:3</ID> + <ID>MagicNumber:EntityMappers.kt:4</ID> + <ID>MagicNumber:GithubRepositoryImpl.kt:1000L</ID> + <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$403</ID> + <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$404</ID> + <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$429</ID> + <ID>MagicNumber:LessonsPreferences.kt:LessonsPreferences$7</ID> + <ID>MagicNumber:LocaleOverride.kt:33</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$401</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$403</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$404</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$409</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$422</ID> + <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$503</ID> + <ID>MagicNumber:Mappers.kt:11</ID> + <ID>MagicNumber:NetSchoolPassword.kt:Cp1251$0x80</ID> + <ID>MagicNumber:NetSchoolPassword.kt:NetSchoolPassword$32</ID> + <ID>MagicNumber:NetSchoolPassword.kt:NetSchoolPassword$4</ID> + <ID>MagicNumber:NetSchoolSignIn.kt:NetSchoolSignIn$0x80</ID> + <ID>MagicNumber:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$403</ID> + <ID>MagicNumber:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$409</ID> + <ID>MagicNumber:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$429</ID> + <ID>MagicNumber:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$500</ID> + <ID>MagicNumber:NetworkModule.kt:NetworkModule$15</ID> + <ID>MagicNumber:NetworkModule.kt:NetworkModule$30</ID> + <ID>MagicNumber:NetworkModule.kt:NetworkModule$60</ID> + <ID>MagicNumber:PetersburgSignIn.kt:PetersburgSignIn.Companion$400</ID> + <ID>MagicNumber:PetersburgSignIn.kt:PetersburgSignIn.Companion$401</ID> + <ID>MagicNumber:PetersburgSignIn.kt:PetersburgSignIn.Companion$403</ID> + <ID>MagicNumber:PetersburgSignIn.kt:PetersburgSignIn.Companion$500</ID> + <ID>MagicNumber:RegionSearch.kt:RegionSearch$3</ID> + <ID>MagicNumber:RegionSearch.kt:RegionSearch$4</ID> + <ID>MagicNumber:RegionSearch.kt:RegionSearch$6</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$404</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$422</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$429</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$503</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$504</ID> + <ID>MagicNumber:SchoolDirectory.kt:DirectoryProblem.Companion$8</ID> + <ID>MagicNumber:UpstreamFailure.kt:8</ID> + <ID>MagicNumber:UpstreamHttp.kt:UpstreamHttp$10</ID> + <ID>MagicNumber:UpstreamHttp.kt:UpstreamHttp$20</ID> + <ID>MagicNumber:UpstreamHttp.kt:UpstreamHttp$40</ID> + <ID>MatchingDeclarationName:BearerTestSupport.kt:BearerHarness</ID> + <ID>MatchingDeclarationName:Converters.kt:LessonsTypeConverters</ID> + <ID>MaxLineLength:DiaryCache.kt:DiaryCacheWriter$suspend</ID> + <ID>MaxLineLength:DiaryCacheTest.kt:DiaryCacheTest$DiaryPeriodDto(id = 11, name = "II", startsOn = "2026-11-05", endsOn = "2026-12-28", isCurrent = true)</ID> + <ID>MaxLineLength:DiaryDaoPolicyTest.kt:DiaryDaoPolicyTest.Companion$val TABLES = listOf("diary_student", "diary_week", "diary_period", "diary_lesson", "diary_homework", "diary_mark")</ID> + <ID>MaxLineLength:DiaryImportTest.kt:DiaryImportTest$assertTrue(rig.cache.marks(1).first().covers(DiaryWindows.gradeWindow(rig.clock.today(), rig.cache.periods(1).first().periods.single())))</ID> + <ID>MaxLineLength:DiaryImportTest.kt:DiaryImportTest$periods = listOf(DiaryPeriodDto(id = 7, name = "I", startsOn = "2026-09-01", endsOn = "2026-10-26", isCurrent = true))</ID> + <ID>MaxLineLength:DiaryImportTest.kt:DiaryImportTest.ClearingSignIn$/** A sign-in that does what [com.lumenpearson.lessons.core.data.repository.DiarySignInImpl] does for a new account: empties the cache, then answers. */</ID> + <ID>MaxLineLength:DiaryImportTest.kt:DiaryImportTest.ClearingSignIn$override suspend fun register</ID> + <ID>MaxLineLength:DiaryImportTest.kt:DiaryImportTest.ClearingSignIn$return Result.success(com.lumenpearson.lessons.core.data.repository.DiaryRegistration(session, listOf(pupil(1))))</ID> + <ID>MaxLineLength:DiaryJsonTest.kt:DiaryJsonTest$credential</ID> + <ID>MaxLineLength:DiaryProtocolVectorsTest.kt:DiaryProtocolVectorsTest$assertEquals(Vectors.petersburg.getValue("session_cookie").jsonPrimitive.content, PetersburgSignIn.SESSION_COOKIE)</ID> + <ID>MaxLineLength:DiaryRepositoryTest.kt:DiaryRepositoryTest.FakeApi$override suspend fun capabilities: DiaryCapabilitiesDto</ID> + <ID>MaxLineLength:DiarySignInProblemTest.kt:DiarySignInProblemTest$row("read address refused", DiaryFailure.ServerAddressRefused, DiarySignInProblem.ServerAddressRefused, Action.NONE)</ID> + <ID>MaxLineLength:DiarySignInTest.kt:DiarySignInTest$assertEquals("42", script.to(NetSchoolSignIn.LOGIN_PATH).single().body!!.utf8().substringAfter("scid=").substringBefore('&'))</ID> + <ID>MaxLineLength:DiarySignInTest.kt:DiarySignInTest$providers = DiaryProvidersDto(petersburg = JsonObject(emptyMap()), netschool = NetSchoolCapabilitiesDto(regions))</ID> + <ID>MaxLineLength:DiaryTestSupport.kt:InMemoryDiaryDao$override suspend fun deleteHomeworkOtherThan</ID> + <ID>MaxLineLength:DiaryTestSupport.kt:InMemoryDiaryDao$weeks.replaceAll { if (it.studentId == studentId && it.monday in mondays) it.copy(homeworkSyncedAt = at) else it }</ID> + <ID>MaxLineLength:DiaryTestSupport.kt:InMemoryDiaryDao$weeks.replaceAll { if (it.studentId == studentId && it.monday in mondays) it.copy(lessonsSyncedAt = at) else it }</ID> + <ID>MaxLineLength:DiaryTestSupport.kt:internal fun lesson</ID> + <ID>MaxLineLength:DiaryTestSupport.kt:internal fun mark</ID> + <ID>MaxLineLength:MembershipsTest.kt:MembershipsTest$"""{"classId":3,"className":"5В","token":"t3","diary":{"provider":"netschool","schoolId":"not a number"}}]"""</ID> + <ID>MaxLineLength:NetSchoolSignInTest.kt:NetSchoolSignInTest$.</ID> + <ID>MaxLineLength:NetSchoolSignInTest.kt:NetSchoolSignInTest$val script = NetSchoolScript(logindata = { jsonAnswer(200, Json.parseToJsonElement("""{"schoolLogin":false}""")) })</ID> + <ID>MaxLineLength:PetersburgSignInTest.kt:PetersburgSignInTest$server.enqueue(rawAnswer(200, "application/json", """{"data":{"token":"body"}}""", listOf("X-JWT-Token=cookie.jwt.value; Path=/")))</ID> + <ID>MaxLineLength:SchoolDirectory.kt:DirectoryProblem.Companion$if</ID> + <ID>MaxLineLength:SyncWorkerSourceTest.kt:SyncWorkerSourceTest$assertTrue("$name is declared, but its source is not at ${file.path}; teach this test where it is", file.isFile)</ID> + <ID>MaxLineLength:SyncWorkerSourceTest.kt:SyncWorkerSourceTest.Companion$val</ID> + <ID>MaxLineLength:UpstreamDirectoryTest.kt:UpstreamDirectoryTest$assertEquals(setOf("altai-krai", "primorye", "tula"), netschool.filterNot { it.password }.map { it.region }.toSet())</ID> + <ID>MaxLineLength:UpstreamDirectoryTest.kt:UpstreamDirectoryTest$assertTrue(UpstreamOrigin("https", "netcity.admsakhalin.ru", 11111) in CatalogUpstreamDirectory(bundled).allowedOrigins())</ID> + <ID>MaxLineLength:UpstreamDirectoryTest.kt:UpstreamDirectoryTest$val none = CatalogUpstreamDirectory(RegionCatalog(platforms = mapOf("x" to CatalogPlatform(provider = "netschool"))))</ID> + <ID>MaxLineLength:UpstreamFailure.kt:UpstreamNotAllowed$class</ID> + <ID>MaxLineLength:UpstreamHttpTest.kt:UpstreamHttpTest$.</ID> + <ID>MaxLineLength:UpstreamHttpTest.kt:UpstreamHttpTest$handshake("PKIX path building failed", CertificateException("PKIX", CertPathBuilderException("unable to find path")))</ID> + <ID>MaxLineLength:UpstreamHttpTest.kt:UpstreamHttpTest$handshake("Read error: ssl=0x7b: I/O error during system call, Connection reset by peer", SocketException("Connection reset"))</ID> + <ID>MaxLineLength:UpstreamTestSupport.kt:NetSchoolScript$jsonAnswer(200, Vectors.flow.getValue("logindata"), "Set-Cookie" to "NSSESSIONID=$SCRIPT_SESSION_COOKIE; Path=/")</ID> + <ID>MaxLineLength:UpstreamTestSupport.kt:internal</ID> + <ID>ReturnCount:AlertNotifier.kt:AlertNotifier$private fun postIn</ID> + <ID>ReturnCount:AppLocale.kt:AppLocale$@SuppressLint("AppBundleLocaleChanges") fun localized: Context</ID> + <ID>ReturnCount:AuthInterceptor.kt:AuthInterceptor$override fun intercept: Response</ID> + <ID>ReturnCount:CrashReporter.kt:CrashReporter$internal fun reportFile: File</ID> + <ID>ReturnCount:DiaryAuthInterceptor.kt:DiaryAuthInterceptor$override fun intercept: Response</ID> + <ID>ReturnCount:DiaryCache.kt:DiaryEditsCodec$fun decode: List<DiaryEdit></ID> + <ID>ReturnCount:DiaryImportImpl.kt:DiaryImportImpl$override suspend fun refreshIfStale: Result<Boolean></ID> + <ID>ReturnCount:DiaryImportImpl.kt:DiaryImportImpl$private suspend fun FlowCollector<DiaryImportProgress>.import</ID> + <ID>ReturnCount:DiaryMappers.kt:internal fun DiaryHomeworkDto.toDomain: DiaryHomework?</ID> + <ID>ReturnCount:DiaryMappers.kt:internal fun DiaryOverrideDto.toDomain: DiaryOverrideRecord?</ID> + <ID>ReturnCount:DiarySignInImpl.kt:DiarySignInImpl$override suspend fun signIn: Result<DiaryRegistration></ID> + <ID>ReturnCount:DiarySignInImpl.kt:DiarySignInImpl$private fun requestFor: DiarySessionRequestDto?</ID> + <ID>ReturnCount:DiaryTarget.kt:DiaryTargetCodec$fun decode: DiaryTarget?</ID> + <ID>ReturnCount:DocsMarkdown.kt:DocsMarkdown$internal fun spans: List<DocsSpan></ID> + <ID>ReturnCount:DocsMarkdown.kt:DocsMarkdown.GuideBuilder$fun read: Boolean</ID> + <ID>ReturnCount:DocsRepositoryImpl.kt:DocsRepositoryImpl$private fun bundled: DocsLibrary?</ID> + <ID>ReturnCount:DocsRepositoryImpl.kt:DocsRepositoryImpl$private suspend fun fetch: Outcome</ID> + <ID>ReturnCount:GithubPreferences.kt:GithubPreferences$private fun Preferences.toAccount: GithubAccount?</ID> + <ID>ReturnCount:GithubRepositoryImpl.kt:GithubRepositoryImpl$private suspend fun contents: Pair<String, String>?</ID> + <ID>ReturnCount:GithubRepositoryImpl.kt:GithubRepositoryImpl$private suspend fun ensureFork: Boolean</ID> + <ID>ReturnCount:GithubRepositoryImpl.kt:internal suspend fun pollUntilDecided: PollVerdict</ID> + <ID>ReturnCount:LegalDocuments.kt:internal fun LegalManifest.toEdition: LegalEdition?</ID> + <ID>ReturnCount:LegalDocuments.kt:internal fun readLegal: LegalText?</ID> + <ID>ReturnCount:LessonsPreferences.kt:internal fun Preferences.toDiarySession: DiarySession?</ID> + <ID>ReturnCount:LessonsPreferences.kt:internal fun Preferences.toDiaryTarget: DiaryTarget?</ID> + <ID>ReturnCount:LocaleOverride.kt:fun localeOverrideFor: List<String>?</ID> + <ID>ReturnCount:ManageMappers.kt:internal fun BellPeriodDto.toDomain: BellPeriod?</ID> + <ID>ReturnCount:ManageMappers.kt:private fun wallTime: LocalDateTime?</ID> + <ID>ReturnCount:ManageModels.kt:ManageFailure.Companion$fun detailOf: String?</ID> + <ID>ReturnCount:Mappers.kt:internal fun EventDto.toDomain: SchoolEvent?</ID> + <ID>ReturnCount:Mappers.kt:internal fun LessonDto.toDomain: Lesson?</ID> + <ID>ReturnCount:Mappers.kt:internal fun TermDto.toDomain: Term?</ID> + <ID>ReturnCount:Memberships.kt:internal fun Preferences.memberships: List<Session></ID> + <ID>ReturnCount:Memberships.kt:private fun storedBinding: DiaryBinding?</ID> + <ID>ReturnCount:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$fun loginMessage: String?</ID> + <ID>ReturnCount:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$fun looksRefused: Boolean</ID> + <ID>ReturnCount:PetersburgSignIn.kt:PetersburgSignIn.Companion$private fun firstError: String?</ID> + <ID>ReturnCount:RegionSearch.kt:RegionSearch$fun looksLikeSchool: Boolean</ID> + <ID>ReturnCount:RegionSearch.kt:RegionSearch$private fun score: RegionMatch?</ID> + <ID>ReturnCount:StringsDocument.kt:StringsDocument$fun replace: String?</ID> + <ID>ReturnCount:StringsDocument.kt:StringsDocument$private fun openingTagOf: Int?</ID> + <ID>ReturnCount:TimetableRepositoryImpl.kt:TimetableRepositoryImpl$private suspend fun fetchYear: SyncResult</ID> + <ID>ReturnCount:UpstreamJson.kt:UpstreamJson$fun integer: BigInteger?</ID> + <ID>ReturnCount:UpstreamJson.kt:UpstreamJson$fun parse: JsonElement?</ID> + <ID>ReturnCount:UpstreamJson.kt:UpstreamJson$fun scalarText: String</ID> + <ID>SwallowedException:GithubRepositoryImpl.kt:unreachable: IOException</ID> + <ID>SwallowedException:SingleFlight.kt:SingleFlight$cancelled: CancellationException</ID> + <ID>SwallowedException:TimetableRepositoryImpl.kt:TimetableRepositoryImpl$missing: ServerAddressMissingException</ID> + <ID>SwallowedException:UpstreamHttpTest.kt:UpstreamHttpTest$refused: UpstreamNotAllowed</ID> + <ID>ThrowsCount:DiarySignInImpl.kt:DiarySignInImpl$private fun endpoint: Endpoint</ID> + <ID>ThrowsCount:NetSchoolSignIn.kt:NetSchoolSignIn$private suspend fun passwordLogin: Outcome</ID> + <ID>ThrowsCount:NetSchoolSignIn.kt:NetSchoolSignIn$suspend fun signIn: UpstreamSession.NetSchool</ID> + <ID>ThrowsCount:NetSchoolSignIn.kt:NetSchoolSignIn.Companion$fun consumeLogin: Outcome</ID> + <ID>ThrowsCount:PetersburgSignIn.kt:PetersburgSignIn.Companion$fun read: String</ID> + <ID>TooGenericExceptionCaught:DeviceLinkRepositoryImpl.kt:DeviceLinkRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:DiaryImportImpl.kt:DiaryImportImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:DiaryRepositoryImpl.kt:DiaryRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:DiarySignInImpl.kt:DiarySignInImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:GithubApi.kt:GithubApi$failure: Exception</ID> + <ID>TooGenericExceptionCaught:GithubRepositoryImpl.kt:GithubRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:GithubRepositoryImpl.kt:GithubRepositoryImpl$failure: Throwable</ID> + <ID>TooGenericExceptionCaught:ManageRepositoryImpl.kt:ManageRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:NetSchoolSchoolSearch.kt:NetSchoolSchoolSearch$failure: Exception</ID> + <ID>TooGenericExceptionCaught:SchoolAlertReceiver.kt:SchoolAlertReceiver$error: Throwable</ID> + <ID>TooGenericExceptionCaught:SchoolDirectory.kt:ServerSchoolDirectory$failure: Exception</ID> + <ID>TooGenericExceptionCaught:SessionRepositoryImpl.kt:SessionRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:SingleFlight.kt:SingleFlight$failure: Throwable</ID> + <ID>TooGenericExceptionCaught:TimetableRepositoryImpl.kt:TimetableRepositoryImpl$unexpected: Exception</ID> + <ID>TooGenericExceptionCaught:UpdateRepositoryImpl.kt:UpdateRepositoryImpl$failure: Exception</ID> + <ID>TooGenericExceptionCaught:UpdateRepositoryImpl.kt:UpdateRepositoryImpl$failure: Throwable</ID> + <ID>TooManyFunctions:AlertNotifier.kt:AlertNotifier</ID> + <ID>TooManyFunctions:CrashReporter.kt:CrashReporter</ID> + <ID>TooManyFunctions:DiaryApi.kt:DiaryApi</ID> + <ID>TooManyFunctions:DiaryCacheImpl.kt:DiaryCacheImpl : DiaryCacheDiaryCacheWriter</ID> + <ID>TooManyFunctions:DiaryDao.kt:DiaryDao</ID> + <ID>TooManyFunctions:DiaryRepository.kt:DiaryRepository</ID> + <ID>TooManyFunctions:DiaryRepositoryImpl.kt:DiaryRepositoryImpl : DiaryRepository</ID> + <ID>TooManyFunctions:GithubRepositoryImpl.kt:GithubRepositoryImpl : GithubRepository</ID> + <ID>TooManyFunctions:LessonsPreferences.kt:LessonsPreferences : DiarySessionStoreShellModeSourceSettingsStore</ID> + <ID>TooManyFunctions:ManageApi.kt:ManageApi</ID> + <ID>TooManyFunctions:ManageMappers.kt:com.lumenpearson.lessons.core.data.repository.ManageMappers.kt</ID> + <ID>TooManyFunctions:ManageRepository.kt:ManageRepository</ID> + <ID>TooManyFunctions:ManageRepositoryImpl.kt:ManageRepositoryImpl : ManageRepository</ID> + <ID>TooManyFunctions:RegionSearch.kt:RegionSearch</ID> + <ID>TooManyFunctions:SchoolAlerts.kt:SchoolAlerts</ID> + <ID>TooManyFunctions:TimetableDao.kt:TimetableDao</ID> + <ID>TooManyFunctions:TimetableRepositoryImpl.kt:TimetableRepositoryImpl : TimetableRepositoryTimetableCache</ID> + </CurrentIssues> +</SmellBaseline> diff --git a/android/core/designsystem/build.gradle.kts b/android/core/designsystem/build.gradle.kts index 69f2aad6..46ed1dc1 100644 --- a/android/core/designsystem/build.gradle.kts +++ b/android/core/designsystem/build.gradle.kts @@ -3,6 +3,21 @@ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.detekt) +} + +detekt { + // What is switched off, and why so little, is written at the top of the + // config; today's findings are this module's `detekt-baseline.xml`. The + // config is named although it sits where the plugin looks by default, + // because the default falls back to detekt's own rules in silence if the + // file ever moves. Named in every module rather than from the root build: + // cross-configuring subprojects is what this build has always avoided. + config.setFrom(rootProject.layout.projectDirectory.file("config/detekt/detekt.yml")) + buildUponDefaultConfig = true + // The plain task reads `src/main` and `src/test` and nothing else, and this + // is the one module with instrumented tests (#110). + source.from("src/androidTest/kotlin") } composeCompiler { diff --git a/android/core/designsystem/detekt-baseline.xml b/android/core/designsystem/detekt-baseline.xml new file mode 100644 index 00000000..ca2c5223 --- /dev/null +++ b/android/core/designsystem/detekt-baseline.xml @@ -0,0 +1,79 @@ +<?xml version="1.0" ?> +<SmellBaseline> + <ManuallySuppressedIssues/> + <CurrentIssues> + <ID>ComplexCondition:ProgressiveBlur.kt:Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && blurRadius > 0f && (topHeight > 0f || bottomHeight > 0f) && !isPowerSave && !isBlurProblematicDevice()</ID> + <ID>CyclomaticComplexMethod:FloatingToolbar.kt:@Composable private fun ToolbarTab</ID> + <ID>LoopWithTooManyJumpStatements:ToolbarArrangeGesture.kt:while</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.0001f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.0722f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.20f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.2126f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.34f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.38f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.46f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.55f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.62f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.66f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.7152f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.72f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.74f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$0.90f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$120f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$180f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$240f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$300f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$31</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$360f</ID> + <ID>MagicNumber:AccentMath.kt:AccentMath$60f</ID> + <ID>MagicNumber:Color.kt:0xFF000000L</ID> + <ID>MagicNumber:Color.kt:6</ID> + <ID>MagicNumber:Color.kt:8</ID> + <ID>MagicNumber:EmptyState.kt:3</ID> + <ID>MagicNumber:Formatting.kt:100f</ID> + <ID>MagicNumber:LessonsDialog.kt:LessonsDialogTone$3</ID> + <ID>MagicNumber:RibbonSheen.kt:RibbonSheenLayer$1000f</ID> + <ID>MagicNumber:SchoolBell.kt:0.06f</ID> + <ID>MagicNumber:SchoolBell.kt:0.08f</ID> + <ID>MagicNumber:SchoolBell.kt:0.10f</ID> + <ID>MagicNumber:SchoolBell.kt:0.13f</ID> + <ID>MagicNumber:SchoolBell.kt:0.16f</ID> + <ID>MagicNumber:SchoolBell.kt:0.44f</ID> + <ID>MagicNumber:SchoolBell.kt:0.5f</ID> + <ID>MagicNumber:SchoolBell.kt:0.70f</ID> + <ID>MagicNumber:SchoolBell.kt:0.88f</ID> + <ID>MagicNumber:SchoolBell.kt:0.92f</ID> + <ID>MagicNumber:ScrollMotionBlur.kt:0.01f</ID> + <ID>MagicNumber:ScrollMotionBlur.kt:0.1f</ID> + <ID>MagicNumber:Skeleton.kt:0.2f</ID> + <ID>MagicNumber:Type.kt:0.15f</ID> + <ID>MagicNumber:Type.kt:0.1f</ID> + <ID>MagicNumber:Type.kt:0.25f</ID> + <ID>MagicNumber:Type.kt:0.4f</ID> + <ID>MagicNumber:Type.kt:0.5f</ID> + <ID>MagicNumber:Type.kt:11f</ID> + <ID>MagicNumber:Type.kt:12f</ID> + <ID>MagicNumber:Type.kt:14f</ID> + <ID>MagicNumber:Type.kt:16f</ID> + <ID>MagicNumber:Type.kt:20f</ID> + <ID>MagicNumber:Type.kt:22f</ID> + <ID>MagicNumber:Type.kt:24f</ID> + <ID>MagicNumber:Type.kt:28f</ID> + <ID>MagicNumber:Type.kt:32f</ID> + <ID>MagicNumber:Type.kt:36f</ID> + <ID>MagicNumber:Type.kt:40f</ID> + <ID>MagicNumber:Type.kt:44f</ID> + <ID>MagicNumber:Type.kt:45f</ID> + <ID>MagicNumber:Type.kt:52f</ID> + <ID>MagicNumber:Type.kt:57f</ID> + <ID>MagicNumber:Type.kt:64f</ID> + <ID>MatchingDeclarationName:Accents.kt:AccentTone</ID> + <ID>MatchingDeclarationName:LiquidRippleHost.kt:LiquidRippleState</ID> + <ID>MatchingDeclarationName:Markup.kt:MarkupStyles</ID> + <ID>MatchingDeclarationName:RibbonSheen.kt:RibbonDepthLevel</ID> + <ID>ReturnCount:Color.kt:fun parseSubjectColor: Color?</ID> + <ID>ReturnCount:Corrections.kt:@Composable fun Modifier.correctable: Modifier</ID> + <ID>ReturnCount:ToolbarArrangeGesture.kt:private suspend fun AwaitPointerEventScope.awaitSideways: Boolean</ID> + <ID>ReturnCount:ToolbarReorder.kt:internal fun <T> moveItem: List<T></ID> + </CurrentIssues> +</SmellBaseline> diff --git a/android/core/model/build.gradle.kts b/android/core/model/build.gradle.kts index ef40a1cd..6b36c971 100644 --- a/android/core/model/build.gradle.kts +++ b/android/core/model/build.gradle.kts @@ -1,5 +1,17 @@ plugins { alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.detekt) +} + +detekt { + // What is switched off, and why so little, is written at the top of the + // config; today's findings are this module's `detekt-baseline.xml`. The + // config is named although it sits where the plugin looks by default, + // because the default falls back to detekt's own rules in silence if the + // file ever moves. Named in every module rather than from the root build: + // cross-configuring subprojects is what this build has always avoided. + config.setFrom(rootProject.layout.projectDirectory.file("config/detekt/detekt.yml")) + buildUponDefaultConfig = true } // Pure JVM on purpose: the schedule engine is the most logic-dense part of the diff --git a/android/core/model/detekt-baseline.xml b/android/core/model/detekt-baseline.xml new file mode 100644 index 00000000..1956078f --- /dev/null +++ b/android/core/model/detekt-baseline.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" ?> +<SmellBaseline> + <ManuallySuppressedIssues/> + <CurrentIssues> + <ID>ComplexCondition:AlertPlanner.kt:AlertPlanner$preferences.morningSummary && day.hasLessons && !skipped && date.dayOfWeek.value in preferences.morningWeekdays</ID> + <ID>CyclomaticComplexMethod:AlertPlanner.kt:AlertPlanner$private fun candidates: List<SchoolAlert></ID> + <ID>LongMethod:ScheduleEngine.kt:ScheduleEngine$fun stateAt: DayState</ID> + <ID>MagicNumber:AlertPlanner.kt:AlertPlanner$60L</ID> + <ID>MagicNumber:SchoolYear.kt:SchoolYear$31</ID> + <ID>ReturnCount:AlertPlanner.kt:AlertPreferences$fun isQuiet: Boolean</ID> + <ID>ReturnCount:AppVersion.kt:AppVersion.Companion$fun isNewer: Boolean</ID> + <ID>ReturnCount:AppVersion.kt:AppVersion.Companion$fun parse: AppVersion?</ID> + <ID>ReturnCount:AppVersion.kt:AppVersion.Companion$private fun compareIdentifiers: Int</ID> + <ID>ReturnCount:DayFilter.kt:fun SchoolDay?.matches: Boolean</ID> + <ID>ReturnCount:DayRibbon.kt:fun progressOf: RibbonProgress</ID> + <ID>ReturnCount:ScheduleEngine.kt:ScheduleEngine$fun stateAt: DayState</ID> + <ID>ReturnCount:StabilityPromiseTest.kt:StabilityPromiseTest$private fun reasonTypeIsNotPromised: String?</ID> + </CurrentIssues> +</SmellBaseline> diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index f10f361c..d329a05b 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -19,6 +19,21 @@ # InputManager.getInstance by reflection, which API 34 removed: every # test failed at its first Espresso.onIdle on the API 37 emulator. # +# detekt -> the maven-metadata.xml of dev.detekt:detekt-gradle-plugin on +# Maven Central and of the dev.detekt plugin marker on the Gradle Plugin +# Portal, both read on 27 September 2026, where 2.0.0-alpha.6 (released +# 4 August 2026) is the <release> and no 2.0.0 exists yet. Its release +# notes (GitHub, detekt/detekt, v2.0.0-alpha.6) say it is built against +# Kotlin 2.4.10, Gradle 9.6.1 and AGP 9.3.1. Of the alphas before it, +# alpha.3 is the first to support AGP 9's built-in Kotlin without it +# being switched off in gradle.properties, and alpha.4 the first built +# against Kotlin 2.4. The 1.x line (io.gitlab.arturbosch.detekt) ends at +# 1.23.8, built against Kotlin 2.0.21 and AGP 8.8. detekt runs on the +# compiler it was built with — detekt-cli's own kotlin-compiler 2.4.10, +# in a configuration of its own — and refuses to start on any other, so +# this build's 2.4.20 never reaches it unless something aligns Kotlin +# versions across every configuration, which nothing here does. +# # The first CI run failed on invented versions (room 2.9.2, navigation 2.9.6, # okhttp 5.2.0, kotlinx-serialization-json 1.9.1) that do not exist in any # repository. Verify a version against its repository before adding it here. @@ -52,6 +67,8 @@ robolectric = "4.17" espresso = "3.7.0" androidxTestRunner = "1.7.0" +detekt = "2.0.0-alpha.6" + [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } @@ -104,3 +121,4 @@ kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } +detekt = { id = "dev.detekt", version.ref = "detekt" } diff --git a/android/widget/build.gradle.kts b/android/widget/build.gradle.kts index fb091977..3c032986 100644 --- a/android/widget/build.gradle.kts +++ b/android/widget/build.gradle.kts @@ -1,6 +1,18 @@ plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.detekt) +} + +detekt { + // What is switched off, and why so little, is written at the top of the + // config; today's findings are this module's `detekt-baseline.xml`. The + // config is named although it sits where the plugin looks by default, + // because the default falls back to detekt's own rules in silence if the + // file ever moves. Named in every module rather than from the root build: + // cross-configuring subprojects is what this build has always avoided. + config.setFrom(rootProject.layout.projectDirectory.file("config/detekt/detekt.yml")) + buildUponDefaultConfig = true } composeCompiler { diff --git a/android/widget/detekt-baseline.xml b/android/widget/detekt-baseline.xml new file mode 100644 index 00000000..36352b39 --- /dev/null +++ b/android/widget/detekt-baseline.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" ?> +<SmellBaseline> + <ManuallySuppressedIssues/> + <CurrentIssues> + <ID>CyclomaticComplexMethod:WidgetSizeClass.kt:WidgetSizeClass.Companion$fun of: WidgetSizeClass</ID> + <ID>LongMethod:WidgetPresentation.kt:internal fun headlineOf: Headline</ID> + <ID>MagicNumber:HomeworkDayLabel.kt:HomeworkDayLabel.Companion$3L</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:10</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:11</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:20</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:4</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:6</ID> + <ID>MagicNumber:LessonsWidgetBody.kt:8</ID> + <ID>MagicNumber:WidgetPrimitives.kt:12</ID> + <ID>MagicNumber:WidgetPrimitives.kt:14</ID> + <ID>MagicNumber:WidgetPrimitives.kt:5</ID> + <ID>MagicNumber:WidgetPrimitives.kt:6</ID> + <ID>MagicNumber:WidgetPrimitives.kt:8</ID> + <ID>MagicNumber:WidgetStrings.kt:WidgetStrings$60L</ID> + <ID>MagicNumber:WidgetStrings.kt:WidgetStrings$60_000.0</ID> + <ID>TooGenericExceptionCaught:LessonsWidgetReceiver.kt:LessonsWidgetReceiver$error: Exception</ID> + <ID>TooGenericExceptionCaught:WidgetTickReceiver.kt:WidgetTickReceiver$error: Exception</ID> + <ID>TooManyFunctions:WidgetPresentation.kt:com.lumenpearson.lessons.widget.ui.WidgetPresentation.kt</ID> + <ID>TooManyFunctions:WidgetStrings.kt:WidgetStrings</ID> + <ID>UnusedParameter:LessonsWidget.kt:LessonsWidget$context: Context</ID> + </CurrentIssues> +</SmellBaseline> diff --git a/docs/build.md b/docs/build.md index 62ade838..da80ca3e 100644 --- a/docs/build.md +++ b/docs/build.md @@ -112,8 +112,8 @@ call a deployed server. Four things about that table are worth more than the table. **`ci.yml` reads no secret and no variable at all.** The gate — ruff, pytest, `./gradlew -test` and both assembles — needs nothing configured, which is why a pull request from a fork -runs the whole of it. The one consequence worth knowing: its APKs are built with the legal +test`, both assembles and detekt — needs nothing configured, which is why a pull request +from a fork runs the whole of it. The one consequence worth knowing: its APKs are built with the legal link's default, so they link *this* repository's terms, whoever's CI built them. **`CRON_SECRET` is one value living in two places, and nothing checks that they match.** @@ -625,6 +625,60 @@ The same four values are read from the environment variables `LESSONS_KEYSTORE_F `LESSONS_KEYSTORE_PASSWORD`, `LESSONS_KEY_ALIAS` and `LESSONS_KEY_PASSWORD` — which is what CI uses. +## detekt + +The Kotlin is read by [detekt](https://detekt.dev) (#210), and CI fails on anything new it +finds: + +```bash +cd android +./gradlew detekt # every module; fails on a finding its baseline does not hold +./gradlew detektBaseline # rewrites all five baselines from the code as it stands +``` + +**What it reads.** Each module's `src/main` and `src/test`, and `:core:designsystem`'s +`src/androidTest` as well — the plain task reads the first two and nothing else. Every rule +is detekt's default except for the handful in `android/config/detekt/detekt.yml`, which +argue with how Compose is written rather than with how this code is: `FunctionNaming` and +`LongMethod` do not apply to a `@Composable`, `TooManyFunctions` does not count one, +`TopLevelPropertyNaming` lets a constant be `ModeFadeMillis` as well as `MODE_FADE_MILLIS`, +and `MagicNumber` does not look inside a `@Preview`. The file gives the reason for each. + +**What it forgives.** Each module has a `detekt-baseline.xml` holding the findings the code +already had when detekt was switched on — 576 of them under 488 entries, most of them +`MagicNumber` (292), `ReturnCount` (82) and `MaxLineLength` (65). They pass; a new one does +not. The baseline is a record of the past rather than a place to put the next finding: fix +that one, or, if it is right as written, suppress it where it stands — +`@Suppress("MagicNumber")` on the declaration, with the comment saying why. + +**When to regenerate, and how.** `./gradlew detektBaseline` is the whole of it: one command, +all five files, rewritten from what the code finds now, which also drops the entries for +findings since fixed. A baseline entry names the rule, the **file** and the declaration, not +the line, so code that moves within a file stays forgiven and code that moves to *another* +file comes back as new findings. That is what a branch that splits a file does, and it is +the one time to run it — after the merge, with nothing else in the diff, so that the review +of the baseline shows only moved entries. + +**Without type resolution, and what that costs.** The build runs the plain `detekt` task, +which parses each file on its own. The plugin also registers type-resolved tasks +(`detektMain` and `detektTest`, and on Android one per variant beneath those) that give +the analysis the compiler's view of the types, but each takes its classpath from its +variant's compilation, so asking for one compiles every module it depends on, debug and +release both: the half-minute check becomes a build. The price of not paying it is real and is written down +rather than hidden — detekt skips every rule that needs types, 93 of its 213, among them +`LongParameterList`, `UnusedImport`, `UnusedPrivateFunction`, `UnusedPrivateProperty`, +`UnusedVariable`, `IgnoredReturnValue` and `UnsafeCast`. Switching them on is a change to +the tasks CI calls and a baseline of its own for what they find, and nobody has measured +what it would cost on the runner. + +**Where it runs.** Not in `test`, `assembleDebug` or `assembleRelease`: the plugin hangs +`detekt` on `check` and on nothing else, so `./gradlew check` and `./gradlew build` run it +too. In CI it is a step of its own after the build, not a fourth task in the one invocation +— that invocation has no `--continue`, detekt's tasks depend on nothing and would run +first, and a single finding would stop Gradle from scheduling the tests. Measured with +detekt's own command line and the task's arguments, the five modules take 3 to 8 seconds +each, about 25 in all, a JVM start included in each. + ## The bundled typeface is two files The app is set in **Google Sans Flex for Latin and digits and Onest for Cyrillic**, chained @@ -694,7 +748,7 @@ Gradle project at `$PROJECT_DIR$/android`. Opening `android/` on its own builds as well and shows none of them. The configurations in `.run/` are Gradle ones only, because they are the only kind that -assume nothing about the machine: the two CI gates (`test`; `assembleDebug assembleRelease`), +assume nothing about the machine: two of the CI gates (`test`; `assembleDebug assembleRelease`), `:core:model:test`, `:app:installDebug`, and `lint`, which is not a gate. Studio makes its own «app» configuration on the first sync. The server's commands stay in the terminal, as the README gives them: a Python configuration needs a Python plugin and an interpreter somebody From bc10d4258bbd96d3e83e7abf15fc9fceadce43b8 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 16:52:21 +0300 Subject: [PATCH 24/43] Talk to the server over https only in a release build, and refuse an http address where it is typed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The release build permitted cleartext to every host, for a school server on a LAN address no public CA will certify. On such an address the class bearer (often a write token since personal connect codes exist), the diary bearer and the diary session the phone registers with our server all crossed the school's Wi-Fi in the clear; the diary form warned, the join screen did not. The owner decided on 27 September: release builds speak https only, localhost and 127.0.0.1 still allowed; debug builds keep cleartext for development; a LAN server on plain http stops working in the release APK, and that is accepted. - network_security_config.xml refuses cleartext except to localhost and 127.0.0.1; a copy under src/debug overrides it by name and permits every host, so no Gradle change chooses between them. Trust stays system CAs only in both. - CleartextPolicy in :core:data asks that configuration through NetworkSecurityPolicy, the question OkHttp asks, so what the screens refuse and what the network refuses cannot disagree. JVM tests hand in a policy, because the platform class is a stub there. - BaseUrlInterceptor throws ServerNeedsHttpsException before `proceed`, so no bearer is written to a socket and nobody reads the platform's «CLEARTEXT communication … not permitted». It is a kind of ServerAddressMissingException, whose cure is the same screen and which nothing retries; the places that can say why catch it first: a sync answers SyncResult.NeedsHttps (the worker fails once, as for no address), the server badge ServerStatus.NeedsHttps rather than «Сервер не отвечает», the diary sign-in DiarySignInProblem.ServerNeedsHttps. - ServerUrlSheet, which is every way in to the address (the join screen, settings, the first run's diary steps), marks a refused address in the field, says why, and holds «Сохранить»; an address kept from an older version is explained the moment the sheet opens on it. The first run's sign-in page and the diary's form show the refusal where a debug build still shows the old warning about the session. - Three strings, each with its English twin: server_needs_https, sync_error_needs_https and about_badge_server_needs_https; the sheet's supporting text reuses the first. Docs: build.md's «Why HTTP and not HTTPS» is now why a debug build speaks it and a release build does not, and the LAN walkthrough says it is the debug build's route; guide.md, the in-app guide in both languages, the docs index and the privacy policy in both languages say what the release build does now. Tests: ServerNeedsHttpsTest (the interceptor refuses before anything reaches the server, allows what the build allows, never refuses https, agrees with the typed-address verdict; a sync stops and keeps the class; the badge), NetworkSecurityConfigTest (both files and the manifest), ServerUrlSheetTest (release and debug, a kept address, loopback, clearing), and a line each in DiarySignInProblemTest, SyncMessageTest, DiaryProblemTextTest and AboutCardTest. Eight mutations of the fix, in two runs, each turned at least one of them red. :core:data 569 tests and :app 566, all green. Not covered: nothing here runs on a device, so the platform's reading of the two files is what its documentation says, and the release APK has not been pointed at a real server. The diary's form is not handed the address, so a release build pointed at a server on the phone itself reads the refusal there although the request would go through. The join screen still words a kept http address as «no address set» when the code is sent; the sheet under it says why. Closes #202 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../debug/res/xml/network_security_config.xml | 21 ++ .../lessons/ui/common/ServerUrlSheet.kt | 26 ++- .../lessons/ui/common/SyncMessage.kt | 9 + .../lessons/ui/diary/DiaryProblemText.kt | 1 + .../lessons/ui/diary/DiarySignInScreen.kt | 22 +- .../lessons/ui/onboarding/SignInPage.kt | 12 +- .../lessons/ui/settings/AboutCard.kt | 8 + .../app/src/main/res/values-en/strings.xml | 3 + android/app/src/main/res/values/strings.xml | 3 + .../main/res/xml/network_security_config.xml | 74 +++---- .../lessons/NetworkSecurityConfigTest.kt | 91 ++++++++ .../lessons/ui/common/ServerUrlSheetTest.kt | 107 ++++++++++ .../lessons/ui/common/SyncMessageTest.kt | 2 + .../lessons/ui/diary/DiaryProblemTextTest.kt | 1 + .../lessons/ui/settings/AboutCardTest.kt | 8 + .../lessons/core/data/di/LessonsContainer.kt | 3 +- .../core/data/network/BaseUrlInterceptor.kt | 35 +++- .../core/data/network/CleartextPolicy.kt | 67 ++++++ .../core/data/network/NetworkModule.kt | 14 +- .../data/repository/DiarySignInProblem.kt | 13 ++ .../lessons/core/data/repository/Models.kt | 10 + .../core/data/repository/ServerStatus.kt | 7 + .../data/repository/SessionRepositoryImpl.kt | 5 + .../repository/TimetableRepositoryImpl.kt | 4 + .../lessons/core/data/sync/SyncWorker.kt | 8 + .../data/datastore/RequestCredentialsTest.kt | 10 +- .../core/data/network/BearerTestSupport.kt | 20 +- .../core/data/network/ServerNeedsHttpsTest.kt | 196 ++++++++++++++++++ .../data/repository/DiarySignInProblemTest.kt | 5 + docs/README.md | 5 +- docs/app/guide.en.md | 2 +- docs/app/guide.ru.md | 2 +- docs/build.md | 42 +++- docs/guide.md | 12 +- docs/legal/privacy.en.md | 2 +- docs/legal/privacy.ru.md | 6 +- 36 files changed, 767 insertions(+), 89 deletions(-) create mode 100644 android/app/src/debug/res/xml/network_security_config.xml create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheetTest.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/ServerNeedsHttpsTest.kt diff --git a/android/app/src/debug/res/xml/network_security_config.xml b/android/app/src/debug/res/xml/network_security_config.xml new file mode 100644 index 00000000..5832e936 --- /dev/null +++ b/android/app/src/debug/res/xml/network_security_config.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + The debug build's network security configuration: cleartext to every host. + + It overrides src/main/res/xml/network_security_config.xml, which is the + release build's and refuses plain http:// except to the phone itself (#202), + because a debug build is what runs against uvicorn on the developer's own + machine, reached by its LAN address or by the emulator's 10.0.2.2. The app's refusal of an http:// address reads this same answer, so + a debug build neither refuses one nor calls it refused. + + Only the cleartext rule differs. Trust stays what it is in release - system + CAs only - so a debug build is not the one that learns to trust a proxy's + certificate by accident. +--> +<network-security-config> + <base-config cleartextTrafficPermitted="true"> + <trust-anchors> + <certificates src="system" /> + </trust-anchors> + </base-config> +</network-security-config> diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt index e8244847..c7ca3f84 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt @@ -24,6 +24,9 @@ import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.network.CleartextPolicy +import com.lumenpearson.lessons.core.data.network.CleartextVerdict +import com.lumenpearson.lessons.core.data.network.cleartextVerdict import com.lumenpearson.lessons.core.designsystem.component.LessonsBottomSheet import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString @@ -48,12 +51,22 @@ import com.lumenpearson.lessons.core.designsystem.theme.emphasised * to, and a pupil who took that at its word pressed «Подключиться» on a blank * address and was shown an English exception message (#154). * + * A release build refuses a plain `http://` address here, where it is typed, + * rather than at the first request (#202): the field says why and «Сохранить» + * waits for an https:// one. Every way in to the address — the join screen, + * settings, the first run's diary steps — is this sheet, so this is the one + * place it has to be said; and because the sheet opens on the stored address, + * a phone that kept an http:// one from an older version reads the reason the + * moment it opens the sheet to fix it. + * * @param initialUrl current address; the field starts from it rather than empty * so a small typo is a small edit. * @param description the sentence above the field. The first run passes its * own where it asks for the address because the diary's sign-in needs one. * @param onConfirm called with the trimmed value; an empty string clears the * address, and the app then has no server until one is set. + * @param cleartext which hosts this build may reach over plain http; a test + * says which build it is. */ @Composable fun ServerUrlSheet( @@ -62,9 +75,11 @@ fun ServerUrlSheet( onConfirm: (String) -> Unit, modifier: Modifier = Modifier, description: String = correctedString(R.string.server_dialog_description), + cleartext: CleartextPolicy = CleartextPolicy.Platform, ) { var url by rememberSaveable(initialUrl) { mutableStateOf(initialUrl) } val trimmed = remember(url) { url.trim() } + val refused = remember(trimmed, cleartext) { cleartextVerdict(trimmed, cleartext) == CleartextVerdict.REFUSED } // Held only to know whether the field has focus: the label is bold while // it does, which is the one accent a text field gets. val interactionSource = remember { MutableInteractionSource() } @@ -96,6 +111,12 @@ fun ServerUrlSheet( ) }, placeholder = { Text(text = correctedString(R.string.server_dialog_placeholder)) }, + isError = refused, + supportingText = if (refused) { + { Text(text = correctedString(R.string.server_needs_https)) } + } else { + null + }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done, @@ -112,8 +133,9 @@ fun ServerUrlSheet( } // Enabled on an empty field too: "" clears the address, and with // the button disabled there was no way to undo a mistyped address - // short of reinstalling. - Button(onClick = { onConfirm(trimmed) }) { + // short of reinstalling. Only a refused address holds it: saving + // one would store an address every request then refuses. + Button(onClick = { onConfirm(trimmed) }, enabled = !refused) { Text(text = correctedString(R.string.action_save)) } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt index 81e7c78f..20de6df0 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt @@ -26,6 +26,13 @@ sealed interface SyncMessage { */ data object NotConfigured : SyncMessage + /** + * The address is plain `http://` and this build speaks https only (#202). + * Not [NotConfigured]: the address is there, and a sentence saying it is + * not would send the reader looking for a field they have already filled. + */ + data object NeedsHttps : SyncMessage + /** * Anything else: no network, a 5xx, a malformed payload. * @@ -52,6 +59,7 @@ fun SyncResult.toMessageOrNull(): SyncMessage? = when (this) { SyncResult.Success -> null SyncResult.Unauthorised -> SyncMessage.Unauthorised SyncResult.NotConfigured -> SyncMessage.NotConfigured + SyncResult.NeedsHttps -> SyncMessage.NeedsHttps is SyncResult.Failed -> SyncMessage.Failed } @@ -60,6 +68,7 @@ fun SyncResult.toMessageOrNull(): SyncMessage? = when (this) { fun SyncMessage.asText(): String = when (this) { SyncMessage.Unauthorised -> correctedString(R.string.sync_error_unauthorised) SyncMessage.NotConfigured -> correctedString(R.string.sync_error_not_configured) + SyncMessage.NeedsHttps -> correctedString(R.string.sync_error_needs_https) SyncMessage.Failed -> correctedString(R.string.sync_error_generic) SyncMessage.IssueFailed -> correctedString(R.string.issue_error_failed) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt index e36f4f97..27dadeb3 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt @@ -89,6 +89,7 @@ fun diaryProblemMessage( DiarySignInProblem.RegisterUnreachable -> line(R.string.diary_problem_register_unreachable) DiarySignInProblem.ServerMissing -> line(if (firstRun) R.string.diary_problem_server_missing_first_run else R.string.diary_problem_server_missing) + DiarySignInProblem.ServerNeedsHttps -> line(R.string.server_needs_https) DiarySignInProblem.ServerTooOld -> line(R.string.diary_problem_server_too_old) DiarySignInProblem.ServerDisabled -> line(R.string.diary_problem_server_disabled) DiarySignInProblem.RegionNotServed -> line(R.string.diary_problem_region_not_served) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt index 8c78840c..5371ebdd 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt @@ -21,6 +21,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.network.cleartextLeavesThePhone import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile import com.lumenpearson.lessons.core.designsystem.component.GroupItem import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem @@ -116,19 +117,26 @@ fun DiarySignInScreen( // Said before the password is typed, not after it has been sent. // - // `network_security_config.xml` permits cleartext for every host on - // purpose — the realistic deployment is uvicorn on a machine in the - // school, reached by LAN address, and no public CA issues a - // certificate for one of those. The password is not what that - // costs: it goes over https to the diary's own origin and nowhere - // else. What crosses an http:// server is what the diary hands back — + // A release build sends nothing to an http:// server (#202): the + // request is refused before it leaves, so what this says there is + // that, and what to do about it. A debug build, whose + // `network_security_config.xml` still permits cleartext for + // development, warns instead. The password is not what http:// costs + // — it goes over https to the diary's own origin and nowhere else. + // What would cross an http:// server is what the diary hands back — // the session this form registers with our server, and the key to it // — and on http:// anybody on the same Wi-Fi can take either. + // + // Asked of the build rather than of the address, which this screen is + // not given; so a release build pointed at a server on the phone + // itself — the one http:// it allows — reads the refusal too. if (insecureServer) { RoundedCardContainer { GroupRow { Text( - text = correctedString(R.string.diary_insecure_server), + text = correctedString( + if (cleartextLeavesThePhone()) R.string.diary_insecure_server else R.string.server_needs_https, + ), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, ) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt index 3298e4a7..0dd7e2f6 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt @@ -27,6 +27,8 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.network.CleartextVerdict +import com.lumenpearson.lessons.core.data.network.cleartextVerdict import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem @@ -38,7 +40,6 @@ import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing import com.lumenpearson.lessons.core.designsystem.theme.accentTone -import com.lumenpearson.lessons.navigation.isInsecure import com.lumenpearson.lessons.ui.common.ServerUrlSheet import com.lumenpearson.lessons.ui.common.openInBrowser import com.lumenpearson.lessons.ui.diary.DiaryCredentialFields @@ -154,7 +155,14 @@ internal fun SignInPage( NoteCard(passwordPrivacyParagraphs(current.place.host).joinToString("\n\n")) } - if (isInsecure(baseUrl)) NoteCard(correctedString(R.string.diary_insecure_server)) + // A release build refuses an http:// server before anything is + // sent (#202), so there the note is the refusal; a debug build + // still sends, and warns about who could read the session. + when (cleartextVerdict(baseUrl)) { + CleartextVerdict.REFUSED -> NoteCard(correctedString(R.string.server_needs_https)) + CleartextVerdict.PERMITTED -> NoteCard(correctedString(R.string.diary_insecure_server)) + CleartextVerdict.NOT_CLEARTEXT -> Unit + } val petersburg = current.provider == DiaryProviderKey.PETERSBURG DiaryCredentialFields( diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt index 6683a2c5..64b13d85 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt @@ -360,6 +360,14 @@ private fun FlowRowScope.ServerBadges(status: ServerStatus) { ServerStatus.NotConfigured -> PillChip(text = correctedString(R.string.about_badge_server_none)) + // Coloured like an unreachable server: nothing will sync until the + // address changes, and that is the thing this card is for saying. + ServerStatus.NeedsHttps -> PillChip( + text = correctedString(R.string.about_badge_server_needs_https), + containerColor = scheme.errorContainer, + contentColor = scheme.onErrorContainer, + ) + ServerStatus.Unreachable -> PillChip( text = correctedString(R.string.about_badge_server_unreachable), containerColor = scheme.errorContainer, diff --git a/android/app/src/main/res/values-en/strings.xml b/android/app/src/main/res/values-en/strings.xml index 6b2f6139..a1ab8dea 100644 --- a/android/app/src/main/res/values-en/strings.xml +++ b/android/app/src/main/res/values-en/strings.xml @@ -88,6 +88,7 @@ The phone keeps an access key and copies of the timetable and the diary, so the <string name="server_dialog_description">The address of the server the class and the diary go through. No server is built into the app: the class admin, or whoever set the server up, has the address.</string> <string name="server_dialog_label">Address</string> <string name="server_dialog_placeholder">https://…</string> + <string name="server_needs_https">The app connects to the server only at a secure address — one that starts with https://. At an http:// address the class access key and the diary sign-in would cross the network in the clear. Ask whoever runs the server for its https:// address.</string> <!-- Today --> <string name="today_title">Today</string> @@ -142,6 +143,7 @@ The phone keeps an access key and copies of the timetable and the diary, so the <string name="interval_hours">%1$d h</string> <string name="sync_error_unauthorised">Access to the class was revoked. Join again.</string> <string name="sync_error_not_configured">No server address — set one in the settings.</string> + <string name="sync_error_needs_https">The server address starts with http://, and the app connects only over https:// — correct the address in the settings.</string> <string name="sync_error_generic">Could not update the timetable</string> <!-- Week --> @@ -387,6 +389,7 @@ The phone keeps an access key and copies of the timetable and the diary, so the <string name="about_badge_server_unreachable">Server is not answering</string> <string name="about_badge_server_degraded">Server: database and code disagree</string> <string name="about_badge_server_none">No server address set</string> + <string name="about_badge_server_needs_https">Needs an https:// address</string> <string name="about_badge_schema">Schema %1$s</string> <string name="about_badge_schema_expected">Expected %1$s</string> <string name="about_badge_api">API v%1$d</string> diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 58d71c0b..e5e665b0 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -76,6 +76,7 @@ <string name="server_dialog_description">Адрес сервера, через который работают класс и дневник. Встроенного в приложение сервера нет: адрес даёт администратор класса или тот, кто поднял сервер.</string> <string name="server_dialog_label">Адрес</string> <string name="server_dialog_placeholder">https://…</string> + <string name="server_needs_https">Приложение подключается к серверу только по защищённому адресу — он начинается с https://. По адресу с http:// ключ доступа к классу и вход в дневник шли бы по сети открытым текстом. Узнайте адрес с https:// у того, кто поднял сервер.</string> <!-- The Today tab --> <string name="today_title">Сегодня</string> @@ -131,6 +132,7 @@ <string name="interval_hours">%1$d ч</string> <string name="sync_error_unauthorised">Доступ к классу отозван. Подключитесь заново.</string> <string name="sync_error_not_configured">Не указан адрес сервера — задайте его в настройках.</string> + <string name="sync_error_needs_https">Адрес сервера начинается с http://, а приложение подключается только по https:// — исправьте адрес в настройках.</string> <string name="sync_error_generic">Не удалось обновить расписание</string> <!-- Week --> @@ -387,6 +389,7 @@ <string name="about_badge_server_unreachable">Сервер не отвечает</string> <string name="about_badge_server_degraded">Сервер: база и код разошлись</string> <string name="about_badge_server_none">Адрес сервера не задан</string> + <string name="about_badge_server_needs_https">Нужен адрес https://</string> <string name="about_badge_schema">Схема %1$s</string> <string name="about_badge_schema_expected">Ожидается %1$s</string> <string name="about_badge_api">API v%1$d</string> diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml index 93380355..68eb6007 100644 --- a/android/app/src/main/res/xml/network_security_config.xml +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -1,51 +1,53 @@ <?xml version="1.0" encoding="utf-8"?> <!-- - Cleartext HTTP is permitted on purpose. + The release build talks to its server over https:// only (#202). - Since Android 9 the platform blocks http:// by default, which is the right - default for an app talking to one known service over the internet. This app - talks to a server the user hosts themselves, and the realistic deployment is - uvicorn or docker compose on a machine in the same building, reached by LAN - address. Demanding HTTPS there would mean a certificate for an IP address on a - private network - which public CAs do not issue - so the practical effect - would not be "encrypted", it would be "the app does not work". + This file used to permit cleartext to every host, on the premise that a + school's server would be uvicorn on a machine in the building, reached by a + LAN address no public CA will certify. What crossed such a server in the + clear, readable by anyone on the same school Wi-Fi, was: + - the class bearer, frequently a WRITE token since personal connect codes + exist; + - the diary bearer that opens the child's marks and attendance through us; + - the diary session the phone registers with our server at + POST /api/v1/diary/session - a working credential for the child's diary + until it expires. + The owner decided on 27 September 2026 that this is not worth the LAN case: a + school server on plain http:// stops working in the release APK, and that is + accepted. - What crosses the wire to that server is NOT harmless, and this comment once - said it was ("no credentials, no personal data, nothing that identifies a - pupil"). The diary's password is not among it: the app never sends it to our - server. It goes only to the diary's own origin, taken from the catalog bundled - with the app, https-only - an origin that is not is dropped from the - allow-list - and enforced on every request by OriginGuard, with no redirect - followed. So the cleartext permitted here never carries it: the allow-list - holds https origins only, and there is no http:// address the sign-in may - send to. + Two hosts are still allowed cleartext, because a request to either never + leaves the phone: localhost and 127.0.0.1 - a server running on the phone + itself, or one reached through `adb reverse`. - What does cross a plain http:// server, readable by anyone on the same school - Wi-Fi, is: - - the diary session the diary hands back, which the phone registers with - our server at POST /api/v1/diary/session - a working credential for the - child's diary until it expires; - - the diary bearer that opens the child's marks and attendance through us; - - the class bearer, which is frequently a WRITE token since personal - connect codes exist. + The debug build keeps cleartext for every host, for development against a + server on the same desk: src/debug/res/xml/network_security_config.xml has + the same name, and a build type's resources override main's. Nothing in + Gradle chooses between them. - It is still permitted, because the premise above is real: demanding HTTPS on - a LAN address would mean "the app does not work" rather than "encrypted". - What changed is that the app says so where it matters: the diary sign-in form - warns before anything is typed when the server address is not https:// - (diary_insecure_server), and the warning is about the session, not the - password. + The app asks this file before it sends anything (CleartextPolicy in + :core:data, through NetworkSecurityPolicy - the same question OkHttp asks), + so an http:// address is refused where it is typed and before any request, + with a sentence about https rather than a network error. NetworkSecurityConfigTest + in :app holds both files to the rule above. - A school that does terminate TLS simply enters an https:// address and this - configuration stops applying to it; nothing here downgrades a secure URL. + The diary's password is not affected either way: it goes only to the diary's + own https origin, from the catalog bundled with the app, and never to this + server. --> <network-security-config> - <base-config cleartextTrafficPermitted="true"> + <base-config cleartextTrafficPermitted="false"> <trust-anchors> <!-- System CAs only. User-installed CAs stay untrusted, so adding a - certificate to the device cannot silently intercept an https:// - server the school did set up properly. --> + certificate to the device cannot silently intercept the + server's https://. --> <certificates src="system" /> </trust-anchors> </base-config> + <!-- The trust anchors are the base config's: a domain-config inherits what + it does not set. --> + <domain-config cleartextTrafficPermitted="true"> + <domain includeSubdomains="false">localhost</domain> + <domain includeSubdomains="false">127.0.0.1</domain> + </domain-config> </network-security-config> diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt new file mode 100644 index 00000000..5fad26c7 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt @@ -0,0 +1,91 @@ +package com.lumenpearson.lessons + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +/** + * The release build talks to its server over https only; the debug build keeps + * cleartext for development (#202). + * + * The owner's decision of 27 September 2026, and it lives in two files of one + * name: `src/main/res/xml/network_security_config.xml` is what a release build + * — and any build type without a copy of its own — is given, and + * `src/debug/res/xml/` overrides it for the debug build. Nothing in Gradle + * chooses between them, so nothing but this notices if the override is + * deleted (the debug build would silently refuse every LAN server a developer + * points it at) or if the release file drifts back to permitting cleartext + * (every class bearer on a school's Wi-Fi in the clear again, with no failure + * anywhere). + * + * What this cannot say is that a phone reads the files the way it is written + * here; it was never run on a device. The app asks the platform the same + * question it asks here (`CleartextPolicy` in :core:data), so a device that + * disagreed would at least disagree consistently. + */ +class NetworkSecurityConfigTest { + + private val release = parse("src/main/res/xml/network_security_config.xml") + private val debug = parse("src/debug/res/xml/network_security_config.xml") + + @Test + fun `a release build refuses cleartext except to the phone itself`() { + val base = release.single("base-config") + assertEquals("false", base.getAttribute("cleartextTrafficPermitted")) + + val permitted = release.children("domain-config") + .filter { it.getAttribute("cleartextTrafficPermitted") == "true" } + assertEquals("one exception, not a list that grows", 1, permitted.size) + val domains = permitted.single().children("domain") + assertEquals(setOf("localhost", "127.0.0.1"), domains.map { it.textContent.trim() }.toSet()) + for (domain in domains) { + assertFalse( + "${domain.textContent} with its subdomains is not the phone itself", + domain.getAttribute("includeSubdomains") == "true", + ) + } + assertTrue("no debug-overrides in the release file", release.children("debug-overrides").isEmpty()) + } + + @Test + fun `a debug build keeps cleartext to every host`() { + assertEquals("true", debug.single("base-config").getAttribute("cleartextTrafficPermitted")) + } + + @Test + fun `neither build trusts a certificate the user installed`() { + for ((name, config) in listOf("release" to release, "debug" to debug)) { + val anchors = config.single("base-config").children("trust-anchors").single().children("certificates") + assertEquals("$name trusts the system's CAs and nothing else", listOf("system"), anchors.map { it.getAttribute("src") }) + } + } + + @Test + fun `the manifest points at the file both builds name`() { + val manifest = File("src/main/AndroidManifest.xml").readText() + assertTrue(manifest.contains("""android:networkSecurityConfig="@xml/network_security_config"""")) + assertFalse( + "usesCleartextTraffic is ignored beside a configuration file, and would only tell a reader the opposite", + manifest.contains("usesCleartextTraffic"), + ) + } + + // ------------------------------------------------------------------------- + + private fun parse(path: String): Element { + val file = File(path) + assertTrue("$path is missing — the walk went wrong, or the file was deleted", file.isFile) + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file).documentElement + } + + private fun Element.children(tag: String): List<Element> { + val nodes = childNodes + return (0 until nodes.length).mapNotNull { nodes.item(it) as? Element }.filter { it.tagName == tag } + } + + private fun Element.single(tag: String): Element = children(tag).single() +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheetTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheetTest.kt new file mode 100644 index 00000000..7c98fde4 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheetTest.kt @@ -0,0 +1,107 @@ +package com.lumenpearson.lessons.ui.common + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import com.lumenpearson.lessons.core.data.network.CleartextPolicy +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * «Адрес сервера», drawn, in the two builds (#202). + * + * Every way in to the server address is this sheet — the join screen, + * settings, the first run's diary steps — so it is where a release build says + * it will not use an `http://` one: before anything is sent, in a sentence + * about https, and with «Сохранить» held until the address is one it will + * use. Which build is which is a [CleartextPolicy]; which hosts each refuses is + * `NetworkSecurityConfigTest`'s. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp") +class ServerUrlSheetTest { + + @get:Rule val compose = createComposeRule() + + private val release = CleartextPolicy { host -> host == "localhost" || host == "127.0.0.1" } + private val debug = CleartextPolicy { true } + + private var confirmed: String? = null + + private fun show(initial: String, build: CleartextPolicy) = compose.setContent { + LessonsTheme { + ServerUrlSheet(initialUrl = initial, onDismiss = {}, onConfirm = { confirmed = it }, cleartext = build) + } + } + + @Test + fun `a release build refuses an http address where it is typed, and says why`() { + show("", release) + + compose.onNode(hasSetTextAction()).performTextInput("http://192.168.1.50:8000/") + + compose.onNodeWithText(REFUSAL, substring = true).assertIsDisplayed() + compose.onNodeWithText("Сохранить").assertIsNotEnabled().performClick() + assertNull("nothing was stored, so nothing will be sent to it", confirmed) + } + + /** A phone that kept an http:// address from an older version reads why as soon as it opens the sheet. */ + @Test + fun `an address kept from before is explained on opening, and an https one takes its place`() { + show("http://192.168.1.50:8000/", release) + compose.onNodeWithText(REFUSAL, substring = true).assertIsDisplayed() + + compose.onNode(hasSetTextAction()).performTextReplacement("https://lessons.example.com/") + + compose.onNodeWithText(REFUSAL, substring = true).assertDoesNotExist() + compose.onNodeWithText("Сохранить").assertIsEnabled().performClick() + assertEquals("https://lessons.example.com/", confirmed) + } + + @Test + fun `a server on the phone itself is still allowed in a release build`() { + show("http://127.0.0.1:8000", release) + + compose.onNodeWithText(REFUSAL, substring = true).assertDoesNotExist() + compose.onNodeWithText("Сохранить").performClick() + assertEquals("http://127.0.0.1:8000", confirmed) + } + + @Test + fun `a debug build takes the same LAN address without a word`() { + show("http://192.168.1.50:8000/", debug) + + compose.onNodeWithText(REFUSAL, substring = true).assertDoesNotExist() + compose.onNodeWithText("Сохранить").performClick() + assertEquals("http://192.168.1.50:8000/", confirmed) + } + + @Test + fun `clearing the address is still allowed`() { + // The empty field is how a mistyped address is undone; a refusal must + // not take that away. + show("http://192.168.1.50:8000/", release) + + compose.onNode(hasSetTextAction()).performTextReplacement("") + compose.onNodeWithText("Сохранить").performClick() + + assertEquals("", confirmed) + } + + private companion object { + /** The start of `server_needs_https`, as a reader sees it. */ + const val REFUSAL = "только по защищённому адресу" + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt index 85169533..4aa3f4b3 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt @@ -28,6 +28,8 @@ class SyncMessageTest { fun `the cases with a remedy keep their own sentences`() { assertEquals(SyncMessage.Unauthorised, SyncResult.Unauthorised.toMessageOrNull()) assertEquals(SyncMessage.NotConfigured, SyncResult.NotConfigured.toMessageOrNull()) + // An address that is there but http:// is not «no address» (#202). + assertEquals(SyncMessage.NeedsHttps, SyncResult.NeedsHttps.toMessageOrNull()) assertNull(SyncResult.Success.toMessageOrNull()) } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt index f4073626..a9ae9bc3 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt @@ -96,6 +96,7 @@ class DiaryProblemTextTest { DiarySignInProblem.Offline, DiarySignInProblem.RegisterUnreachable, DiarySignInProblem.ServerMissing, + DiarySignInProblem.ServerNeedsHttps, DiarySignInProblem.ServerTooOld, DiarySignInProblem.ServerDisabled, DiarySignInProblem.RegionNotServed, diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt index 7a167303..6627886a 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt @@ -181,6 +181,14 @@ class AboutCardTest { assertShows("Адрес сервера не задан") } + /** #202: the server was never asked, so it is not «не отвечает» — the address is the problem. */ + @Test + fun `an http address this build refuses is a sentence about the address`() { + show(ServerStatus.NeedsHttps) + + assertShows("Нужен адрес https://") + } + @Test fun `a build that was told nothing about itself says that rather than nothing`() { // What a fresh clone with no configuration produces. A page with no diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt index c32c25cd..6b764912 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt @@ -14,6 +14,7 @@ import com.lumenpearson.lessons.core.data.diary.DiaryImport import com.lumenpearson.lessons.core.data.diary.DiaryImportImpl import com.lumenpearson.lessons.core.data.diary.SeedingDiarySignIn import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences +import com.lumenpearson.lessons.core.data.network.CleartextPolicy import com.lumenpearson.lessons.core.data.network.LessonsApi import com.lumenpearson.lessons.core.data.notifications.SchoolAlerts import com.lumenpearson.lessons.core.data.network.NetworkModule @@ -204,7 +205,7 @@ class DefaultLessonsContainer( // this one brings the copy up to date on its own. runCatching { preferences.followCredentials() } } - NetworkModule.apis(credentials = preferences.credentials::current) + NetworkModule.apis(credentials = preferences.credentials::current, cleartext = CleartextPolicy.Platform) } private val api: LessonsApi by lazy { apis.lessons } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/BaseUrlInterceptor.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/BaseUrlInterceptor.kt index 8ab793f0..93a556e2 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/BaseUrlInterceptor.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/BaseUrlInterceptor.kt @@ -6,13 +6,33 @@ import okhttp3.Interceptor import okhttp3.Response /** - * The server address is missing, or is not an address. + * The server address is missing, or is not an address — or, as + * [ServerNeedsHttpsException], is one this build will not use. * * A dedicated type rather than a plain [IOException] so the layers above can * tell "you have not set this up yet" apart from "the network is down" and say * something the user can act on. */ -class ServerAddressMissingException : IOException("No server address configured") +open class ServerAddressMissingException(message: String = "No server address configured") : IOException(message) + +/** + * The server address is plain `http://` to a host this build refuses cleartext + * to — every host but the phone's own, in a release build (#202). + * + * A kind of [ServerAddressMissingException] because the cure is the same + * screen: every place that already answers «no address» with «set the server» + * answers this with it too, and none of them retries it on a timer. The places + * that can say *why* catch it first — a sync, the server badge, a diary + * sign-in — so the sentence is about https rather than about an address that + * is plainly there. + * + * Thrown before the request leaves, so nothing — not the class bearer, not the + * diary's — is ever written to the socket, and the user is not shown the + * platform's «CLEARTEXT communication … not permitted», which names a policy + * nobody has heard of. + */ +class ServerNeedsHttpsException(host: String) : + ServerAddressMissingException("Plain http:// to $host is refused by this build; the server needs https://") /** * Points every request at the server address currently stored in settings. @@ -27,9 +47,13 @@ class ServerAddressMissingException : IOException("No server address configured" * Retrofit still needs a syntactically valid base URL at build time; it is a * `.invalid` host, so a rewrite that ever fails to happen dies at DNS instead of * quietly talking to a real server. + * + * @param cleartext whether this build may send plain `http://` to a host; see + * [CleartextPolicy]. */ internal class BaseUrlInterceptor( private val baseUrlProvider: () -> String, + private val cleartext: CleartextPolicy, ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { @@ -43,6 +67,13 @@ internal class BaseUrlInterceptor( val configured = baseUrlProvider().trim().toHttpUrlOrNull() ?: throw ServerAddressMissingException() + // Here, before `proceed`, rather than left to OkHttp, which refuses the + // same address a step later with an exception the layers above could + // only tell from «no network» by its message. + if (!configured.isHttps && !cleartext.permits(configured.host)) { + throw ServerNeedsHttpsException(configured.host) + } + // A configured path such as /lessons/ prefixes the endpoint path, which // is what makes hosting behind a reverse proxy subdirectory work. val prefix = configured.encodedPath.trimEnd('/') diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt new file mode 100644 index 00000000..4c0eb8a7 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt @@ -0,0 +1,67 @@ +package com.lumenpearson.lessons.core.data.network + +import android.security.NetworkSecurityPolicy +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +/** + * Whether this build may speak plain `http://` to a host (#202). + * + * The answer is the app's `network_security_config.xml`, asked through the + * platform — the same question OkHttp asks before it opens a socket, so what + * the screens refuse and what the network refuses cannot disagree. A release + * build answers yes for `localhost` and `127.0.0.1` only; a debug build, whose + * `src/debug` copy of the file overrides the release one, answers yes for + * every host, for development against a server on the same desk. + * + * An interface so that the JVM tests can say which build they are: the + * platform's class there is a stub that throws. + */ +fun interface CleartextPolicy { + + fun permits(host: String): Boolean + + companion object { + /** The app's own answer, from its network security configuration. */ + val Platform = CleartextPolicy { host -> NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(host) } + } +} + +/** + * Whether this build sends plain `http://` beyond the phone itself — a debug + * build does, a release build does not. + * + * For a screen that knows only that the address is `http://`, not what it is: + * the diary's sign-in form, whose note is a warning about who could read the + * session in the first case and a refusal in the second. It is the base rule + * of the same configuration [CleartextPolicy.Platform] asks host by host, so + * the two cannot disagree except about `localhost`. + */ +fun cleartextLeavesThePhone(): Boolean = NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted + +/** + * What this build will do with an address typed as the server's, asked before + * anything is sent to it. + */ +enum class CleartextVerdict { + /** `https://`, blank, or not an address at all — none of which this is about. */ + NOT_CLEARTEXT, + + /** Plain `http://` this build allows: a debug build, or the phone's own loopback. */ + PERMITTED, + + /** Plain `http://` a release build will not send a byte to; see [ServerNeedsHttpsException]. */ + REFUSED, +} + +/** + * The [CleartextVerdict] on [address] under [policy]. + * + * Parsed the way [BaseUrlInterceptor] parses it, so an address this calls + * refused is exactly one the interceptor would refuse, and one it cannot parse + * is left to the «no address» answer that interceptor already gives. + */ +fun cleartextVerdict(address: String, policy: CleartextPolicy = CleartextPolicy.Platform): CleartextVerdict { + val url = address.trim().toHttpUrlOrNull() ?: return CleartextVerdict.NOT_CLEARTEXT + if (url.isHttps) return CleartextVerdict.NOT_CLEARTEXT + return if (policy.permits(url.host)) CleartextVerdict.PERMITTED else CleartextVerdict.REFUSED +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt index 565ce5a5..935ab7fd 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt @@ -53,8 +53,14 @@ internal object NetworkModule { * and the one step into another year, on a school's mobile signal. Measure * before moving any of these: a number raised on a guess is one nobody can * lower again. + * + * @param cleartext whether a plain `http://` address may be used, asked + * before a request leaves; the container hands in the platform's answer. */ - fun okHttpClient(credentials: () -> RequestCredentials): OkHttpClient = OkHttpClient.Builder() + fun okHttpClient( + credentials: () -> RequestCredentials, + cleartext: CleartextPolicy, + ): OkHttpClient = OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) @@ -62,7 +68,7 @@ internal object NetworkModule { .retryOnConnectionFailure(true) // Order matters: the URL is rewritten first so the auth interceptors see // the real path when they decide whether the call is theirs to sign. - .addInterceptor(BaseUrlInterceptor { credentials().baseUrl }) + .addInterceptor(BaseUrlInterceptor({ credentials().baseUrl }, cleartext)) // Two bearers, one client. The class token and the diary token are // independent — either can exist without the other, and signing out of // one must not disturb the other — so each has an interceptor that @@ -91,9 +97,9 @@ internal object NetworkModule { * client is the expensive part and all four interfaces want the same one — * the same pool, the same timeouts and the same base-URL rewrite. */ - fun apis(credentials: () -> RequestCredentials): Apis { + fun apis(credentials: () -> RequestCredentials, cleartext: CleartextPolicy): Apis { val retrofit = retrofit( - client = okHttpClient(credentials), + client = okHttpClient(credentials, cleartext), json = json(), ) return Apis( diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt index 78331c41..4def6e2a 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt @@ -1,6 +1,7 @@ package com.lumenpearson.lessons.core.data.repository import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.upstream.UpstreamFailure import com.lumenpearson.lessons.core.data.upstream.UpstreamNotAllowed import com.lumenpearson.lessons.core.data.upstream.isTimeout @@ -172,6 +173,15 @@ sealed class DiarySignInProblem(message: String, cause: Throwable? = null) : override val action get() = Action.SET_SERVER } + /** + * The server address is plain `http://`, which this build does not send + * to (#202). Found out at the first question to our server, before a + * password was taken, and nothing was sent anywhere. + */ + data object ServerNeedsHttps : DiarySignInProblem("The server address needs https://") { + override val action get() = Action.SET_SERVER + } + /** * The server predates sessions opened on the phone (`404` on * `/capabilities`), so it could not keep one. Found out before a password @@ -356,6 +366,9 @@ sealed class DiarySignInProblem(message: String, cause: Throwable? = null) : /** No answer from our server at all. */ private fun ofTransport(failure: Throwable, registering: Boolean): DiarySignInProblem = when { + // First: it is a kind of the next one, and the more useful to say. + generateSequence(failure) { it.cause }.take(8).any { it is ServerNeedsHttpsException } -> + ServerNeedsHttps generateSequence(failure) { it.cause }.take(8).any { it is ServerAddressMissingException } -> ServerMissing failure.isTimeout() -> Timeout(host = null) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt index 80b3fe43..0d4b0fde 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt @@ -430,6 +430,16 @@ sealed interface SyncResult { */ data object NotConfigured : SyncResult + /** + * The address is plain `http://` and this build talks to its server over + * https only (#202), so nothing was attempted. + * + * Its own answer rather than [NotConfigured]: the address is plainly + * there, and «set an address» would be a sentence about somebody else's + * phone. The remedy is the same screen, and retrying it is as hopeless. + */ + data object NeedsHttps : SyncResult + /** Anything transient - no network, server down, malformed payload. Retry later. */ data class Failed(val message: String) : SyncResult } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatus.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatus.kt index e9817151..e3923613 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatus.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ServerStatus.kt @@ -24,6 +24,13 @@ sealed interface ServerStatus { /** No address configured, so there is nothing to ask. */ data object NotConfigured : ServerStatus + /** + * The address is plain `http://`, which this build does not send to + * (#202); nothing was asked. Apart from [Unreachable] because nothing about + * the server or the network is wrong, and the cure is the address. + */ + data object NeedsHttps : ServerStatus + /** Up, and its database is the one its code expects. */ data class Ok(val apiVersion: Int, val schema: String?) : ServerStatus diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt index a60bd184..0b36778a 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt @@ -2,6 +2,7 @@ package com.lumenpearson.lessons.core.data.repository import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences import com.lumenpearson.lessons.core.data.network.LessonsApi +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.network.dto.JoinRequestDto import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher @@ -97,6 +98,10 @@ internal class SessionRepositoryImpl( // scope, and turning a cancellation into «сервер не отвечает» would // leave a badge accusing the server of a screen that was closed. throw e + } catch (_: ServerNeedsHttpsException) { + // Refused before it was sent, so the server was never asked and + // must not be called unreachable. + ServerStatus.NeedsHttps } catch (_: Exception) { // Everything else is one answer on purpose. A reader cannot act on // the difference between an unresolved host, a refused connection diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt index bf2e20c8..cefc9802 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt @@ -7,6 +7,7 @@ import com.lumenpearson.lessons.core.data.database.toEntity import com.lumenpearson.lessons.core.data.database.toRecord import com.lumenpearson.lessons.core.data.network.LessonsApi import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.network.dto.toDomain import com.lumenpearson.lessons.core.model.SchoolYear import com.lumenpearson.lessons.core.model.Timetable @@ -360,6 +361,9 @@ internal class TimetableRepositoryImpl( } else { SyncResult.Failed("Server returned HTTP ${http.code()}") } + } catch (cleartext: ServerNeedsHttpsException) { + // Before the «no address» catch, whose kind this is. + SyncResult.NeedsHttps } catch (missing: ServerAddressMissingException) { SyncResult.NotConfigured } catch (io: IOException) { diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt index 10863839..d894b58c 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt @@ -63,6 +63,11 @@ class SyncWorker( workDataOf(KEY_ERROR to REASON_NOT_CONFIGURED), ) + // Nor can it make the server speak https. The same: fail once. + is SyncResult.NeedsHttps -> Result.failure( + workDataOf(KEY_ERROR to REASON_NEEDS_HTTPS), + ) + is SyncResult.Failed -> if (runAttemptCount < MAX_ATTEMPTS) { Result.retry() @@ -82,6 +87,9 @@ class SyncWorker( /** @see SyncResult.NotConfigured */ const val REASON_NOT_CONFIGURED: String = "not_configured" + /** @see SyncResult.NeedsHttps */ + const val REASON_NEEDS_HTTPS: String = "needs_https" + /** * After three tries the next scheduled run will happen sooner than the * backoff would anyway, so there is no point retrying further. diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt index 4aef4f4c..144b434e 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/RequestCredentialsTest.kt @@ -66,7 +66,7 @@ class RequestCredentialsTest { val preferences = LessonsPreferences(store, vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(7, "token-7")) - val client = NetworkModule.okHttpClient(preferences.credentials::current) + val client = NetworkModule.okHttpClient(preferences.credentials::current, cleartext = { true }) val readsBefore = store.reads.get() repeat(20) { @@ -97,7 +97,7 @@ class RequestCredentialsTest { } val preferences = LessonsPreferences(MemoryStore(lastProcess.value), testVault(keys)) - val client = NetworkModule.okHttpClient(preferences.credentials::current) + val client = NetworkModule.okHttpClient(preferences.credentials::current, cleartext = { true }) assertEquals("Bearer token-7", authorizationOn(client, "/api/v1/bundle")) assertEquals("Bearer diary-1", authorizationOn(client, "/api/v1/diary/days")) @@ -114,7 +114,7 @@ class RequestCredentialsTest { preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(1, "token-1")) preferences.addSession(session(2, "token-2")) - val client = NetworkModule.okHttpClient(preferences.credentials::current) + val client = NetworkModule.okHttpClient(preferences.credentials::current, cleartext = { true }) assertEquals("Bearer token-2", authorizationOn(client, "/api/v1/bundle")) preferences.selectSession(1) @@ -136,7 +136,7 @@ class RequestCredentialsTest { answering(MockWebServer()).use { other -> val preferences = LessonsPreferences(MemoryStore(), vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } - val client = NetworkModule.okHttpClient(preferences.credentials::current) + val client = NetworkModule.okHttpClient(preferences.credentials::current, cleartext = { true }) authorizationOn(client, "/api/v1/warmup") assertEquals(1, server.requestCount) @@ -154,7 +154,7 @@ class RequestCredentialsTest { val preferences = LessonsPreferences(MemoryStore(), vault) preferences.updateSettings { it.copy(baseUrl = server.url("/").toString()) } preferences.addSession(session(7, "token-7")) - val client = NetworkModule.okHttpClient(preferences.credentials::current) + val client = NetworkModule.okHttpClient(preferences.credentials::current, cleartext = { true }) assertNull(authorizationOn(client, "/api/v1/diary/days")) preferences.writeDiarySession(DiarySession(login = "parent", token = "diary-1")) diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt index 9ab6a7dd..1c1bbb8c 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt @@ -20,13 +20,19 @@ internal class BearerHarness( diaryToken: String? = DIARY_TOKEN, basePath: String = "/", ) { - private val client = NetworkModule.okHttpClient { - RequestCredentials( - baseUrl = server.url(basePath).toString(), - classToken = classToken, - diaryToken = diaryToken, - ) - } + private val client = NetworkModule.okHttpClient( + credentials = { + RequestCredentials( + baseUrl = server.url(basePath).toString(), + classToken = classToken, + diaryToken = diaryToken, + ) + }, + // The debug build's answer: the server here is plain http on the + // loopback, and which bearer goes where is the question, not which + // build refuses what — ServerNeedsHttpsTest asks that. + cleartext = { true }, + ) init { server.dispatcher = object : Dispatcher() { diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/ServerNeedsHttpsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/ServerNeedsHttpsTest.kt new file mode 100644 index 00000000..08940293 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/ServerNeedsHttpsTest.kt @@ -0,0 +1,196 @@ +package com.lumenpearson.lessons.core.data.network + +import com.lumenpearson.lessons.core.data.database.InMemoryTimetableDao +import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences +import com.lumenpearson.lessons.core.data.datastore.MemoryStore +import com.lumenpearson.lessons.core.data.datastore.testVault +import com.lumenpearson.lessons.core.data.network.dto.BundleDto +import com.lumenpearson.lessons.core.data.network.dto.DeviceMeDto +import com.lumenpearson.lessons.core.data.network.dto.HealthDto +import com.lumenpearson.lessons.core.data.network.dto.JoinRequestDto +import com.lumenpearson.lessons.core.data.network.dto.JoinResponseDto +import com.lumenpearson.lessons.core.data.network.dto.UnlinkResponseDto +import com.lumenpearson.lessons.core.data.network.dto.WarmupDto +import com.lumenpearson.lessons.core.data.repository.ServerStatus +import com.lumenpearson.lessons.core.data.repository.SessionRepositoryImpl +import com.lumenpearson.lessons.core.data.repository.SyncResult +import com.lumenpearson.lessons.core.data.repository.TimetableCache +import com.lumenpearson.lessons.core.data.repository.TimetableRepositoryImpl +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import retrofit2.Response as RetrofitResponse + +/** + * A release build talks to its server over https only (#202). + * + * The owner's decision of 27 September: plain `http://` carries the class + * bearer — often a write token — and the diary's, readable by anybody on the + * same school Wi-Fi, and a LAN server is not worth that. What is under test is + * the half this module owns: an address the build refuses is refused *before* + * the request leaves, so no bearer is ever written to the socket, and every + * place that reports it says «needs https» rather than «no network» or «no + * address». Which hosts a build refuses is the app's + * `network_security_config.xml`, held by `NetworkSecurityConfigTest` in :app; + * here the two builds are two policies. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ServerNeedsHttpsTest { + + /** What the release configuration answers: only the phone itself. */ + private val release = CleartextPolicy { host -> host == "localhost" || host == "127.0.0.1" } + + /** And the debug one: anywhere. */ + private val debug = CleartextPolicy { true } + + /** A build that refuses the test server's own host, whatever the JVM calls it. */ + private val refusesEverything = CleartextPolicy { false } + + private lateinit var server: MockWebServer + + @Before + fun setUp() { + server = MockWebServer().apply { + enqueue(MockResponse.Builder().code(200).body("{}").build()) + start() + } + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `a refused http address is refused before anything reaches the server`() { + val client = NetworkModule.okHttpClient( + credentials = { RequestCredentials(server.url("/").toString(), "class-token", "diary-token") }, + cleartext = refusesEverything, + ) + + for (path in listOf("/api/v1/bundle", "/api/v1/diary/days", "/api/v1/join")) { + try { + client.newCall(Request.Builder().url("http://base-url.invalid$path").build()).execute().close() + fail("$path was sent") + } catch (refused: ServerNeedsHttpsException) { + // What every «set the server» answer already catches, by kind. + assertTrue(refused is ServerAddressMissingException) + } + } + assertEquals("not a byte, and so not a bearer, reached the server", 0, server.requestCount) + } + + @Test + fun `a build that allows the host still sends to it`() { + val client = NetworkModule.okHttpClient( + credentials = { RequestCredentials(server.url("/").toString(), "class-token", null) }, + cleartext = debug, + ) + + client.newCall(Request.Builder().url("http://base-url.invalid/api/v1/bundle").build()).execute().close() + + assertEquals(1, server.requestCount) + } + + @Test + fun `an https address is never refused, whatever the build says about cleartext`() { + var sent: HttpUrl? = null + val client = OkHttpClient.Builder() + .addInterceptor(BaseUrlInterceptor({ "https://school.example/lessons/" }, refusesEverything)) + .addInterceptor { chain -> + sent = chain.request().url + Response.Builder() + .request(chain.request()) + .protocol(Protocol.HTTP_1_1) + .code(200) + .message("OK") + .body("{}".toResponseBody()) + .build() + } + .build() + + client.newCall(Request.Builder().url("http://base-url.invalid/api/v1/bundle").build()).execute().close() + + assertEquals("https://school.example/lessons/api/v1/bundle", sent.toString()) + } + + @Test + fun `the verdict on a typed address is the interceptor's`() { + val cases = listOf( + Triple("", release, CleartextVerdict.NOT_CLEARTEXT), + Triple(" ", release, CleartextVerdict.NOT_CLEARTEXT), + Triple("not an address", release, CleartextVerdict.NOT_CLEARTEXT), + Triple("https://lessons.example.com/", release, CleartextVerdict.NOT_CLEARTEXT), + Triple("HTTPS://Lessons.Example.com", release, CleartextVerdict.NOT_CLEARTEXT), + Triple("http://192.168.1.50:8000/", release, CleartextVerdict.REFUSED), + Triple(" HTTP://school.example ", release, CleartextVerdict.REFUSED), + Triple("http://127.0.0.1:8000", release, CleartextVerdict.PERMITTED), + Triple("http://localhost:8000/", release, CleartextVerdict.PERMITTED), + Triple("http://192.168.1.50:8000/", debug, CleartextVerdict.PERMITTED), + ) + for ((address, policy, expected) in cases) { + assertEquals("«$address»", expected, cleartextVerdict(address, policy)) + } + } + + @Test + fun `a sync against a refused address stops, says why, and keeps the class`() = runTest { + var rejected = 0 + val result = TimetableRepositoryImpl( + dao = InMemoryTimetableDao(), + api = RefusingApi, + activeClassId = flowOf(1L), + ioDispatcher = UnconfinedTestDispatcher(), + onTokenRejected = { rejected++ }, + ).refresh() + + assertEquals(SyncResult.NeedsHttps, result) + assertEquals("the token is not what was wrong", 0, rejected) + } + + @Test + fun `the server badge calls a refused address that, not an unreachable server`() = runTest { + val preferences = LessonsPreferences(MemoryStore(), testVault()) + preferences.updateSettings { it.copy(baseUrl = "http://192.168.1.50:8000/") } + val repository = SessionRepositoryImpl( + preferences = preferences, + api = RefusingApi, + cache = NoCache, + ioDispatcher = UnconfinedTestDispatcher(), + ) + + assertEquals(ServerStatus.NeedsHttps, repository.serverStatus()) + } + + /** What the interceptor throws for every call, as the real client would. */ + private object RefusingApi : LessonsApi { + private fun refuse(): Nothing = throw ServerNeedsHttpsException("192.168.1.50") + override suspend fun join(body: JoinRequestDto): JoinResponseDto = refuse() + override suspend fun bundle(start: String, days: Int, ifNoneMatch: String?): RetrofitResponse<BundleDto> = + refuse() + override suspend fun health(): HealthDto = refuse() + override suspend fun warmup(): WarmupDto = refuse() + override suspend fun me(): DeviceMeDto = refuse() + override suspend fun unlink(): UnlinkResponseDto = refuse() + } + + private object NoCache : TimetableCache { + override suspend fun forgetClass(classId: Long) = Unit + override suspend fun forgetEverything() = Unit + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt index e840151b..92df1740 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt @@ -1,6 +1,7 @@ package com.lumenpearson.lessons.core.data.repository import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem.Action import com.lumenpearson.lessons.core.data.upstream.UpstreamFailure import com.lumenpearson.lessons.core.data.upstream.UpstreamNotAllowed @@ -53,6 +54,8 @@ class DiarySignInProblemTest { DiarySignInProblem.ProviderUnreadable(host), Action.NONE), // Our server. row("no address", ServerAddressMissingException(), DiarySignInProblem.ServerMissing, Action.SET_SERVER), + row("http:// refused by the build (#202)", ServerNeedsHttpsException("192.168.1.50"), + DiarySignInProblem.ServerNeedsHttps, Action.SET_SERVER), row("no network", IOException("unreachable"), DiarySignInProblem.Offline, Action.RETRY), row("socket timeout", SocketTimeoutException("timeout"), DiarySignInProblem.Timeout(null), Action.RETRY), row("call timeout", InterruptedIOException("timeout"), DiarySignInProblem.Timeout(null), Action.RETRY), @@ -81,6 +84,8 @@ class DiarySignInProblemTest { row("read offline", DiaryFailure.Offline(IOException("x")), DiarySignInProblem.Offline, Action.RETRY), row("read offline, no address", DiaryFailure.Offline(ServerAddressMissingException()), DiarySignInProblem.ServerMissing, Action.SET_SERVER), + row("read offline, http:// refused", DiaryFailure.Offline(ServerNeedsHttpsException("192.168.1.50")), + DiarySignInProblem.ServerNeedsHttps, Action.SET_SERVER), ) for ((label, thrown, expected) in table) { val problem = DiarySignInProblem.of(thrown, host = if (thrown is UpstreamFailure) host else null) diff --git a/docs/README.md b/docs/README.md index df158ab2..a2b5eda1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -65,8 +65,9 @@ the user will actually see, it quotes it in Russian, because that is what is on [architecture.md](architecture.md#the-phones-half): the app signs in to the diary itself and registers only the session, so from the app the password goes to the diary and nowhere else; `/diary/login`, kept for older APKs, and the bot's sign-in page pass it through this - server once and store it nowhere. What an `http://` server address exposes is in - [build.md](build.md#why-http-and-not-https). + server once and store it nowhere. What an `http://` server address would expose, and why + only a debug build still speaks it, is in + [build.md](build.md#why-a-debug-build-speaks-http-and-a-release-build-does-not). - **Why there is no Госуслуги sign-in** — [diaries.md](diaries.md#what-it-means-for-this-project): a Госуслуги session is the person's whole state-services account. - **Who lets a phone into a class** — [api.md](api.md), "Who lets a phone in: the class diff --git a/docs/app/guide.en.md b/docs/app/guide.en.md index 8567b7e2..b4dfce63 100644 --- a/docs/app/guide.en.md +++ b/docs/app/guide.en.md @@ -38,7 +38,7 @@ A fresh install does not open with the code field. It opens with five introducto - **Loading** — The student, the terms, two weeks of timetable, homework and marks. If the account has several students, the app asks whose diary to show; if the load stops, “Try again” carries on from where it stopped — and where trying again would change nothing (the account has no student, the diary does not let the server in, the diary answered in a way nobody could read), “Sign out of the diary and start over” is what remains. - **All set** — The student, the diary, the class if there is one, and the main settings. “Open the app” goes to the home screen. -The app has no server of its own: the address comes from the class admin, or from whoever set a server up for your school. It goes into the “Server address” row — on the “How do you want to start?” screen, under the code field, or in Settings → Sync; on the way through your school you are asked for it when it is needed. It has to be the address the server is reachable at from the phone itself: “localhost” on a phone means the phone. +The app has no server of its own: the address comes from the class admin, or from whoever set a server up for your school. It goes into the “Server address” row — on the “How do you want to start?” screen, under the code field, or in Settings → Sync; on the way through your school you are asked for it when it is needed. It has to be the address the server is reachable at from the phone itself: “localhost” on a phone means the phone. And it has to start with https://: the app does not connect to an http:// address, because the access keys would cross the network in the clear. To change class or leave it: Settings → Class. After leaving the last class the app opens not the introduction again but “How do you want to start?” — or the diary, if you are signed in to one. diff --git a/docs/app/guide.ru.md b/docs/app/guide.ru.md index de79ea58..4d80363e 100644 --- a/docs/app/guide.ru.md +++ b/docs/app/guide.ru.md @@ -38,7 +38,7 @@ - **Загрузка** — Ученик, учебные периоды, расписание на две недели, задания и оценки. Если в аккаунте несколько учеников, приложение спросит, чей дневник показывать; если загрузка остановилась, «Повторить» продолжит с того же места — а там, где повтор ничего не изменит (в аккаунте нет ученика, дневник не пускает сервер, дневник ответил непонятно), останется «Выйти из дневника и начать заново». - **Всё готово** — Ученик, дневник, класс, если он есть, и основные настройки. «Открыть приложение» ведёт на главный экран. -Своего сервера у приложения нет: адрес даёт администратор класса или тот, кто поднял сервер для вашей школы. Его вводят в строке «Адрес сервера» — на экране «Как подключиться?», под полем кода или в «Настройки → Синхронизация»; на пути через свою школу его спросят, когда он понадобится. Адрес нужен тот, по которому сервер видит телефон: «localhost» для телефона означает его самого. +Своего сервера у приложения нет: адрес даёт администратор класса или тот, кто поднял сервер для вашей школы. Его вводят в строке «Адрес сервера» — на экране «Как подключиться?», под полем кода или в «Настройки → Синхронизация»; на пути через свою школу его спросят, когда он понадобится. Адрес нужен тот, по которому сервер видит телефон: «localhost» для телефона означает его самого. И начинаться он должен с https://: к адресу с http:// приложение не подключается, потому что ключи доступа шли бы по сети открытым текстом. Сменить класс или выйти из него — «Настройки → Класс». После выхода из последнего класса приложение откроет не знакомство заново, а выбор «Как подключиться?» — или дневник, если вы в него вошли. diff --git a/docs/build.md b/docs/build.md index 62ade838..eb2b2665 100644 --- a/docs/build.md +++ b/docs/build.md @@ -729,6 +729,12 @@ launcher's own log — which is how #167 was found. The app needs an address the **phone** can reach, not the computer. `localhost` and `127.0.0.1` do not work in the app: to a phone, those are the phone. +**This is the debug build's route.** A release build speaks `https://` to its server and +nothing else, except to the phone itself (#202, and [below](#why-a-debug-build-speaks-http-and-a-release-build-does-not)): +it refuses the `http://<address>:8000/` of step 4 where it is typed, with a sentence about +https. With a release build, go through the `adb` tunnel described under «On the +emulator» — it works for a phone on a cable too — or put the server behind TLS. + 1. Start the server so that it listens on more than the loopback: ```bash @@ -793,13 +799,28 @@ the Compose BOM brings, because the BOM's Espresso 3.5.0 reaches for `InputManager.getInstance` by reflection, which API 34 removed, and every test failed at its first `onIdle` on the API 37 emulator. -### Why HTTP and not HTTPS - -Since Android 9 the system blocks `http://` by default. The app allows it through -`network_security_config.xml`, because the real scenario is a server in the same school, -reachable at a local address, and public CAs do not issue certificates for an IP on a -private network. If the school has configured TLS, enter `https://` — the configuration does -not apply to such an address. +### Why a debug build speaks HTTP and a release build does not + +Since Android 9 the system blocks `http://` by default. The app used to allow it to every +host through `network_security_config.xml`, on the premise that the real scenario was a +server in the same school, reachable at a local address, for which public CAs issue no +certificate. The owner decided on 27 September 2026 that what crosses such a wire (the list +below) is not worth that case (#202), so there are now two files: + +- `app/src/main/res/xml/network_security_config.xml` — the release build's: cleartext is + refused except to `localhost` and `127.0.0.1`, whose requests never leave the phone. A + school server on a LAN over plain `http://` does not work in the release APK, and that is + accepted. +- `app/src/debug/res/xml/network_security_config.xml` — the debug build's, which overrides + it by name: cleartext to every host, for development against a server on the same desk. + Nothing in Gradle chooses between them; a build type's resources win over `main`'s. + +The app asks that configuration before it sends anything (`CleartextPolicy` in +`:core:data`, through `NetworkSecurityPolicy` — the question OkHttp asks too). The address +sheet refuses a refused `http://` address where it is typed; one kept from an older version +is refused by the base-URL interceptor before the request leaves, and a sync, the server +badge and the diary sign-in each say it needs `https://` rather than showing a network +error. `NetworkSecurityConfigTest` holds both files to the rule. What travels over a plain `http://` wire is **not** harmless, and this page used to say it was — «only a class code and a timetable: no passwords, no personal data». The diary @@ -821,6 +842,7 @@ Two routes still carry a **password** through the server, and over `http://` the in the clear: the older `POST /api/v1/diary/login`, kept for the APKs built before registration, and the bot's sign-in page, which posts the password to the server at `PUBLIC_BASE_URL` — in the clear if that address is `http://`. Neither is on this app's path. -Before anything is typed, the app's diary sign-in warns when the server address is `http://` -(«⚠️ Адрес сервера начинается с http://…»), and the warning is about the session, not the -password; the configuration file's own comment carries the same list. +In a debug build, before anything is typed, the app's diary sign-in warns when the server +address is `http://` («⚠️ Адрес сервера начинается с http://…»), and the warning is about the +session, not the password; a release build says there that the server needs `https://` +instead. The configuration file's own comment carries the same list. diff --git a/docs/guide.md b/docs/guide.md index bf426805..ce05c4ee 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -80,11 +80,13 @@ code. **The app has no server of its own**: the address comes from the class's administrator, or from whoever set a server up for the school. It goes into the **«Адрес сервера»** row under «Сервер» — on the «Как подключиться?» screen, at the bottom of the class-code screen, -or in «Настройки → Синхронизация» — as a whole address, `http://192.168.1.50:8000/` or -`https://lessons.example.com/`. On the way through the school's diary it is asked for when -it is first needed. The address has to be the one the **phone** can see the server at: to a -phone, `localhost` means itself. The details, and how to check from a browser, are in -[build.md](build.md#pointing-the-app-at-a-server). +or in «Настройки → Синхронизация» — as a whole address, `https://lessons.example.com/`. On +the way through the school's diary it is asked for when it is first needed. The address has +to be the one the **phone** can see the server at: to a phone, `localhost` means itself. A +released app talks to its server over `https://` only and refuses a plain `http://` address +where it is typed, saying so; a debug build, made for development, also takes one on the +local network, such as `http://192.168.1.50:8000/`. The details, and how to check from a +browser, are in [build.md](build.md#pointing-the-app-at-a-server). ### Several classes on one phone diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index 15be13d1..232cb9c8 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -195,7 +195,7 @@ A parent who wants the server to delete their child's data can write to the oper - The server encrypts the diary session (Fernet: AES-128-CBC with HMAC) with a key the operator sets. Without that key the diary does not run on the server at all, rather than keeping sessions unencrypted. - On the phone the app encrypts only the class and diary access keys (AES-256-GCM, with a key from the Android Keystore). If the phone's key store does not work, it keeps them unencrypted, as it used to, and tries again to encrypt them at every start. Everything else — the copies of the timetable and the diary, the login, the settings — is protected only by whatever protects the phone itself. The encryption of the keys has not yet been checked on a device. -**HTTPS depends on the address you typed.** The app also accepts `http://` addresses, for servers on a school's local network. At such an address everything between the phone and the server travels in the clear: the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in. Anybody on the same network can intercept it and open your diary. The app warns you about this before you sign in to a diary, but does not forbid it. +**The app talks to the server over HTTPS only.** It does not accept an address that starts with `http://`, and sends nothing to one: at such an address everything between the phone and the server — the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in — would travel in the clear, and anybody on the same network could intercept it and open your diary. The exception is a server on the phone itself (`localhost`, `127.0.0.1`), which requests to never leave the phone. A debug build of the app, made for development, does accept `http://` addresses, and sends everything to them in the clear. In the app, whatever the server's address, the diary password goes only to the diary's system, and only over HTTPS. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index f9d62e21..1babe682 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -21,8 +21,8 @@ password does cross the server on the bot's sign-in page and from older apps; the data is not in Russia; the operator holds the key and can read the diary; leaving a class deletes nothing on the server; the phone encrypts the two access keys and nothing else, and keeps - them bare where its Keystore does not work; an http:// server address - carries everything in the clear; the keep-alive runs for up to 30 days after the last + them bare where its Keystore does not work; a debug build still sends everything in the + clear to an http:// server address, and a release build to one on the phone itself; the keep-alive runs for up to 30 days after the last use, not only while somebody is active; a correction to the diary is the child's rather than the account's, so every account whose diary lists that pupil reads, changes and resets it, and no row says who wrote it, so the operator cannot pick out one adult's @@ -221,7 +221,7 @@ - Сессию дневника сервер шифрует (Fernet: AES-128-CBC с HMAC) ключом, который задаёт оператор. Без ключа дневник на сервере не работает вовсе, а не хранит сессии открыто. - На телефоне приложение шифрует только ключи доступа к классам и к дневнику (AES-256-GCM, ключом из Android Keystore). Если хранилище ключей на телефоне не работает, оно хранит их без шифрования, как раньше, и пробует зашифровать при каждом запуске. Всё остальное — копии расписания и дневника, логин, настройки — защищено лишь тем, чем защищён сам телефон. Шифрование ключей на устройстве пока не проверялось. -**HTTPS зависит от адреса, который вы ввели.** Приложение принимает и адреса `http://` — ради серверов в локальной сети школы. По такому адресу всё, что идёт между телефоном и сервером, передаётся открытым текстом: ключи доступа к классу и к дневнику, название телефона, расписание и сессия дневника, которую телефон передаёт серверу при входе. Любой в той же сети может её перехватить и открыть ваш дневник. Приложение предупреждает об этом перед входом в дневник, но не запрещает. +**С сервером приложение говорит только по HTTPS.** Адрес, который начинается с `http://`, приложение не принимает и ничего по нему не отправляет: по такому адресу всё, что идёт между телефоном и сервером, — ключи доступа к классу и к дневнику, название телефона, расписание и сессия дневника, которую телефон передаёт серверу при входе, — шло бы открытым текстом, и любой в той же сети мог бы это перехватить и открыть ваш дневник. Исключение — сервер на самом телефоне (`localhost`, `127.0.0.1`): запросы к нему телефон не покидают. Отладочная сборка приложения, которую собирают для разработки, адреса `http://` принимает и передаёт по ним всё открытым текстом. В приложении пароль от дневника при любом адресе сервера уходит только в систему дневника и только по HTTPS. From c6212b2861daea91f652b05ecbb5843af085ea6e Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 16:57:42 +0300 Subject: [PATCH 25/43] Stop HANDOVER.md and the README saying nobody looked at what #186 looked at MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Section 5 of HANDOVER.md says the bullets #186's walk answered «say so in place», and seven of them did not. Each was checked against #186's own record in docs/history.md, or against git, before it was changed: - The year scrolling and the calendar were «not looked at»; #186 opened the week, the month, the ribbon and its list, «Подробно» and the year picker, and saw 2025/26 arrive under «Загружаю год». The ribbon opened without #79's crash, and #111's emulator flings are now named beside the cost nobody has measured on a phone. - «Nothing of #80 has been looked at»; #186 opened the about card and filed #172 on it. - «Nobody has opened a live Telegram with these changes»; #186 drove «11А» from the bot in the owner's chat. The README said the same of the coloured keyboards, and says now that a live client showed them and nothing recorded how they looked. - The join-mode bullet said the switch «is now pressed in tests» and, four lines later, «Not one test presses the button». ClassJoinModeScreenTest presses it; the second sentence goes. - «Nobody has looked at the build-chain bumps»; both builds #186 walked are on AGP 9.4.1, Gradle 9.7.1 and compose-bom 2026.09.00 (read from bd7c816 and c26eace), and #185 is the one defect it filed that names one. - «Nothing from #62 has been seen moving»; #80 answered a phone's report of a marquee that moved on one label and had parked on another. - «The guide ... seen by nobody»; one of #186's screenshots caught it open, and what it showed was not recorded, which is what it says now. Section 7's item 2 now says which of its four checks #186 made on an emulator, and that the join-mode switch itself was never flipped. The README's «Nobody has pressed the rest of the interface» sits under «What nothing checks automatically», beside a paragraph about the walkthrough: it says «No test presses» now. Not touched: the opening, which still names #189 as open and #174, #188 and #119 as about to close — all four are done on GitHub, and rewriting the opening is the close-out's. What each bullet still leaves open was kept as it was. Refs #211 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- HANDOVER.md | 95 +++++++++++++++++++++++++++++++---------------------- README.md | 7 ++-- 2 files changed, 60 insertions(+), 42 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index 2a1f7226..5aaac2d6 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -454,23 +454,27 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i batch: a drag of ten thousand pixels parks at the end under any density, which is what `ToolbarDragTest` does and what caught it. Anything *between* two slots is still not asked of a composition, and `ToolbarReorderTest` asks it in pixels instead. -- **Nothing of the year scrolling has been looked at either.** What the tests prove is - which year is asked for and when, which one is dropped, and that a request made while - another was in flight comes back. What nobody has seen: the year chip, the picker, how - long a school year takes to arrive over a school's wifi, and what three years of day - rows cost a `LazyColumn` that re-reads them on every write. The cap of three is a guess. -- **Nothing of the calendar or the day screen has been looked at.** What the tests prove is +- **The year scrolling has been looked at once, on an emulator** (#186): the year picker, + and 2025/26 fetched on demand under «Загружаю год» from a server on the same machine. + What the tests prove is which year is asked for and when, which one is dropped, and that + a request made while another was in flight comes back. What nobody has seen: how long a + school year takes to arrive over a school's wifi, and what three years of day rows cost a + `LazyColumn` that re-reads them on every write. The cap of three is a guess. +- **The calendar and the day screen have been looked at on an emulator only** (#186): the + week, the month, the day's ribbon and its list, and «Подробно». What the tests prove is which accent a day resolves to, where a band of one reason ends, which row «вернуться к текущему» lands on, and which of three depth levels a given API level gets. - What nobody has seen: the four accents beside one another, whether the summer's tint is + What nobody has judged: the four accents beside one another, whether the summer's tint is faint enough across sixty cells, whether the perspective tilt reads as depth or as a wobble, and whether the AGSL band reads as light rather than as a smear. **What it costs - is unmeasured too** — one shader layer and a per-frame clock on a mid-range phone is a - frame budget nobody has looked at. + on a phone is unmeasured too** — one shader layer and a per-frame clock on a mid-range + phone is a frame budget nobody has looked at. #111's flings on the emulator put the shader + below that emulator's own floor, which is relative only, and #111 stays open for a phone. **One qualification, earned in #79:** the ribbon *has* now been run on a real phone, and it crashed on opening. What that proves is that the three defects #79 fixes were the ones reported, and the bugreport says so in the platform's own words. It proves nothing about - how any of it looks, because nobody got far enough to see it. + how any of it looks, because nobody got far enough to see it. #186 got that far on the + emulator, and the ribbon opened without the crash. - **No rule stops another composable reading `BuildConfig` directly**, which is how #81 happened. Three tests hold `AboutCard`; nothing holds the next one. Such a defect is invisible on a pull request by construction — `ci.yml` does not set the build properties @@ -483,11 +487,13 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i a phone on a school's wifi resolves into `Ok`, `Degraded` or `Unreachable` as intended, and how long it takes to say so. It is also the first thing in this app that makes a network request from the settings page, so it is the first that can make that page wait. -- **Nothing of #80 has been looked at either.** The tests compose the about card, the - calendar header and both link buttons and assert their text is *displayed*. What nobody - has seen: whether the concentric corner reads as concentric, whether a marquee that never - stops is pleasant rather than merely readable, and whether stepping a month with the - arrows surprises somebody who has just switched «День» into its list mode. +- **#80's screens have been on an emulator, and nobody judged what this bullet asks.** #186 + opened the about card — «Схема unknown» on it was #172 — and the calendar. The tests + compose the about card, the calendar header and both link buttons and assert their text + is *displayed*. What nobody has judged: whether the concentric corner reads as + concentric, whether a marquee that never stops is pleasant rather than merely readable, + and whether stepping a month with the arrows surprises somebody who has just switched + «День» into its list mode. - **The widget's new corners have been on a launcher only on an emulator's, and nobody judged them there**: #186 and #189 had the widget on the Pixel launcher at a few sizes, and #113 stays open for the corner radii. A launcher is the only place they exist. #82 derives every @@ -566,8 +572,9 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i - **Every card in the bot is now drawn**, and that found eight defects in one pass (section 4, in `docs/history.md` now). The hole that is left is exactly where it was: the tests assert what is - written on a card rather than how it looks in a client, and nobody has opened a live - Telegram with these changes. + written on a card rather than how it looks in a client. A live Telegram has shown these + cards once, in #186's walk — `/start`, «📱 Подключить телефон» and the class «11А» driven + from the owner's chat — which recorded what the bot did and not how a card looked. **Nobody draws the widget.** Glance has `glance-appwidget-testing` at the same version as the Glance in this project (`1.3.0-alpha02`) — the twelve rungs of the size ladder could be rendered and compared with no device. Not done. @@ -598,11 +605,11 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i writes nothing, and restoring the class code writes straight away. It is covered lower down the stack too: the class code's refusal in `invite`, a personal code for one phone, a race between two requests for one code, a stale button, the sweeping, a `PATCH` in both - directions, the log line, and that the column holds `OPEN` rather than `open`. **Not one - test presses the button.** #186 saw «📱 Подключить телефон» in the live bot, its code link - a phone as «Владелец», the spent code answer `404`, and the invite-only class's own code - refused in words; nobody has flipped the switch on a live class or seen the confirmation - in the app. + directions, the log line, and that the column holds `OPEN` rather than `open`. The presses + are `ClassJoinModeScreenTest`'s. #186 saw «📱 Подключить телефон» in the live bot, its + code link a phone as «Владелец», the spent code answer `404`, and the invite-only class's + own code refused in words; nobody has flipped the switch on a live class or seen the + confirmation in the app. - **The `429` on the code screen was seen once, on an emulator (#186):** «Слишком много попыток. Попробуйте через 15 минут.», with `Retry-After: 866`. - **The upgrade path has been installed over once, on an emulator (#117)**: a build of @@ -612,14 +619,18 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i is found and the "introduction shown" flag is not reset. Nobody has upgraded a real installation of the previous version. If that is broken, the user sees the code field instead of their class — and nothing in the logs. -- **Nobody has looked at the build-chain bumps.** AGP 9.3.1 → 9.4.0 → 9.4.1, Gradle - 9.5.0 → 9.7.1 and compose-bom 2026.06.01 → 2026.09.00 are proved by every test passing and - both assembles building — locally and on the runner. The same goes for the two Python - floors raised the same way, sqlalchemy 2.0.54 and pydantic 2.13.5: the suite passes on - them and nobody read either changelog. The compose-bom is **the app's entire - rendering**, and one of its effects already surfaced by itself (`OverlayLayerTest`, - section 6); what it changed where there is no test, nobody knows. That is the first reason - on the list to open the APK. +- **The build-chain bumps have been looked at only as far as #186's walk goes.** AGP + 9.3.1 → 9.4.0 → 9.4.1, Gradle 9.5.0 → 9.7.1 and compose-bom 2026.06.01 → 2026.09.00 are + proved by every test passing and both assembles building — locally and on the runner. + The same goes for the two Python floors raised the same way, sqlalchemy 2.0.54 and + pydantic 2.13.5: the suite passes on them and nobody read either changelog. The + compose-bom is **the app's entire rendering**, and one of its effects already surfaced by + itself (`OverlayLayerTest`, section 6). Both builds #186 walked on an emulator — + `bd7c816`'s release and its own branch's debug — are on all three, and the one defect it + filed that names any of them is #185, AGP 9.4's warnings about `srcDirs`: a build + message, not a screen. Nobody has set a screen beside one from a build before them, so + what the compose-bom changed where there is no test, nobody knows. On a phone, that is + the first reason on the list to open the APK. - **Both alarm fixes are unverifiable without a device, in principle.** They are inferred from the platform's contract and from neighbouring code that had already taken the same decision (`SchoolAlerts.arm` refused `setWindow` and explained why). @@ -633,13 +644,13 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i claiming twice on one date, but nobody has run two ticks at once; the export's round trip is verified by computing both sides, which is all it claims. -- **Nothing from #62, the batch that stopped text being cut off, has been seen moving, or - wrapping.** Robolectric composes the marquee but advances no animation and reads no - frame, so what is proven is that a line - which fits is laid out exactly as before, that a line which does not stays inside its box - rather than pushing the row apart, and that the whole string is present either way. That it - actually scrolls — and reads well doing so — needs the APK. The same for the other - direction: nobody has seen what an uncapped block does with a long string. **A five-line +- **#62, the batch that stopped text being cut off, has been seen moving only in the reports + #80 answered**: on a phone, a line that scrolled beside one that had spent its three passes + and parked, which #80 made endless. Robolectric composes the marquee but advances no + animation and reads no frame, so what is proven is that a line which fits is laid out + exactly as before, that a line which does not stays inside its box rather than pushing + the row apart, and that the whole string is present either way. Whether it reads well + scrolling needs the APK. The same for the other direction: nobody has seen what an uncapped block does with a long string. **A five-line lesson note now makes a five-line row**, and whether an uncapped heading pushes a sheet's first control too far down is a question only a screen can answer. - **The fade widths are chosen, not measured.** 8 dp at each end, narrower on a segment @@ -659,7 +670,10 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i `raw.githubusercontent.com` are written and have never run. Nor has the bundled fallback been read at runtime — the assets are proven only by listing the built APK, because `:core:data`'s tests have no `Context`. The pager, the loader on the guide, the banner - naming its version and the arrow that leaves it have been seen by nobody. + naming its version and the arrow that leaves it have been looked at by nobody: one of + #186's screenshots caught the guide open, where the owner had left it on the shared + emulator, and what it showed — or whether it had come from GitHub or from the APK — was + not recorded. **The most useful next action is to install the APK on a phone and live with it for one school day.** After that the only questions left are about runtime and layout, and those are @@ -1222,7 +1236,10 @@ which #186 made on an emulator (#115). All four are in [docs/history.md](docs/hi not shown again; and sign into a real diary, press a lesson, correct the room and reset it. And a fourth: put a class into "invitation only", make sure a connected phone goes on working, take a personal code with the «📱 Подключить телефон» button and connect a second - phone with it. + phone with it. #186 did the first and the second on an emulator (#116, #117), and the + fourth on a class that was invite-only already, so the switch itself is still unflipped + (section 5). On a phone those are a thumb's check rather than an open question; the diary + is still nobody's (#121). 3. **Make sure `DADATA_TOKEN` really works** on Vercel (Production and Preview; it is the API key, not the secret one). 4. **Open «Настройки → О приложении → Лицензии» in the app** and look at the eighth row — diff --git a/README.md b/README.md index 349830ac..752c1da6 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,7 @@ under its button, the diary home, the crash-report sheet, the calendar's header, sheets, its year picker and its day list, and the rest — are composed in JVM tests under Robolectric, with a Russian locale and a phone's width, and those are real presses and real rotations on real strings; the design system's components -are exercised the same way. Nobody has pressed the +are exercised the same way. No test presses the rest of the interface or the widget: compilation proves that the types line up and says nothing about what happens on the screen. Covered by nothing: @@ -419,8 +419,9 @@ through the ORM — checking the default specifically — and the third reads th and demands `server_default="OPEN"` in it. The bot's coloured buttons (`app/bot/button_style.py`) are checked only by tests: they -assert which style sits on which button and say nothing about how it looks. Nobody has -opened a live client with those keyboards, and on a client older than Bot API 9.3 a button +assert which style sits on which button and say nothing about how it looks. A live client +has shown those keyboards once — the walkthrough drove a class from the bot in the owner's +chat — and nothing recorded how they looked. On a client older than Bot API 9.3 a button is drawn plain — the colour carries no meaning that is not in the caption anyway, but it is worth checking with your eyes on the first run. From f7928d773b064a51a88031367c0dc35457f4c2c3 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 17:12:46 +0300 Subject: [PATCH 26/43] Split the bot's and the API's class management into one module per screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bot/handlers/manage.py` had grown to 3434 lines and `api/manage.py` to 1516, so a change to the bells meant reading past the subjects, the devices and the access requests. Each is now a package: the bot's has one module per screen of «⚙️ Класс» (subjects, holidays, bells, devices, audit_log, class_card, calendar_feed, diary_binding, import_export, stats, requests, terms) plus `_common` for the refusals, the one permission check and the callback-data parsers; the API's has one per resource (classes, subjects, bells, timetable, devices, journal, statistics, requests, terms, schools) plus `_common` for `Actor` and the role dependencies. Nothing but the location of the code changes. Every top-level definition was moved verbatim with the comments above it (checked by comparing the AST chunks of the old file against the package: nothing missing, nothing altered but `router` and `log`). Each package's `__init__` re-exports every name the old module defined that a caller or a test imports, and includes the modules' routers in one written-down order: - The API: the OpenAPI document and the flattened route list, dumped before and after with and without a bot token, are byte-identical. - The bot: per observer, the sequence of handlers and their filters is identical for `message` (59), `error` and `update`. For `callback_query` (118) one pair moved: «📅 Календарь»'s `calendar_card` and `calendar_rotate` now come before the diary binding's five instead of after. They match `ManageAction.action == "calendar"` / `"rotate_feed"`, the five match `"diary_bind"`, `"diary_prov"`, `"diary_reg"` or a `DiarySchoolPick`, so no press can match both and no update is routed differently. Keeping the message order exact is why: `cmd_calendar` stood before the diary search's free-text step. Three tests reached into the single module and now name the submodule that holds what they patch (`requests._tell`, `requests._build_bot`, `requests._bot_of`, `diary_binding.NetSchoolClient`, and `audit.record` through `app.services.audit` rather than through the module's import). The test that reads every handler's minimum role off its source now reads every module of the package and walks the sub-routers. `schemas.py`, the third file #208 names, is another agent's. Refs #208 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/api/manage.py | 1516 -------- server/app/api/manage/__init__.py | 112 + server/app/api/manage/_common.py | 119 + server/app/api/manage/bells.py | 296 ++ server/app/api/manage/classes.py | 199 + server/app/api/manage/devices.py | 163 + server/app/api/manage/journal.py | 65 + server/app/api/manage/requests.py | 188 + server/app/api/manage/schools.py | 74 + server/app/api/manage/statistics.py | 55 + server/app/api/manage/subjects.py | 228 ++ server/app/api/manage/terms.py | 134 + server/app/api/manage/timetable.py | 148 + server/app/bot/handlers/manage.py | 3434 ----------------- server/app/bot/handlers/manage/__init__.py | 268 ++ server/app/bot/handlers/manage/_common.py | 144 + server/app/bot/handlers/manage/audit_log.py | 77 + server/app/bot/handlers/manage/bells.py | 452 +++ .../app/bot/handlers/manage/calendar_feed.py | 114 + server/app/bot/handlers/manage/class_card.py | 362 ++ server/app/bot/handlers/manage/devices.py | 159 + .../app/bot/handlers/manage/diary_binding.py | 287 ++ server/app/bot/handlers/manage/holidays.py | 604 +++ .../app/bot/handlers/manage/import_export.py | 241 ++ server/app/bot/handlers/manage/requests.py | 342 ++ server/app/bot/handlers/manage/stats.py | 101 + server/app/bot/handlers/manage/subjects.py | 589 +++ server/app/bot/handlers/manage/terms.py | 203 + server/tests/test_access_service.py | 4 +- server/tests/test_api_manage.py | 6 +- server/tests/test_bot_manage.py | 18 +- 31 files changed, 5743 insertions(+), 4959 deletions(-) delete mode 100644 server/app/api/manage.py create mode 100644 server/app/api/manage/__init__.py create mode 100644 server/app/api/manage/_common.py create mode 100644 server/app/api/manage/bells.py create mode 100644 server/app/api/manage/classes.py create mode 100644 server/app/api/manage/devices.py create mode 100644 server/app/api/manage/journal.py create mode 100644 server/app/api/manage/requests.py create mode 100644 server/app/api/manage/schools.py create mode 100644 server/app/api/manage/statistics.py create mode 100644 server/app/api/manage/subjects.py create mode 100644 server/app/api/manage/terms.py create mode 100644 server/app/api/manage/timetable.py delete mode 100644 server/app/bot/handlers/manage.py create mode 100644 server/app/bot/handlers/manage/__init__.py create mode 100644 server/app/bot/handlers/manage/_common.py create mode 100644 server/app/bot/handlers/manage/audit_log.py create mode 100644 server/app/bot/handlers/manage/bells.py create mode 100644 server/app/bot/handlers/manage/calendar_feed.py create mode 100644 server/app/bot/handlers/manage/class_card.py create mode 100644 server/app/bot/handlers/manage/devices.py create mode 100644 server/app/bot/handlers/manage/diary_binding.py create mode 100644 server/app/bot/handlers/manage/holidays.py create mode 100644 server/app/bot/handlers/manage/import_export.py create mode 100644 server/app/bot/handlers/manage/requests.py create mode 100644 server/app/bot/handlers/manage/stats.py create mode 100644 server/app/bot/handlers/manage/subjects.py create mode 100644 server/app/bot/handlers/manage/terms.py diff --git a/server/app/api/manage.py b/server/app/api/manage.py deleted file mode 100644 index db395bba..00000000 --- a/server/app/api/manage.py +++ /dev/null @@ -1,1516 +0,0 @@ -"""Running the class from the phone: the bot's management commands as an API. - -Everything here has a twin in ``app.bot.handlers.manage`` - «📚 Предметы», -«🔔 Звонки», «📱 Устройства», «📜 Журнал», «⚙️ Класс», export, import, -«📊 Статистика» and the access requests - and the twin is the authority. The -same minimum role guards the same operation on both surfaces, the same rows -move when a subject is renamed, and the same line lands in the audit log. An -admin who does something in the app and then opens the bot must find the class -in the state the app said it was in. - -Two rules this module never bends: - -* **The role is looked up per request from the linked Telegram account.** - Nothing the client sends about itself is consulted, and there is no second - permission system for phones: revoking somebody in the bot revokes their - phone in the same instant (``linking.effective_role``, exactly as - ``app.api.edit`` does it). -* **Every id is re-scoped by the query that reads it.** A subject, schedule, - device or request is fetched by ``(id, class_id)``, so an id naming another - class's row finds nothing rather than editing it. - -Days, substitutions, events and homework are *not* here: they are the day-to-day -writes and they already live in ``app.api.edit`` under the editor's role. -""" - -from __future__ import annotations - -import logging -from collections.abc import Awaitable, Callable -from dataclasses import dataclass -from datetime import UTC, datetime -from html import escape -from typing import Any - -from dishka.integrations.fastapi import FromDishka, inject -from fastapi import APIRouter, Depends, HTTPException, Query, status -from sqlalchemy import func, select -from sqlalchemy.ext.asyncio import AsyncSession - -from app.api.deps import current_class, current_device -from app.api.routing import DishkaAnnotatedRoute -from app.bot.render import WEEKDAYS -from app.config import get_settings -from app.models import ( - AccessRequest, - AuditEntry, - BellSchedule, - BotUser, - DayOverride, - DeviceToken, - JoinMode, - Role, - SchoolClass, - Subject, - TermKind, - TimetableEntry, -) -from app.providers import dadata -from app.schemas import ( - AccessRequestOut, - AuditEntryOut, - AuditPageOut, - BellPeriodOut, - BellPeriodsIn, - BellScheduleIn, - BellScheduleOut, - BellSchedulePatch, - ClassDeleteIn, - ClassPatch, - DeletedOut, - ImportConflictOut, - ManagedClassOut, - ManagedDeviceOut, - ManagedSubjectOut, - RequestDecisionIn, - RequestDecisionOut, - SchoolOut, - SchoolSearchOut, - StatsOut, - SubjectHoursOut, - SubjectIn, - SubjectPatch, - SubjectSavedOut, - TermBoundsIn, - TermOut, - TermSchemeIn, - TermsOut, - TimetableExportOut, - TimetableImportIn, - TimetableImportOut, -) -from app.services import access as access_service -from app.services import audit, linking, structure, timetable_io -from app.services import schools as schools_service -from app.services import stats as stats_service -from app.services import subjects as subjects_service -from app.services import terms as terms_service -from app.timezones import is_supported, label_for - -log = logging.getLogger(__name__) - -router = APIRouter(route_class=DishkaAnnotatedRoute, prefix="/api/v1/manage", tags=["manage"]) - -#: Audit lines per page, matching «📜 Журнал» in the bot. -AUDIT_PAGE = 30 - - -# -------------------------------------------------------------------------- -# Who may manage -# -------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class Actor: - """Who is making the change: the device, the Telegram account behind it, - and that account's role in the class *right now*.""" - - device: DeviceToken - telegram_id: int - role: Role - - -def _role_at_least(minimum: Role) -> Callable[..., Awaitable[Actor]]: - """A dependency demanding ``minimum`` of the linked account. - - One factory rather than a guard written out in each endpoint, for the - reason the bot keeps ``_allowed`` in one place: a check that is copied is a - check that will eventually be copied wrong. The refusals are the two the - app already knows from ``app.api.edit`` - «привяжите телефон» and «нужна - роль» - with the role named, because the app shows a different screen for - each and an admin-only page has to say «admin», not «editor». - """ - - @inject - async def dependency( - device: DeviceToken = Depends(current_device), - *, - session: FromDishka[AsyncSession], - ) -> Actor: - if device.telegram_id is None: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="device is not linked" - ) - role = await linking.effective_role(session, device) - if role is None or not role.at_least(minimum): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail=f"{minimum.value} role required" - ) - return Actor(device=device, telegram_id=device.telegram_id, role=role) - - return dependency - - -editor_actor = _role_at_least(Role.EDITOR) -admin_actor = _role_at_least(Role.ADMIN) -owner_actor = _role_at_least(Role.OWNER) - - -# -------------------------------------------------------------------------- -# Small shared pieces -# -------------------------------------------------------------------------- - - -def _wall(stamp: datetime | None, school_class: SchoolClass) -> datetime | None: - """A stored UTC stamp on the class's own wall clock. - - ``created_at`` and friends are naive UTC in the database. An admin in - Vladivostok reading a Moscow server's log should not see yesterday evening - against this morning's change, so they are converted here the same way the - bot's ``render_audit`` converts them. - """ - if stamp is None: - return None - return stamp.replace(tzinfo=UTC).astimezone(school_class.tz).replace(tzinfo=None) - - -def _person(full_name: str | None, username: str | None, telegram_id: int | None) -> str: - """The best name we hold for somebody, in the same order the bot picks it. - - Falls back to the numeric id rather than to «неизвестный»: an id is - something an admin can actually act on, and this surface is admin-only. - """ - if username: - return f"@{username}" - if full_name: - return full_name - return str(telegram_id) if telegram_id is not None else "—" - - -async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: - """Telegram id -> the name to show. Plain text: this is JSON, not HTML.""" - members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) - return { - member.telegram_id: _person(member.full_name, member.username, member.telegram_id) - for member in members - } - - -async def _count(session: AsyncSession, model: Any, *where: Any) -> int: - return int(await session.scalar(select(func.count()).select_from(model).where(*where)) or 0) - - -def _build_bot() -> Any | None: - """A bot for one send, or ``None`` when the deployment has no token. - - Imported lazily: aiogram costs seconds to import and a management endpoint - should not pay that on a deployment that has no bot to notify with. One - per router module, as in ``app.api.edit`` and ``app.api.cron`` - it is the - seam the tests replace. - """ - if not get_settings().bot_token: - return None - from app.bot.bot import build_bot - - return build_bot() - - -async def _tell(telegram_id: int, text: str) -> None: - """Tell one person what was decided. Never fails the request: the decision - is already committed, and a Telegram outage does not undo it.""" - bot = _build_bot() - if bot is None: - return - try: - await bot.send_message(telegram_id, text) - except Exception: # noqa: BLE001 - see the docstring - log.warning("could not tell %s about the decision", telegram_id, exc_info=True) - finally: - bot_session = getattr(bot, "session", None) - if bot_session is not None: - await bot_session.close() - - -def _conflict(detail: str) -> HTTPException: - """409, for a request that is well-formed and refused by the class's own - state: a name already taken, a schedule days still point at.""" - return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail) - - -# -------------------------------------------------------------------------- -# ⚙️ The class card -# -------------------------------------------------------------------------- - - -async def _class_out(session: AsyncSession, school_class: SchoolClass) -> ManagedClassOut: - return ManagedClassOut( - id=school_class.id, - name=school_class.name, - school=school_class.school, - city=school_class.city, - timezone=school_class.timezone_name, - timezone_label=label_for(school_class.timezone_name), - join_code=school_class.join_code, - members=await _count(session, BotUser, BotUser.class_id == school_class.id), - devices=await _count( - session, - DeviceToken, - DeviceToken.class_id == school_class.id, - DeviceToken.revoked.is_(False), - ), - pending_requests=await _count( - session, - AccessRequest, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ), - bell_schedule_id=school_class.bell_schedule_id, - calendar_ready=bool(school_class.calendar_token), - # `.value`, so the wire says «open». The column stores the member name - # because that is how SQLAlchemy persists an enum, and the two are not - # the same string. - join_mode=school_class.join_mode.value, - ) - - -@router.get("/class", response_model=ManagedClassOut) -async def class_card( - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> ManagedClassOut: - """What «⚙️ Класс» shows, as data.""" - return await _class_out(session, school_class) - - -@router.patch("/class", response_model=ManagedClassOut) -async def class_update( - payload: ClassPatch, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> ManagedClassOut: - """Rename the class, re-home it, move its time zone, or change who may join. - - One audit line per field changed rather than one for the request, because - that is what the log is read for: «что изменилось», not «кто открыл - настройки». Changing the zone moves no stored time - a bell rings at 08:30 - whatever the zone says - it changes which instant the class calls «сейчас». - - Moving the grade or the letter recomposes the name, because that is where - the name came from; a name sent in the same request wins over both. - """ - changes = payload.model_dump(exclude_unset=True) - zone = changes.pop("timezone", None) - mode = changes.pop("join_mode", None) - if "letter" in changes: - # The same rule the bot's «Буква» step applies, not a second one. It - # trims, and it reads «-» as «no letter» — which is what the bot tells - # people to send and what the phone's own field offers. Stored raw, a - # «-» became the literal name «9-» and a padded « А » a `letter` that - # never equals the «А» anything compares it with, while `compose_name` - # trimmed on its way past and left the name looking correct. - changes["letter"] = terms_service.normalise_letter(changes["letter"]) - if zone is not None and not is_supported(zone): - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="unknown timezone", - ) - - for column, value in changes.items(): - setattr(school_class, column, value) - await audit.record( - session, - school_class.id, - actor.telegram_id, - f"class.{column}", - f"{column}: {value or 'убрано'}", - ) - if zone is not None: - school_class.timezone = zone - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.timezone", - f"часовой пояс: {zone}", - ) - if ("grade" in changes or "letter" in changes) and "name" not in changes: - # A class moved from 9 to 10 is not called «9А» any more. The name was - # composed from these two at creation (`bot/handlers/start.py`), and a - # move that left the old name standing showed the wrong class on every - # screen that prints one. Unless the same request also names the class: - # an admin who typed a name has said what they want, and recomposing - # over it would overrule them within the one request. - composed = terms_service.compose_name( - school_class.grade, school_class.letter, fallback=school_class.name - ) - if composed != school_class.name: - school_class.name = composed - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.name", - f"name: {composed}", - ) - if mode is not None: - # Through the enum rather than by the string, because the attribute is - # read back as one by `_class_out` in this same request - and because - # the audit line should say what changed rather than echo a wire value. - school_class.join_mode = JoinMode(mode) - await audit.record( - session, - school_class.id, - actor.telegram_id, - # The same action name the bot's own toggle writes, so the log - # reads as one history however the switch was flipped. - "access.join_mode", - "вход только по личным приглашениям" - if school_class.join_mode is JoinMode.INVITE - else "вход по коду класса снова разрешён", - ) - - await session.commit() - return await _class_out(session, school_class) - - -@router.delete("/class", response_model=DeletedOut) -async def class_delete( - payload: ClassDeleteIn, - actor: Actor = Depends(owner_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> DeletedOut: - """Delete the class and everything hanging off it. Owner only. - - ``confirm_name`` must be the class's name, exactly as the bot makes an - owner type it back: a confirmation dialog is answered by the same thumb - that opened it, while a name has to be read off the screen first. The app - will show its own «вы уверены» sheet, but the check that matters is this - one, because the endpoint is reachable without the sheet. - - Nothing is written to the audit log: the log lives in the class and goes - with it. Every device token goes too, so the caller's own token stops - working - which is correct, there is nothing left for it to read. - """ - if payload.confirm_name.strip() != school_class.name: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="confirm_name does not match the class name", - ) - - class_id = school_class.id - log.info("class %s deleted by %s", class_id, actor.telegram_id) - await session.delete(school_class) - await session.commit() - return DeletedOut(id=class_id) - - -# -------------------------------------------------------------------------- -# 📚 Subjects -# -------------------------------------------------------------------------- - - -def _subject_out(subject: Subject) -> ManagedSubjectOut: - return ManagedSubjectOut( - id=subject.id, - name=subject.name, - short_name=subject.short_name, - teacher=subject.teacher, - color=subject.color, - ) - - -async def _subject_or_404( - session: AsyncSession, school_class: SchoolClass, subject_id: int -) -> Subject: - subject = await session.scalar( - select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) - ) - if subject is None: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown subject") - return subject - - -async def _name_taken( - session: AsyncSession, class_id: int, name: str, *, besides: int | None = None -) -> bool: - """Ignores case, because everything downstream of it does.""" - return await subjects_service.clashing(session, class_id, name, besides=besides) is not None - - -@router.get("/subjects", response_model=list[ManagedSubjectOut]) -async def subjects_list( - _: Actor = Depends(editor_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> list[ManagedSubjectOut]: - """The dictionary with ids, for a screen that edits it. An editor may - read it - it is the same list ``GET /api/v1/subjects`` gives any device. - - Adopts whatever the timetable already uses on the way, so this list is - never emptily lying about a class with thirty-five lessons in it. Free once - the two agree, which after the first read they do. - """ - # Committed whatever the count says, the way `public.bundle` does it. The - # number that comes back is how many dictionary entries were *created*, and - # the function also links the timetable rows to them — so a class whose - # dictionary was already complete but whose lessons were not yet pointed at - # it got its UPDATEs run and then dropped when the session closed, on every - # read, forever. It healed only because `/bundle` commits unconditionally - # and a phone polls it; the screen that exists to edit this list did the - # work and threw it away. - await subjects_service.sync_from_timetable(session, school_class.id) - await session.commit() - rows = await session.scalars( - select(Subject).where(Subject.class_id == school_class.id).order_by(Subject.name) - ) - return [_subject_out(row) for row in rows] - - -@router.post("/subjects", response_model=SubjectSavedOut, status_code=status.HTTP_201_CREATED) -async def subject_create( - payload: SubjectIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> SubjectSavedOut: - """Add a subject. The name is unique within the class - that uniqueness is - the whole point of the dictionary, so a duplicate is a 409, not a silent - second «Алгебра».""" - if await _name_taken(session, school_class.id, payload.name): - raise _conflict("a subject with that name is already in this class") - - subject = Subject( - class_id=school_class.id, - name=payload.name, - short_name=payload.short_name, - teacher=payload.teacher, - color=payload.color, - ) - session.add(subject) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.add", - f"добавлен предмет «{payload.name}»", - ) - await session.commit() - await session.refresh(subject) - return SubjectSavedOut(subject=_subject_out(subject)) - - -@router.patch("/subjects/{subject_id}", response_model=SubjectSavedOut) -async def subject_update( - subject_id: int, - payload: SubjectPatch, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> SubjectSavedOut: - """Rename a subject, or set its short name, teacher or colour. - - A rename is a cascade: the timetable, the homework and the substitutions store the - subject as text, so all three move with it in this one transaction, and - ``moved`` says how many rows did. Renaming onto a name the class already - uses is refused - merging two subjects is a different operation, and doing - it by accident cannot be undone. - """ - subject = await _subject_or_404(session, school_class, subject_id) - changes = payload.model_dump(exclude_unset=True) - new_name = changes.pop("name", None) - moved = 0 - - if new_name is not None and new_name != subject.name: - if await _name_taken(session, school_class.id, new_name, besides=subject.id): - raise _conflict("a subject with that name is already in this class") - # The dictionary check above cannot see this one: homework may be - # written under a name that is not a dictionary entry, and homework is - # unique per subject per day. See `structure.homework_clashing`. - clash = await structure.homework_clashing( - session, school_class.id, subject.name, new_name - ) - if clash: - days = ", ".join(day.isoformat() for day in clash) - raise _conflict( - f"homework under both names on the same day: {days}" - ) - old_name = subject.name - moved = await structure.rename_subject(session, school_class.id, subject, new_name) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.rename", - f"предмет «{old_name}» → «{new_name}», строк обновлено: {moved}", - ) - - #: Column -> (audit tag, the word the log line uses). The bot writes the - #: colour as «цвет», not «color», and the two logs are read side by side. - labels = { - "short_name": ("subject.short_name", "сокращение"), - "teacher": ("subject.teacher", "учитель"), - "color": ("subject.colour", "цвет"), - } - for column, value in changes.items(): - setattr(subject, column, value) - action, label = labels[column] - await audit.record( - session, - school_class.id, - actor.telegram_id, - action, - f"{label} предмета «{subject.name}»: {value or 'убрано'}", - ) - - await session.commit() - await session.refresh(subject) - return SubjectSavedOut(subject=_subject_out(subject), moved=moved) - - -@router.delete("/subjects/{subject_id}", response_model=DeletedOut) -async def subject_delete( - subject_id: int, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> DeletedOut: - """Deleting a subject the timetable still uses is refused. - - It used to be allowed, and it left the lessons alone: the timetable stores - the name as well as the link, so the class kept its timetable and lost - only the colour and the teacher. That stopped being true when the - dictionary started keeping itself. The name is still in the template, so - the next read adopts it again - the entry returns within one poll, without - its colour, its short name or its teacher, and the admin is left believing - they deleted something. - - So the two halves of one list are deleted in one order: take the subject - out of the weekly template, and then out of the dictionary. A subject - nothing teaches still deletes in one step, which is the case this endpoint - was really for. - """ - subject = await _subject_or_404(session, school_class, subject_id) - in_use = await subjects_service.lessons_using(session, school_class.id, subject) - if in_use: - raise _conflict(f"{in_use} lesson(s) still use this subject") - name = subject.name - await session.delete(subject) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.delete", - f"удалён предмет «{name}»", - ) - await session.commit() - return DeletedOut(id=subject_id) - - -# -------------------------------------------------------------------------- -# 🔔 Bell schedules -# -------------------------------------------------------------------------- - - -def _schedule_out( - schedule: BellSchedule, school_class: SchoolClass, silenced: int = 0 -) -> BellScheduleOut: - return BellScheduleOut( - id=schedule.id, - name=schedule.name, - is_default=schedule.id == school_class.bell_schedule_id, - silenced_lessons=silenced, - periods=[ - BellPeriodOut(index=row.index, starts_at=row.starts_at, ends_at=row.ends_at) - for row in sorted(schedule.periods, key=lambda row: row.index) - ], - ) - - -async def _schedule_or_404( - session: AsyncSession, school_class: SchoolClass, schedule_id: int -) -> BellSchedule: - schedule = await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) - if schedule is None: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown bell schedule") - return schedule - - -def _rows_of(payload: Any) -> list[tuple[int, Any, Any]]: - """The wire shape as ``structure.write_bell_periods`` takes it.""" - return [(row.index, row.starts_at, row.ends_at) for row in payload.periods] - - -@router.get("/bells", response_model=list[BellScheduleOut]) -async def bells_list( - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> list[BellScheduleOut]: - """Every schedule the class keeps - «Обычное», «Сокращённое», «Суббота» - - with the class default marked.""" - rows = await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == school_class.id) - .order_by(BellSchedule.id) - ) - return [_schedule_out(row, school_class) for row in rows] - - -@router.post("/bells", response_model=BellScheduleOut, status_code=status.HTTP_201_CREATED) -async def bells_create( - payload: BellScheduleIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> BellScheduleOut: - """A new named schedule, with its rows if they came with it. - - It does not become the class default: a shortened schedule is created in - order to be pointed at by particular days, and making it the default the - moment it exists would move every day onto it. - """ - schedule = BellSchedule(class_id=school_class.id, name=payload.name) - session.add(schedule) - await session.flush() - if payload.periods: - await structure.write_bell_periods(session, schedule, _rows_of(payload)) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.create", - f"создано расписание звонков «{payload.name}»: {len(payload.periods)} уроков", - ) - await session.commit() - await session.refresh(schedule, ["periods"]) - return _schedule_out(schedule, school_class) - - -async def _rung_by_default( - session: AsyncSession, school_class: SchoolClass -) -> set[int]: - """The lesson numbers the class rings today, before anything is changed. - - An empty set when the class has no default at all, which is the honest - reading: nothing was ringing, so nothing can stop. - """ - if school_class.bell_schedule_id is None: - return set() - current = await session.scalar( - select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) - ) - return {period.index for period in current.periods} if current is not None else set() - - -@router.patch("/bells/{schedule_id}", response_model=BellScheduleOut) -async def bells_update( - schedule_id: int, - payload: BellSchedulePatch, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> BellScheduleOut: - """Rename a schedule, or make it the one the class runs on by default. - - ``is_default: false`` is refused: a class with no default schedule has no - times for an ordinary day, so the way to stop using this one is to make - another one the default. - """ - schedule = await _schedule_or_404(session, school_class, schedule_id) - silenced: list[tuple[int, int]] = [] - - if payload.name is not None and payload.name != schedule.name: - old_name = schedule.name - schedule.name = payload.name - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.rename", - f"звонки «{old_name}» → «{payload.name}»", - ) - - if payload.is_default is not None: - if not payload.is_default: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="make another schedule the default instead", - ) - # A schedule may be created empty and filled in afterwards, which is - # the point of the two-step flow — but the class default is what every - # ordinary day rings, and a default that rings nothing draws nothing: - # no lesson on any weekday can be placed on a timeline, so `/bundle` - # answers zero lessons, `/now` answers «day_off» on a Monday, and the - # phone, the widget, the calendar feed and the morning digest all go - # blank at once with nothing anywhere reporting a problem. Worse, - # `rung_indexes` then returns an empty set, which `can_ring` reads as - # «this class has not set its bells up yet» and waves every lesson - # number through. `edit.day_put` refuses the same thing at day level. - if not schedule.periods: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="в этом расписании звонков нет ни одного урока", - ) - if school_class.bell_schedule_id != schedule.id: - # Moving the default to a *shorter* schedule takes lessons off - # every weekday exactly as shrinking the current one does — the - # rows past its last rung stay in the database and are drawn, - # logged and announced nowhere. `write_bell_periods` has answered - # this question since the other way in was closed, but it is only - # reached when a schedule's rows are rewritten, and re-pointing - # the class rewrites none. Asked here with the incoming - # schedule's numbers, through the same function, so the two - # cannot answer differently. - # What the class rang a moment ago, against what it will ring - # now. Asking only the incoming schedule counts rows that were - # already silent, which said «перестали звонить уроков: N» on a - # move to a schedule ringing exactly the same numbers. - was = await _rung_by_default(session, school_class) - silenced = await structure.lessons_silenced_by( - session, - school_class.id, - was, - {period.index for period in schedule.periods}, - ) - school_class.bell_schedule_id = schedule.id - summary = f"основное расписание звонков: «{schedule.name}»" - if silenced: - summary += f", перестали звонить уроков: {len(silenced)}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.default", - summary, - ) - - await session.commit() - await session.refresh(schedule, ["periods"]) - return _schedule_out(schedule, school_class, len(silenced)) - - -@router.put("/bells/{schedule_id}/periods", response_model=BellScheduleOut) -async def bells_periods( - schedule_id: int, - payload: BellPeriodsIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> BellScheduleOut: - """Replace a schedule's rows wholesale. - - Wholesale rather than row by row because that is what editing bells is: - the times of the lessons after the one that moved all shift with it, and - sending the six rows that are now true is one intention, not six. - """ - schedule = await _schedule_or_404(session, school_class, schedule_id) - orphaned = await structure.write_bell_periods(session, schedule, _rows_of(payload)) - summary = f"звонки «{schedule.name}»: {len(payload.periods)} уроков" - if orphaned: - # Shrinking the class's own schedule takes lessons off every weekday - # that carried a number past the new last rung. They are still stored - # and they are drawn nowhere, so the log is where an admin finds out. - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.edit", - summary, - ) - await session.commit() - await session.refresh(schedule, ["periods"]) - return _schedule_out(schedule, school_class, len(orphaned)) - - -@router.delete("/bells/{schedule_id}", response_model=DeletedOut) -async def bells_delete( - schedule_id: int, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> DeletedOut: - """Refused for the class default and for anything a day still points at. - - Both are a ``SET NULL`` at the database level, which would silently move - those days onto the default schedule - a change nobody asked for, on dates - an admin is not looking at. - """ - schedule = await _schedule_or_404(session, school_class, schedule_id) - - if schedule.id == school_class.bell_schedule_id: - raise _conflict("this is the class default; make another one the default first") - - used = await _count( - session, - DayOverride, - DayOverride.class_id == school_class.id, - DayOverride.bell_schedule_id == schedule.id, - ) - if used: - raise _conflict(f"{used} special day(s) still use this schedule") - - name = schedule.name - await session.delete(schedule) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.delete", - f"удалено расписание звонков «{name}»", - ) - await session.commit() - return DeletedOut(id=schedule_id) - - -# -------------------------------------------------------------------------- -# 📤 Export and 📥 import -# -------------------------------------------------------------------------- - - -@router.get("/timetable", response_model=TimetableExportOut) -async def timetable_export( - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> TimetableExportOut: - """The weekly template as the text «📤 Экспорт» sends. - - The same format in both directions, which is what makes it a backup: a - text saved out of the bot goes back in through the app, and the other way - round. An empty timetable is an empty string, not a 404 - there is nothing - wrong with a class that has not filled one in yet. - """ - entries = list( - await session.scalars( - select(TimetableEntry) - .where(TimetableEntry.class_id == school_class.id) - .order_by(TimetableEntry.weekday, TimetableEntry.index) - ) - ) - periods = [] - if school_class.bell_schedule_id: - schedule = await session.get(BellSchedule, school_class.bell_schedule_id) - if schedule is not None: - periods = list(schedule.periods) - return TimetableExportOut( - text=timetable_io.export_timetable(entries, periods), lessons=len(entries) - ) - - -@router.post("/timetable/import", response_model=TimetableImportOut) -async def timetable_import( - payload: TimetableImportIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> TimetableImportOut: - """Parse a paste and replace exactly the weekdays it names. - - The bot shows a preview and asks «Применить»; an API has no screen to show - one on, so the preview is the refusal: if a weekday in the paste already - has lessons, nothing is written and the response lists what stands to be - overwritten. Sending it again with ``replace: true`` is the second tap. - - Days the paste does not mention are left alone, so importing one day's - block is a legitimate thing to do, and a day named with nothing under it is - emptied - that is how a paste says «в четверг уроков нет». A - ``== Звонки ==`` block replaces the default schedule's rows outright, as it - does in the bot; it is a schedule, not a day, and nothing else points at it. - """ - days, rejected = timetable_io.parse_timetable_block(payload.text) - bells, _rejected_bells = timetable_io.parse_bells_block(payload.text) - if not days and not bells: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="no weekday header and no bells block found in the text", - ) - - existing = await structure.lessons_per_weekday(session, school_class.id, list(days)) - conflicts = [ - ImportConflictOut(weekday=weekday, existing=count, incoming=len(days[weekday])) - for weekday, count in sorted(existing.items()) - if count - ] - if conflicts and not payload.replace: - return TimetableImportOut( - applied=False, - days=sorted(days), - lessons=sum(len(rows) for rows in days.values()), - bells=len(bells), - conflicts=conflicts, - rejected=rejected, - ) - - result = await structure.apply_timetable(session, school_class, days, bells) - total = result.written - schedule = result.schedule - # Reported, not silently dropped: a lesson past the last bell has nowhere - # to be drawn, and «applied: true, lessons: N» with N short of what was - # pasted is exactly the answer that hides it. One line per dropped row, - # named by its weekday: the same number under two weekdays is two lessons - # gone, and while this counted the distinct numbers it admitted to one. - rejected = rejected + [ - f"{WEEKDAYS[weekday - 1]}, урок {index}: " - "нет такого звонка в расписании звонков" - for weekday, index in result.dropped - ] - # The other direction, and the one nothing used to report: these lessons - # were already stored and the bells this import wrote no longer ring them, - # so they are still in the database and drawn nowhere. - rejected = rejected + [ - f"{WEEKDAYS[weekday - 1]}, урок {index}: " - "больше не звонит — новые звонки короче" - for weekday, index in result.orphaned - ] - summary = f"импорт расписания: дней {len(days)}, уроков {total}" - if bells: - summary += f", звонков {len(bells)}" - if result.dropped: - summary += f", без звонка пропущено {len(result.dropped)}" - if result.orphaned: - summary += f", перестали звонить {len(result.orphaned)}" - await audit.record( - session, school_class.id, actor.telegram_id, "timetable.import", summary - ) - await session.commit() - if schedule is not None: - await session.refresh(schedule, ["periods"]) - - return TimetableImportOut( - applied=True, - days=sorted(days), - lessons=total, - bells=len(bells), - conflicts=conflicts, - rejected=rejected, - ) - - -# -------------------------------------------------------------------------- -# 📱 Devices -# -------------------------------------------------------------------------- - - -def _device_out( - device: DeviceToken, - school_class: SchoolClass, - names: dict[int, str], - role: Role | None, -) -> ManagedDeviceOut: - return ManagedDeviceOut( - id=device.id, - device_name=device.device_name, - linked=device.is_linked, - owner=names.get(device.telegram_id) if device.telegram_id is not None else None, - role=role.value if role is not None else None, - revoked=device.revoked, - created_at=_wall(device.created_at, school_class), - last_seen_at=_wall(device.last_seen_at, school_class), - linked_at=_wall(device.linked_at, school_class), - ) - - -async def _device_or_404( - session: AsyncSession, school_class: SchoolClass, device_id: int -) -> DeviceToken: - device = await session.scalar( - select(DeviceToken).where( - DeviceToken.id == device_id, DeviceToken.class_id == school_class.id - ) - ) - if device is None: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown device") - return device - - -@router.get("/devices", response_model=list[ManagedDeviceOut]) -async def devices_list( - include_revoked: bool = Query(default=False), - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> list[ManagedDeviceOut]: - """The phones on the class's list, oldest first. - - The role is a lookup, not a stored field: a device acts with whatever role - its owner holds right now, so revoking somebody in the bot has already - changed this list by the time it is drawn. ``include_revoked`` brings back - the ones that were switched off, which the bot's page leaves out. - """ - devices = await linking.devices_of(session, school_class.id, include_revoked=include_revoked) - names = await _member_names(session, school_class.id) - # Once per owner, not once per phone: the role hangs off the account, and a - # class where everybody joined from their own phone was paying a round trip - # a row for an answer already in hand. «📱 Устройства» in the bot resolves - # it the same way. - roles: dict[int, Role | None] = {} - for device in devices: - if device.telegram_id is not None and device.telegram_id not in roles: - roles[device.telegram_id] = await linking.effective_role(session, device) - return [ - _device_out(device, school_class, names, roles.get(device.telegram_id)) - for device in devices - ] - - -@router.post("/devices/{device_id}/revoke", response_model=ManagedDeviceOut) -async def device_revoke( - device_id: int, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> ManagedDeviceOut: - """Switch a phone off. Revoked, not deleted: the row is what a token is - checked against, and keeping it is what makes the refusal instant and - permanent. Revoking an already revoked device changes nothing and adds no - second line to the log. - - An admin may do this to the phone they are holding, and then the next - request from it is a 401. That is the point - it is how a lost phone is - dealt with from the one that is still in a pocket. - """ - device = await _device_or_404(session, school_class, device_id) - names = await _member_names(session, school_class.id) - role = await linking.effective_role(session, device) - if device.revoked: - return _device_out(device, school_class, names, role) - - device.revoked = True - name = device.device_name or f"Устройство {device.id}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "device.revoke", - f"отключено устройство «{name}»", - ) - await session.commit() - return _device_out(device, school_class, names, role) - - -@router.post("/devices/{device_id}/unlink", response_model=ManagedDeviceOut) -async def device_unlink( - device_id: int, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> ManagedDeviceOut: - """Back to read-only, without taking the phone off the class. - - The device keeps reading the timetable and loses the role it borrowed from - its owner's account. A device that is not linked has nothing to unlink, - which is a 409 rather than a silent success: the admin pressed it expecting - something to change. - """ - device = await _device_or_404(session, school_class, device_id) - if device.telegram_id is None: - raise _conflict("device is not linked") - - name = device.device_name or f"Устройство {device.id}" - await linking.unlink_device(session, device) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "device.unlink", - f"отвязано устройство «{name}» — снова только чтение", - ) - await session.commit() - names = await _member_names(session, school_class.id) - role = await linking.effective_role(session, device) - return _device_out(device, school_class, names, role) - - -# -------------------------------------------------------------------------- -# 📜 The audit log -# -------------------------------------------------------------------------- - - -@router.get("/log", response_model=AuditPageOut) -async def audit_log( - limit: int = Query(default=AUDIT_PAGE, ge=1, le=100), - offset: int = Query(default=0, ge=0), - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> AuditPageOut: - """Who changed what, newest first. - - One row more than ``limit`` is read and thrown away: that is what - ``has_more`` is, and it costs one row instead of the count of an - append-only table on every page turn. - """ - entries = await audit.recent(session, school_class.id, limit=limit + 1, offset=offset) - has_more = len(entries) > limit - entries = entries[:limit] - names = await _member_names(session, school_class.id) - - def _entry(row: AuditEntry) -> AuditEntryOut: - return AuditEntryOut( - id=row.id, - action=row.action, - summary=row.summary, - who=names.get(row.telegram_id) if row.telegram_id is not None else None, - at=_wall(row.created_at, school_class), - ) - - return AuditPageOut( - entries=[_entry(row) for row in entries], - limit=limit, - offset=offset, - has_more=has_more, - ) - - -# -------------------------------------------------------------------------- -# 📊 Stats -# -------------------------------------------------------------------------- - - -@router.get("/stats", response_model=StatsOut) -async def stats( - _: Actor = Depends(editor_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> StatsOut: - """The numbers «📊 Статистика» shows, without the sentence around them. - - An editor may read them, as in the bot: they say whether the timetable is - complete and whether homework is being entered, which is exactly what the - person entering it wants to know. - """ - numbers = await stats_service.class_stats(session, school_class) - return StatsOut( - today=numbers["today"], - lessons_per_week=numbers["lessons_per_week"], - subjects_count=numbers["subjects_count"], - subjects=[ - SubjectHoursOut(name=name, hours=hours) for name, hours in numbers["subjects"] - ], - homework_open=numbers["homework_open"], - homework_total=numbers["homework_total"], - members_by_role={role.value: count for role, count in numbers["members_by_role"].items()}, - devices_active=numbers["devices_active"], - overrides_upcoming=numbers["overrides_upcoming"], - events_upcoming=numbers["events_upcoming"], - ) - - -# -------------------------------------------------------------------------- -# 🙋 Access requests -# -------------------------------------------------------------------------- - - -async def _request_or_404( - session: AsyncSession, school_class: SchoolClass, request_id: int -) -> AccessRequest: - """Pending, and this class's. A request that has already been answered is - gone as far as this endpoint is concerned, so two admins tapping «Выдать» - at once cannot grant twice.""" - request = await session.scalar( - select(AccessRequest).where( - AccessRequest.id == request_id, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ) - ) - if request is None: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown request") - return request - - -@router.get("/requests", response_model=list[AccessRequestOut]) -async def requests_list( - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> list[AccessRequestOut]: - """Everybody waiting for a role, oldest first.""" - rows = list( - await session.scalars( - select(AccessRequest) - .where(AccessRequest.class_id == school_class.id, AccessRequest.status == "pending") - .order_by(AccessRequest.id) - ) - ) - names = await _member_names(session, school_class.id) - return [ - AccessRequestOut( - id=row.id, - who=names.get(row.telegram_id, str(row.telegram_id)), - requested_role=row.requested_role.value, - message=row.message, - created_at=_wall(row.created_at, school_class), - ) - for row in rows - ] - - -@router.post("/requests/{request_id}/approve", response_model=RequestDecisionOut) -async def request_approve( - request_id: int, - payload: RequestDecisionIn | None = None, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> RequestDecisionOut: - """Grant the role, through the same rules as «👥 Доступ» in the bot. - - Literally the same rules: `services/access.approve_request` is what the - bot's own «✅ Выдать» calls, so the two surfaces cannot drift apart. The - only thing this one does differently is let an admin answer with a role - other than the one asked for - which `can_grant` still gates, inside the - service. - - The requester is told in Telegram, because that is where they asked. - """ - request = await _request_or_404(session, school_class, request_id) - target = Role(payload.role) if payload is not None and payload.role else request.requested_role - - try: - member = await access_service.approve_request( - session, - school_class, - request, - actor_id=actor.telegram_id, - actor_role=actor.role, - role=target, - ) - except access_service.GrantRefused as refused: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail=refused.detail - ) from refused - - who = _person(member.full_name, member.username, member.telegram_id) - await session.commit() - - await _tell(request.telegram_id, access_service.approval_notice(school_class, target)) - return RequestDecisionOut(id=request_id, status="approved", role=target.value, who=who) - - -@router.post("/requests/{request_id}/decline", response_model=RequestDecisionOut) -async def request_decline( - request_id: int, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> RequestDecisionOut: - """Say no. The person keeps whatever role they already had, and is told - - silence would leave them asking again.""" - request = await _request_or_404(session, school_class, request_id) - names = await _member_names(session, school_class.id) - who = names.get(request.telegram_id, str(request.telegram_id)) - - request.status = "declined" - request.decided_by = actor.telegram_id - request.decided_at = datetime.now(UTC).replace(tzinfo=None) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "access.decline", - f"отклонён запрос доступа от {request.telegram_id}", - ) - await session.commit() - - await _tell( - request.telegram_id, - f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", - ) - return RequestDecisionOut(id=request_id, status="declined", who=who) - - -# -------------------------------------------------------------------------- -# Quarters and half-years -# -# The same service the bot's editor calls, for the same reason the rest of -# this module does it that way: «пересекается с периодом 2» decided twice -# disagrees within a month. -# -------------------------------------------------------------------------- - - -def _terms_out(school_class: SchoolClass, year: int, rows) -> TermsOut: - return TermsOut( - kind=terms_service.scheme_of(school_class).value, - year=year, - terms=[ - TermOut( - index=term.index, - kind=term.kind.value, - starts_on=term.starts_on, - ends_on=term.ends_on, - ) - for term in rows - ], - ) - - -def _term_year(school_class: SchoolClass) -> int: - """The school year in force for this class, in the class's own zone.""" - return terms_service.opening_year_of(datetime.now(school_class.tz).date()) - - -@router.get("/terms", response_model=TermsOut) -async def terms_list( - _: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> TermsOut: - """This class's terms, seeding the conventional set if it has none.""" - year = _term_year(school_class) - rows = await terms_service.ensure(session, school_class, year) - await session.commit() - return _terms_out(school_class, year, rows) - - -@router.put("/terms/scheme", response_model=TermsOut) -async def terms_set_scheme( - payload: TermSchemeIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> TermsOut: - """Switch between quarters and half-years, reseeding the year. - - A replacement rather than an edit: four quarters and two halves do not map - onto each other, and a leftover third quarter inside a year that has two is - not a state worth keeping. - """ - year = _term_year(school_class) - wanted = TermKind(payload.kind) - rows = await terms_service.set_scheme(session, school_class, wanted, year) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.term_kind", - f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", - ) - await session.commit() - return _terms_out(school_class, year, rows) - - -@router.put("/terms/{index}", response_model=TermsOut) -async def terms_set_bounds( - index: int, - payload: TermBoundsIn, - actor: Actor = Depends(admin_actor), - school_class: SchoolClass = Depends(current_class), - *, - session: FromDishka[AsyncSession], -) -> TermsOut: - """Move one term's edges. - - 422 with the service's own Russian sentence rather than a field-shaped - error: what is wrong is the relationship between this term and the year or - its neighbours, and «конец периода раньше его начала» is the thing worth - putting on the screen. - """ - year = _term_year(school_class) - await terms_service.ensure(session, school_class, year) - try: - await terms_service.set_bounds( - session, school_class, year, index, payload.starts_on, payload.ends_on - ) - except terms_service.TermError as error: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) - ) from error - - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.term", - f"период {index}: {payload.starts_on:%d.%m.%Y} — {payload.ends_on:%d.%m.%Y}", - ) - await session.commit() - rows = await terms_service.read(session, school_class.id, year) - return _terms_out(school_class, year, rows) - - -@router.get("/schools", response_model=SchoolSearchOut) -async def schools_search( - q: str = Query(..., description="Название или номер школы"), - page: int = Query(1, ge=1), - page_size: int = Query( - schools_service.PAGE_SIZE, - ge=1, - le=dadata.MAX_SUGGESTIONS, - description="Строк на странице; 20 отдаёт всё найденное за один запрос", - ), - region: str | None = Query(None, max_length=120), - _: Actor = Depends(admin_actor), - __: SchoolClass = Depends(current_class), -) -> SchoolSearchOut: - """Search the school directory, the same way «⚙️ Класс» does in the bot. - - Reads nothing and writes nothing: it is a lookup the app needs before it - can `PATCH /class` with a school name, and the name is all that is stored. - Admin-only despite being read-only, because every call spends part of a - daily allowance somebody else pays for, and the class's own members are the - only people with a reason to spend it. - - 503 rather than 500 when the directory is not configured or not answering: - nothing here is broken, the feature is simply unavailable right now, and - the client's answer to that is to let the name be typed. - - **Every call is one upstream search**, whatever ``page`` says — the - directory has no offset to page with, so there is nothing to resume. A - client that pages should therefore ask once with ``page_size=20`` and cut - the answer up itself, which is what the bot and the app both do; asking for - four pages of five is four searches for one question. - """ - try: - result = await schools_service.search(q, region=region) - except schools_service.SearchError as error: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) - ) from error - except dadata.DirectoryError as error: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=error.message - ) from error - - found = schools_service.page_of( - result.schools, page, size=page_size, truncated=result.truncated - ) - return SchoolSearchOut( - items=[SchoolOut(**school.model_dump()) for school in found.items], - page=found.page, - pages=found.pages, - total=found.total, - truncated=found.truncated, - ) diff --git a/server/app/api/manage/__init__.py b/server/app/api/manage/__init__.py new file mode 100644 index 00000000..35991f2a --- /dev/null +++ b/server/app/api/manage/__init__.py @@ -0,0 +1,112 @@ +"""Running the class from the phone: the bot's management commands as an API. + +Everything here has a twin in ``app.bot.handlers.manage`` - «📚 Предметы», +«🔔 Звонки», «📱 Устройства», «📜 Журнал», «⚙️ Класс», export, import, +«📊 Статистика» and the access requests - and the twin is the authority. The +same minimum role guards the same operation on both surfaces, the same rows +move when a subject is renamed, and the same line lands in the audit log. An +admin who does something in the app and then opens the bot must find the class +in the state the app said it was in. + +Two rules this package never bends: + +* **The role is looked up per request from the linked Telegram account.** + Nothing the client sends about itself is consulted, and there is no second + permission system for phones: revoking somebody in the bot revokes their + phone in the same instant (``linking.effective_role``, exactly as + ``app.api.edit`` does it). +* **Every id is re-scoped by the query that reads it.** A subject, schedule, + device or request is fetched by ``(id, class_id)``, so an id naming another + class's row finds nothing rather than editing it. + +Days, substitutions, events and homework are *not* here: they are the day-to-day +writes and they already live in ``app.api.edit`` under the editor's role. + +One module per resource, each with a router of its own, and ``_common`` for +who is asking and the conversions they share. This used to be one file of +fifteen hundred lines; the names it defined are still importable from here. +""" + +from fastapi import APIRouter + +from app.api.manage import ( + bells, + classes, + devices, + journal, + requests, + schools, + statistics, + subjects, + terms, + timetable, +) +from app.api.manage._common import Actor, admin_actor, editor_actor, owner_actor +from app.api.manage.bells import ( + bells_create, + bells_delete, + bells_list, + bells_periods, + bells_update, +) +from app.api.manage.classes import class_card, class_delete, class_update +from app.api.manage.devices import device_revoke, device_unlink, devices_list +from app.api.manage.journal import AUDIT_PAGE, audit_log +from app.api.manage.requests import request_approve, request_decline, requests_list +from app.api.manage.schools import schools_search +from app.api.manage.statistics import stats +from app.api.manage.subjects import subject_create, subject_delete, subject_update, subjects_list +from app.api.manage.terms import terms_list, terms_set_bounds, terms_set_scheme +from app.api.manage.timetable import timetable_export, timetable_import +from app.api.routing import DishkaAnnotatedRoute + +router = APIRouter(route_class=DishkaAnnotatedRoute, prefix="/api/v1/manage", tags=["manage"]) + +# The order a request is matched in, written down once here rather than implied +# by which module happens to import which. It is the order the routes stood in +# when this was one file, and none of them moved. +router.include_router(classes.router) +router.include_router(subjects.router) +router.include_router(bells.router) +router.include_router(timetable.router) +router.include_router(devices.router) +router.include_router(journal.router) +router.include_router(statistics.router) +router.include_router(requests.router) +router.include_router(terms.router) +router.include_router(schools.router) + +__all__ = [ + "AUDIT_PAGE", + "Actor", + "admin_actor", + "audit_log", + "bells_create", + "bells_delete", + "bells_list", + "bells_periods", + "bells_update", + "class_card", + "class_delete", + "class_update", + "device_revoke", + "device_unlink", + "devices_list", + "editor_actor", + "owner_actor", + "request_approve", + "request_decline", + "requests_list", + "router", + "schools_search", + "stats", + "subject_create", + "subject_delete", + "subject_update", + "subjects_list", + "terms_list", + "terms_set_bounds", + "terms_set_scheme", + "timetable_export", + "timetable_import", +] diff --git a/server/app/api/manage/_common.py b/server/app/api/manage/_common.py new file mode 100644 index 00000000..85eea2b4 --- /dev/null +++ b/server/app/api/manage/_common.py @@ -0,0 +1,119 @@ +"""What every endpoint of :mod:`app.api.manage` shares: who is asking, and +the few conversions from a row to what goes on the wire. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Any + +from dishka.integrations.fastapi import FromDishka, inject +from fastapi import Depends, HTTPException, status +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_device +from app.models import BotUser, DeviceToken, Role, SchoolClass +from app.services import linking + +# -------------------------------------------------------------------------- +# Who may manage +# -------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Actor: + """Who is making the change: the device, the Telegram account behind it, + and that account's role in the class *right now*.""" + + device: DeviceToken + telegram_id: int + role: Role + + +def _role_at_least(minimum: Role) -> Callable[..., Awaitable[Actor]]: + """A dependency demanding ``minimum`` of the linked account. + + One factory rather than a guard written out in each endpoint, for the + reason the bot keeps ``_allowed`` in one place: a check that is copied is a + check that will eventually be copied wrong. The refusals are the two the + app already knows from ``app.api.edit`` - «привяжите телефон» and «нужна + роль» - with the role named, because the app shows a different screen for + each and an admin-only page has to say «admin», not «editor». + """ + + @inject + async def dependency( + device: DeviceToken = Depends(current_device), + *, + session: FromDishka[AsyncSession], + ) -> Actor: + if device.telegram_id is None: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="device is not linked" + ) + role = await linking.effective_role(session, device) + if role is None or not role.at_least(minimum): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail=f"{minimum.value} role required" + ) + return Actor(device=device, telegram_id=device.telegram_id, role=role) + + return dependency + + +editor_actor = _role_at_least(Role.EDITOR) +admin_actor = _role_at_least(Role.ADMIN) +owner_actor = _role_at_least(Role.OWNER) + + +# -------------------------------------------------------------------------- +# Small shared pieces +# -------------------------------------------------------------------------- + + +def _wall(stamp: datetime | None, school_class: SchoolClass) -> datetime | None: + """A stored UTC stamp on the class's own wall clock. + + ``created_at`` and friends are naive UTC in the database. An admin in + Vladivostok reading a Moscow server's log should not see yesterday evening + against this morning's change, so they are converted here the same way the + bot's ``render_audit`` converts them. + """ + if stamp is None: + return None + return stamp.replace(tzinfo=UTC).astimezone(school_class.tz).replace(tzinfo=None) + + +def _person(full_name: str | None, username: str | None, telegram_id: int | None) -> str: + """The best name we hold for somebody, in the same order the bot picks it. + + Falls back to the numeric id rather than to «неизвестный»: an id is + something an admin can actually act on, and this surface is admin-only. + """ + if username: + return f"@{username}" + if full_name: + return full_name + return str(telegram_id) if telegram_id is not None else "—" + + +async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: + """Telegram id -> the name to show. Plain text: this is JSON, not HTML.""" + members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) + return { + member.telegram_id: _person(member.full_name, member.username, member.telegram_id) + for member in members + } + + +async def _count(session: AsyncSession, model: Any, *where: Any) -> int: + return int(await session.scalar(select(func.count()).select_from(model).where(*where)) or 0) + + +def _conflict(detail: str) -> HTTPException: + """409, for a request that is well-formed and refused by the class's own + state: a name already taken, a schedule days still point at.""" + return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail) diff --git a/server/app/api/manage/bells.py b/server/app/api/manage/bells.py new file mode 100644 index 00000000..c318eb00 --- /dev/null +++ b/server/app/api/manage/bells.py @@ -0,0 +1,296 @@ +"""``/bells``: the class's bell schedules, as «🔔 Звонки» edits them. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from typing import Any + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _conflict, _count, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import BellSchedule, DayOverride, SchoolClass +from app.schemas import ( + BellPeriodOut, + BellPeriodsIn, + BellScheduleIn, + BellScheduleOut, + BellSchedulePatch, + DeletedOut, +) +from app.services import audit, structure + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# 🔔 Bell schedules +# -------------------------------------------------------------------------- + + +def _schedule_out( + schedule: BellSchedule, school_class: SchoolClass, silenced: int = 0 +) -> BellScheduleOut: + return BellScheduleOut( + id=schedule.id, + name=schedule.name, + is_default=schedule.id == school_class.bell_schedule_id, + silenced_lessons=silenced, + periods=[ + BellPeriodOut(index=row.index, starts_at=row.starts_at, ends_at=row.ends_at) + for row in sorted(schedule.periods, key=lambda row: row.index) + ], + ) + + +async def _schedule_or_404( + session: AsyncSession, school_class: SchoolClass, schedule_id: int +) -> BellSchedule: + schedule = await session.scalar( + select(BellSchedule).where( + BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id + ) + ) + if schedule is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown bell schedule") + return schedule + + +def _rows_of(payload: Any) -> list[tuple[int, Any, Any]]: + """The wire shape as ``structure.write_bell_periods`` takes it.""" + return [(row.index, row.starts_at, row.ends_at) for row in payload.periods] + + +@router.get("/bells", response_model=list[BellScheduleOut]) +async def bells_list( + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> list[BellScheduleOut]: + """Every schedule the class keeps - «Обычное», «Сокращённое», «Суббота» - + with the class default marked.""" + rows = await session.scalars( + select(BellSchedule) + .where(BellSchedule.class_id == school_class.id) + .order_by(BellSchedule.id) + ) + return [_schedule_out(row, school_class) for row in rows] + + +@router.post("/bells", response_model=BellScheduleOut, status_code=status.HTTP_201_CREATED) +async def bells_create( + payload: BellScheduleIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> BellScheduleOut: + """A new named schedule, with its rows if they came with it. + + It does not become the class default: a shortened schedule is created in + order to be pointed at by particular days, and making it the default the + moment it exists would move every day onto it. + """ + schedule = BellSchedule(class_id=school_class.id, name=payload.name) + session.add(schedule) + await session.flush() + if payload.periods: + await structure.write_bell_periods(session, schedule, _rows_of(payload)) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "bells.create", + f"создано расписание звонков «{payload.name}»: {len(payload.periods)} уроков", + ) + await session.commit() + await session.refresh(schedule, ["periods"]) + return _schedule_out(schedule, school_class) + + +async def _rung_by_default( + session: AsyncSession, school_class: SchoolClass +) -> set[int]: + """The lesson numbers the class rings today, before anything is changed. + + An empty set when the class has no default at all, which is the honest + reading: nothing was ringing, so nothing can stop. + """ + if school_class.bell_schedule_id is None: + return set() + current = await session.scalar( + select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) + ) + return {period.index for period in current.periods} if current is not None else set() + + +@router.patch("/bells/{schedule_id}", response_model=BellScheduleOut) +async def bells_update( + schedule_id: int, + payload: BellSchedulePatch, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> BellScheduleOut: + """Rename a schedule, or make it the one the class runs on by default. + + ``is_default: false`` is refused: a class with no default schedule has no + times for an ordinary day, so the way to stop using this one is to make + another one the default. + """ + schedule = await _schedule_or_404(session, school_class, schedule_id) + silenced: list[tuple[int, int]] = [] + + if payload.name is not None and payload.name != schedule.name: + old_name = schedule.name + schedule.name = payload.name + await audit.record( + session, + school_class.id, + actor.telegram_id, + "bells.rename", + f"звонки «{old_name}» → «{payload.name}»", + ) + + if payload.is_default is not None: + if not payload.is_default: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="make another schedule the default instead", + ) + # A schedule may be created empty and filled in afterwards, which is + # the point of the two-step flow — but the class default is what every + # ordinary day rings, and a default that rings nothing draws nothing: + # no lesson on any weekday can be placed on a timeline, so `/bundle` + # answers zero lessons, `/now` answers «day_off» on a Monday, and the + # phone, the widget, the calendar feed and the morning digest all go + # blank at once with nothing anywhere reporting a problem. Worse, + # `rung_indexes` then returns an empty set, which `can_ring` reads as + # «this class has not set its bells up yet» and waves every lesson + # number through. `edit.day_put` refuses the same thing at day level. + if not schedule.periods: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="в этом расписании звонков нет ни одного урока", + ) + if school_class.bell_schedule_id != schedule.id: + # Moving the default to a *shorter* schedule takes lessons off + # every weekday exactly as shrinking the current one does — the + # rows past its last rung stay in the database and are drawn, + # logged and announced nowhere. `write_bell_periods` has answered + # this question since the other way in was closed, but it is only + # reached when a schedule's rows are rewritten, and re-pointing + # the class rewrites none. Asked here with the incoming + # schedule's numbers, through the same function, so the two + # cannot answer differently. + # What the class rang a moment ago, against what it will ring + # now. Asking only the incoming schedule counts rows that were + # already silent, which said «перестали звонить уроков: N» on a + # move to a schedule ringing exactly the same numbers. + was = await _rung_by_default(session, school_class) + silenced = await structure.lessons_silenced_by( + session, + school_class.id, + was, + {period.index for period in schedule.periods}, + ) + school_class.bell_schedule_id = schedule.id + summary = f"основное расписание звонков: «{schedule.name}»" + if silenced: + summary += f", перестали звонить уроков: {len(silenced)}" + await audit.record( + session, + school_class.id, + actor.telegram_id, + "bells.default", + summary, + ) + + await session.commit() + await session.refresh(schedule, ["periods"]) + return _schedule_out(schedule, school_class, len(silenced)) + + +@router.put("/bells/{schedule_id}/periods", response_model=BellScheduleOut) +async def bells_periods( + schedule_id: int, + payload: BellPeriodsIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> BellScheduleOut: + """Replace a schedule's rows wholesale. + + Wholesale rather than row by row because that is what editing bells is: + the times of the lessons after the one that moved all shift with it, and + sending the six rows that are now true is one intention, not six. + """ + schedule = await _schedule_or_404(session, school_class, schedule_id) + orphaned = await structure.write_bell_periods(session, schedule, _rows_of(payload)) + summary = f"звонки «{schedule.name}»: {len(payload.periods)} уроков" + if orphaned: + # Shrinking the class's own schedule takes lessons off every weekday + # that carried a number past the new last rung. They are still stored + # and they are drawn nowhere, so the log is where an admin finds out. + summary += f", перестали звонить уроков: {len(orphaned)}" + await audit.record( + session, + school_class.id, + actor.telegram_id, + "bells.edit", + summary, + ) + await session.commit() + await session.refresh(schedule, ["periods"]) + return _schedule_out(schedule, school_class, len(orphaned)) + + +@router.delete("/bells/{schedule_id}", response_model=DeletedOut) +async def bells_delete( + schedule_id: int, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> DeletedOut: + """Refused for the class default and for anything a day still points at. + + Both are a ``SET NULL`` at the database level, which would silently move + those days onto the default schedule - a change nobody asked for, on dates + an admin is not looking at. + """ + schedule = await _schedule_or_404(session, school_class, schedule_id) + + if schedule.id == school_class.bell_schedule_id: + raise _conflict("this is the class default; make another one the default first") + + used = await _count( + session, + DayOverride, + DayOverride.class_id == school_class.id, + DayOverride.bell_schedule_id == schedule.id, + ) + if used: + raise _conflict(f"{used} special day(s) still use this schedule") + + name = schedule.name + await session.delete(schedule) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "bells.delete", + f"удалено расписание звонков «{name}»", + ) + await session.commit() + return DeletedOut(id=schedule_id) diff --git a/server/app/api/manage/classes.py b/server/app/api/manage/classes.py new file mode 100644 index 00000000..53ec429d --- /dev/null +++ b/server/app/api/manage/classes.py @@ -0,0 +1,199 @@ +"""``/class``: the card «⚙️ Класс» shows, its settings, and deleting the class. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +import logging + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _count, admin_actor, owner_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import AccessRequest, BotUser, DeviceToken, JoinMode, SchoolClass +from app.schemas import ClassDeleteIn, ClassPatch, DeletedOut, ManagedClassOut +from app.services import audit +from app.services import terms as terms_service +from app.timezones import is_supported, label_for + +log = logging.getLogger(__name__) + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# ⚙️ The class card +# -------------------------------------------------------------------------- + + +async def _class_out(session: AsyncSession, school_class: SchoolClass) -> ManagedClassOut: + return ManagedClassOut( + id=school_class.id, + name=school_class.name, + school=school_class.school, + city=school_class.city, + timezone=school_class.timezone_name, + timezone_label=label_for(school_class.timezone_name), + join_code=school_class.join_code, + members=await _count(session, BotUser, BotUser.class_id == school_class.id), + devices=await _count( + session, + DeviceToken, + DeviceToken.class_id == school_class.id, + DeviceToken.revoked.is_(False), + ), + pending_requests=await _count( + session, + AccessRequest, + AccessRequest.class_id == school_class.id, + AccessRequest.status == "pending", + ), + bell_schedule_id=school_class.bell_schedule_id, + calendar_ready=bool(school_class.calendar_token), + # `.value`, so the wire says «open». The column stores the member name + # because that is how SQLAlchemy persists an enum, and the two are not + # the same string. + join_mode=school_class.join_mode.value, + ) + + +@router.get("/class", response_model=ManagedClassOut) +async def class_card( + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> ManagedClassOut: + """What «⚙️ Класс» shows, as data.""" + return await _class_out(session, school_class) + + +@router.patch("/class", response_model=ManagedClassOut) +async def class_update( + payload: ClassPatch, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> ManagedClassOut: + """Rename the class, re-home it, move its time zone, or change who may join. + + One audit line per field changed rather than one for the request, because + that is what the log is read for: «что изменилось», not «кто открыл + настройки». Changing the zone moves no stored time - a bell rings at 08:30 + whatever the zone says - it changes which instant the class calls «сейчас». + + Moving the grade or the letter recomposes the name, because that is where + the name came from; a name sent in the same request wins over both. + """ + changes = payload.model_dump(exclude_unset=True) + zone = changes.pop("timezone", None) + mode = changes.pop("join_mode", None) + if "letter" in changes: + # The same rule the bot's «Буква» step applies, not a second one. It + # trims, and it reads «-» as «no letter» — which is what the bot tells + # people to send and what the phone's own field offers. Stored raw, a + # «-» became the literal name «9-» and a padded « А » a `letter` that + # never equals the «А» anything compares it with, while `compose_name` + # trimmed on its way past and left the name looking correct. + changes["letter"] = terms_service.normalise_letter(changes["letter"]) + if zone is not None and not is_supported(zone): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="unknown timezone", + ) + + for column, value in changes.items(): + setattr(school_class, column, value) + await audit.record( + session, + school_class.id, + actor.telegram_id, + f"class.{column}", + f"{column}: {value or 'убрано'}", + ) + if zone is not None: + school_class.timezone = zone + await audit.record( + session, + school_class.id, + actor.telegram_id, + "class.timezone", + f"часовой пояс: {zone}", + ) + if ("grade" in changes or "letter" in changes) and "name" not in changes: + # A class moved from 9 to 10 is not called «9А» any more. The name was + # composed from these two at creation (`bot/handlers/start.py`), and a + # move that left the old name standing showed the wrong class on every + # screen that prints one. Unless the same request also names the class: + # an admin who typed a name has said what they want, and recomposing + # over it would overrule them within the one request. + composed = terms_service.compose_name( + school_class.grade, school_class.letter, fallback=school_class.name + ) + if composed != school_class.name: + school_class.name = composed + await audit.record( + session, + school_class.id, + actor.telegram_id, + "class.name", + f"name: {composed}", + ) + if mode is not None: + # Through the enum rather than by the string, because the attribute is + # read back as one by `_class_out` in this same request - and because + # the audit line should say what changed rather than echo a wire value. + school_class.join_mode = JoinMode(mode) + await audit.record( + session, + school_class.id, + actor.telegram_id, + # The same action name the bot's own toggle writes, so the log + # reads as one history however the switch was flipped. + "access.join_mode", + "вход только по личным приглашениям" + if school_class.join_mode is JoinMode.INVITE + else "вход по коду класса снова разрешён", + ) + + await session.commit() + return await _class_out(session, school_class) + + +@router.delete("/class", response_model=DeletedOut) +async def class_delete( + payload: ClassDeleteIn, + actor: Actor = Depends(owner_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> DeletedOut: + """Delete the class and everything hanging off it. Owner only. + + ``confirm_name`` must be the class's name, exactly as the bot makes an + owner type it back: a confirmation dialog is answered by the same thumb + that opened it, while a name has to be read off the screen first. The app + will show its own «вы уверены» sheet, but the check that matters is this + one, because the endpoint is reachable without the sheet. + + Nothing is written to the audit log: the log lives in the class and goes + with it. Every device token goes too, so the caller's own token stops + working - which is correct, there is nothing left for it to read. + """ + if payload.confirm_name.strip() != school_class.name: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="confirm_name does not match the class name", + ) + + class_id = school_class.id + log.info("class %s deleted by %s", class_id, actor.telegram_id) + await session.delete(school_class) + await session.commit() + return DeletedOut(id=class_id) diff --git a/server/app/api/manage/devices.py b/server/app/api/manage/devices.py new file mode 100644 index 00000000..ebe44180 --- /dev/null +++ b/server/app/api/manage/devices.py @@ -0,0 +1,163 @@ +"""``/devices``: the phones on the class, as «📱 Устройства» lists them. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +import logging + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, Query, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _conflict, _member_names, _wall, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import DeviceToken, Role, SchoolClass +from app.schemas import ManagedDeviceOut +from app.services import audit, linking + +log = logging.getLogger(__name__) + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# 📱 Devices +# -------------------------------------------------------------------------- + + +def _device_out( + device: DeviceToken, + school_class: SchoolClass, + names: dict[int, str], + role: Role | None, +) -> ManagedDeviceOut: + return ManagedDeviceOut( + id=device.id, + device_name=device.device_name, + linked=device.is_linked, + owner=names.get(device.telegram_id) if device.telegram_id is not None else None, + role=role.value if role is not None else None, + revoked=device.revoked, + created_at=_wall(device.created_at, school_class), + last_seen_at=_wall(device.last_seen_at, school_class), + linked_at=_wall(device.linked_at, school_class), + ) + + +async def _device_or_404( + session: AsyncSession, school_class: SchoolClass, device_id: int +) -> DeviceToken: + device = await session.scalar( + select(DeviceToken).where( + DeviceToken.id == device_id, DeviceToken.class_id == school_class.id + ) + ) + if device is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown device") + return device + + +@router.get("/devices", response_model=list[ManagedDeviceOut]) +async def devices_list( + include_revoked: bool = Query(default=False), + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> list[ManagedDeviceOut]: + """The phones on the class's list, oldest first. + + The role is a lookup, not a stored field: a device acts with whatever role + its owner holds right now, so revoking somebody in the bot has already + changed this list by the time it is drawn. ``include_revoked`` brings back + the ones that were switched off, which the bot's page leaves out. + """ + devices = await linking.devices_of(session, school_class.id, include_revoked=include_revoked) + names = await _member_names(session, school_class.id) + # Once per owner, not once per phone: the role hangs off the account, and a + # class where everybody joined from their own phone was paying a round trip + # a row for an answer already in hand. «📱 Устройства» in the bot resolves + # it the same way. + roles: dict[int, Role | None] = {} + for device in devices: + if device.telegram_id is not None and device.telegram_id not in roles: + roles[device.telegram_id] = await linking.effective_role(session, device) + return [ + _device_out(device, school_class, names, roles.get(device.telegram_id)) + for device in devices + ] + + +@router.post("/devices/{device_id}/revoke", response_model=ManagedDeviceOut) +async def device_revoke( + device_id: int, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> ManagedDeviceOut: + """Switch a phone off. Revoked, not deleted: the row is what a token is + checked against, and keeping it is what makes the refusal instant and + permanent. Revoking an already revoked device changes nothing and adds no + second line to the log. + + An admin may do this to the phone they are holding, and then the next + request from it is a 401. That is the point - it is how a lost phone is + dealt with from the one that is still in a pocket. + """ + device = await _device_or_404(session, school_class, device_id) + names = await _member_names(session, school_class.id) + role = await linking.effective_role(session, device) + if device.revoked: + return _device_out(device, school_class, names, role) + + device.revoked = True + name = device.device_name or f"Устройство {device.id}" + await audit.record( + session, + school_class.id, + actor.telegram_id, + "device.revoke", + f"отключено устройство «{name}»", + ) + await session.commit() + return _device_out(device, school_class, names, role) + + +@router.post("/devices/{device_id}/unlink", response_model=ManagedDeviceOut) +async def device_unlink( + device_id: int, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> ManagedDeviceOut: + """Back to read-only, without taking the phone off the class. + + The device keeps reading the timetable and loses the role it borrowed from + its owner's account. A device that is not linked has nothing to unlink, + which is a 409 rather than a silent success: the admin pressed it expecting + something to change. + """ + device = await _device_or_404(session, school_class, device_id) + if device.telegram_id is None: + raise _conflict("device is not linked") + + name = device.device_name or f"Устройство {device.id}" + await linking.unlink_device(session, device) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "device.unlink", + f"отвязано устройство «{name}» — снова только чтение", + ) + await session.commit() + names = await _member_names(session, school_class.id) + role = await linking.effective_role(session, device) + return _device_out(device, school_class, names, role) diff --git a/server/app/api/manage/journal.py b/server/app/api/manage/journal.py new file mode 100644 index 00000000..0ee5b7a4 --- /dev/null +++ b/server/app/api/manage/journal.py @@ -0,0 +1,65 @@ +"""``/log``: «📜 Журнал», a page at a time. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, Query +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _member_names, _wall, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import AuditEntry, SchoolClass +from app.schemas import AuditEntryOut, AuditPageOut +from app.services import audit + +router = APIRouter(route_class=DishkaAnnotatedRoute) + +#: Audit lines per page, matching «📜 Журнал» in the bot. +AUDIT_PAGE = 30 + + +# -------------------------------------------------------------------------- +# 📜 The audit log +# -------------------------------------------------------------------------- + + +@router.get("/log", response_model=AuditPageOut) +async def audit_log( + limit: int = Query(default=AUDIT_PAGE, ge=1, le=100), + offset: int = Query(default=0, ge=0), + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> AuditPageOut: + """Who changed what, newest first. + + One row more than ``limit`` is read and thrown away: that is what + ``has_more`` is, and it costs one row instead of the count of an + append-only table on every page turn. + """ + entries = await audit.recent(session, school_class.id, limit=limit + 1, offset=offset) + has_more = len(entries) > limit + entries = entries[:limit] + names = await _member_names(session, school_class.id) + + def _entry(row: AuditEntry) -> AuditEntryOut: + return AuditEntryOut( + id=row.id, + action=row.action, + summary=row.summary, + who=names.get(row.telegram_id) if row.telegram_id is not None else None, + at=_wall(row.created_at, school_class), + ) + + return AuditPageOut( + entries=[_entry(row) for row in entries], + limit=limit, + offset=offset, + has_more=has_more, + ) diff --git a/server/app/api/manage/requests.py b/server/app/api/manage/requests.py new file mode 100644 index 00000000..bd58d0fc --- /dev/null +++ b/server/app/api/manage/requests.py @@ -0,0 +1,188 @@ +"""``/requests``: the access requests waiting for an admin, and the answer. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime +from html import escape +from typing import Any + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _member_names, _person, _wall, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.config import get_settings +from app.models import AccessRequest, Role, SchoolClass +from app.schemas import AccessRequestOut, RequestDecisionIn, RequestDecisionOut +from app.services import access as access_service +from app.services import audit + +log = logging.getLogger(__name__) + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +def _build_bot() -> Any | None: + """A bot for one send, or ``None`` when the deployment has no token. + + Imported lazily: aiogram costs seconds to import and a management endpoint + should not pay that on a deployment that has no bot to notify with. One + per router module, as in ``app.api.edit`` and ``app.api.cron`` - it is the + seam the tests replace. + """ + if not get_settings().bot_token: + return None + from app.bot.bot import build_bot + + return build_bot() + + +async def _tell(telegram_id: int, text: str) -> None: + """Tell one person what was decided. Never fails the request: the decision + is already committed, and a Telegram outage does not undo it.""" + bot = _build_bot() + if bot is None: + return + try: + await bot.send_message(telegram_id, text) + except Exception: # noqa: BLE001 - see the docstring + log.warning("could not tell %s about the decision", telegram_id, exc_info=True) + finally: + bot_session = getattr(bot, "session", None) + if bot_session is not None: + await bot_session.close() + + +# -------------------------------------------------------------------------- +# 🙋 Access requests +# -------------------------------------------------------------------------- + + +async def _request_or_404( + session: AsyncSession, school_class: SchoolClass, request_id: int +) -> AccessRequest: + """Pending, and this class's. A request that has already been answered is + gone as far as this endpoint is concerned, so two admins tapping «Выдать» + at once cannot grant twice.""" + request = await session.scalar( + select(AccessRequest).where( + AccessRequest.id == request_id, + AccessRequest.class_id == school_class.id, + AccessRequest.status == "pending", + ) + ) + if request is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown request") + return request + + +@router.get("/requests", response_model=list[AccessRequestOut]) +async def requests_list( + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> list[AccessRequestOut]: + """Everybody waiting for a role, oldest first.""" + rows = list( + await session.scalars( + select(AccessRequest) + .where(AccessRequest.class_id == school_class.id, AccessRequest.status == "pending") + .order_by(AccessRequest.id) + ) + ) + names = await _member_names(session, school_class.id) + return [ + AccessRequestOut( + id=row.id, + who=names.get(row.telegram_id, str(row.telegram_id)), + requested_role=row.requested_role.value, + message=row.message, + created_at=_wall(row.created_at, school_class), + ) + for row in rows + ] + + +@router.post("/requests/{request_id}/approve", response_model=RequestDecisionOut) +async def request_approve( + request_id: int, + payload: RequestDecisionIn | None = None, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> RequestDecisionOut: + """Grant the role, through the same rules as «👥 Доступ» in the bot. + + Literally the same rules: `services/access.approve_request` is what the + bot's own «✅ Выдать» calls, so the two surfaces cannot drift apart. The + only thing this one does differently is let an admin answer with a role + other than the one asked for - which `can_grant` still gates, inside the + service. + + The requester is told in Telegram, because that is where they asked. + """ + request = await _request_or_404(session, school_class, request_id) + target = Role(payload.role) if payload is not None and payload.role else request.requested_role + + try: + member = await access_service.approve_request( + session, + school_class, + request, + actor_id=actor.telegram_id, + actor_role=actor.role, + role=target, + ) + except access_service.GrantRefused as refused: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail=refused.detail + ) from refused + + who = _person(member.full_name, member.username, member.telegram_id) + await session.commit() + + await _tell(request.telegram_id, access_service.approval_notice(school_class, target)) + return RequestDecisionOut(id=request_id, status="approved", role=target.value, who=who) + + +@router.post("/requests/{request_id}/decline", response_model=RequestDecisionOut) +async def request_decline( + request_id: int, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> RequestDecisionOut: + """Say no. The person keeps whatever role they already had, and is told - + silence would leave them asking again.""" + request = await _request_or_404(session, school_class, request_id) + names = await _member_names(session, school_class.id) + who = names.get(request.telegram_id, str(request.telegram_id)) + + request.status = "declined" + request.decided_by = actor.telegram_id + request.decided_at = datetime.now(UTC).replace(tzinfo=None) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "access.decline", + f"отклонён запрос доступа от {request.telegram_id}", + ) + await session.commit() + + await _tell( + request.telegram_id, + f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", + ) + return RequestDecisionOut(id=request_id, status="declined", who=who) diff --git a/server/app/api/manage/schools.py b/server/app/api/manage/schools.py new file mode 100644 index 00000000..8c26f3db --- /dev/null +++ b/server/app/api/manage/schools.py @@ -0,0 +1,74 @@ +"""``/schools``: the school directory, looked up before ``PATCH /class``. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Query, status + +from app.api.deps import current_class +from app.api.manage._common import Actor, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import SchoolClass +from app.providers import dadata +from app.schemas import SchoolOut, SchoolSearchOut +from app.services import schools as schools_service + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +@router.get("/schools", response_model=SchoolSearchOut) +async def schools_search( + q: str = Query(..., description="Название или номер школы"), + page: int = Query(1, ge=1), + page_size: int = Query( + schools_service.PAGE_SIZE, + ge=1, + le=dadata.MAX_SUGGESTIONS, + description="Строк на странице; 20 отдаёт всё найденное за один запрос", + ), + region: str | None = Query(None, max_length=120), + _: Actor = Depends(admin_actor), + __: SchoolClass = Depends(current_class), +) -> SchoolSearchOut: + """Search the school directory, the same way «⚙️ Класс» does in the bot. + + Reads nothing and writes nothing: it is a lookup the app needs before it + can `PATCH /class` with a school name, and the name is all that is stored. + Admin-only despite being read-only, because every call spends part of a + daily allowance somebody else pays for, and the class's own members are the + only people with a reason to spend it. + + 503 rather than 500 when the directory is not configured or not answering: + nothing here is broken, the feature is simply unavailable right now, and + the client's answer to that is to let the name be typed. + + **Every call is one upstream search**, whatever ``page`` says — the + directory has no offset to page with, so there is nothing to resume. A + client that pages should therefore ask once with ``page_size=20`` and cut + the answer up itself, which is what the bot and the app both do; asking for + four pages of five is four searches for one question. + """ + try: + result = await schools_service.search(q, region=region) + except schools_service.SearchError as error: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) + ) from error + except dadata.DirectoryError as error: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=error.message + ) from error + + found = schools_service.page_of( + result.schools, page, size=page_size, truncated=result.truncated + ) + return SchoolSearchOut( + items=[SchoolOut(**school.model_dump()) for school in found.items], + page=found.page, + pages=found.pages, + total=found.total, + truncated=found.truncated, + ) diff --git a/server/app/api/manage/statistics.py b/server/app/api/manage/statistics.py new file mode 100644 index 00000000..d20b5fff --- /dev/null +++ b/server/app/api/manage/statistics.py @@ -0,0 +1,55 @@ +"""``/stats``: the numbers «📊 Статистика» shows. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, editor_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import SchoolClass +from app.schemas import StatsOut, SubjectHoursOut +from app.services import stats as stats_service + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# 📊 Stats +# -------------------------------------------------------------------------- + + +@router.get("/stats", response_model=StatsOut) +async def stats( + _: Actor = Depends(editor_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> StatsOut: + """The numbers «📊 Статистика» shows, without the sentence around them. + + An editor may read them, as in the bot: they say whether the timetable is + complete and whether homework is being entered, which is exactly what the + person entering it wants to know. + """ + numbers = await stats_service.class_stats(session, school_class) + return StatsOut( + today=numbers["today"], + lessons_per_week=numbers["lessons_per_week"], + subjects_count=numbers["subjects_count"], + subjects=[ + SubjectHoursOut(name=name, hours=hours) for name, hours in numbers["subjects"] + ], + homework_open=numbers["homework_open"], + homework_total=numbers["homework_total"], + members_by_role={role.value: count for role, count in numbers["members_by_role"].items()}, + devices_active=numbers["devices_active"], + overrides_upcoming=numbers["overrides_upcoming"], + events_upcoming=numbers["events_upcoming"], + ) diff --git a/server/app/api/manage/subjects.py b/server/app/api/manage/subjects.py new file mode 100644 index 00000000..88d92cb6 --- /dev/null +++ b/server/app/api/manage/subjects.py @@ -0,0 +1,228 @@ +"""``/subjects``: the class's subject dictionary, as «📚 Предметы» edits it. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, _conflict, admin_actor, editor_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import SchoolClass, Subject +from app.schemas import DeletedOut, ManagedSubjectOut, SubjectIn, SubjectPatch, SubjectSavedOut +from app.services import audit, structure +from app.services import subjects as subjects_service + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# 📚 Subjects +# -------------------------------------------------------------------------- + + +def _subject_out(subject: Subject) -> ManagedSubjectOut: + return ManagedSubjectOut( + id=subject.id, + name=subject.name, + short_name=subject.short_name, + teacher=subject.teacher, + color=subject.color, + ) + + +async def _subject_or_404( + session: AsyncSession, school_class: SchoolClass, subject_id: int +) -> Subject: + subject = await session.scalar( + select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) + ) + if subject is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown subject") + return subject + + +async def _name_taken( + session: AsyncSession, class_id: int, name: str, *, besides: int | None = None +) -> bool: + """Ignores case, because everything downstream of it does.""" + return await subjects_service.clashing(session, class_id, name, besides=besides) is not None + + +@router.get("/subjects", response_model=list[ManagedSubjectOut]) +async def subjects_list( + _: Actor = Depends(editor_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> list[ManagedSubjectOut]: + """The dictionary with ids, for a screen that edits it. An editor may + read it - it is the same list ``GET /api/v1/subjects`` gives any device. + + Adopts whatever the timetable already uses on the way, so this list is + never emptily lying about a class with thirty-five lessons in it. Free once + the two agree, which after the first read they do. + """ + # Committed whatever the count says, the way `public.bundle` does it. The + # number that comes back is how many dictionary entries were *created*, and + # the function also links the timetable rows to them — so a class whose + # dictionary was already complete but whose lessons were not yet pointed at + # it got its UPDATEs run and then dropped when the session closed, on every + # read, forever. It healed only because `/bundle` commits unconditionally + # and a phone polls it; the screen that exists to edit this list did the + # work and threw it away. + await subjects_service.sync_from_timetable(session, school_class.id) + await session.commit() + rows = await session.scalars( + select(Subject).where(Subject.class_id == school_class.id).order_by(Subject.name) + ) + return [_subject_out(row) for row in rows] + + +@router.post("/subjects", response_model=SubjectSavedOut, status_code=status.HTTP_201_CREATED) +async def subject_create( + payload: SubjectIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> SubjectSavedOut: + """Add a subject. The name is unique within the class - that uniqueness is + the whole point of the dictionary, so a duplicate is a 409, not a silent + second «Алгебра».""" + if await _name_taken(session, school_class.id, payload.name): + raise _conflict("a subject with that name is already in this class") + + subject = Subject( + class_id=school_class.id, + name=payload.name, + short_name=payload.short_name, + teacher=payload.teacher, + color=payload.color, + ) + session.add(subject) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "subject.add", + f"добавлен предмет «{payload.name}»", + ) + await session.commit() + await session.refresh(subject) + return SubjectSavedOut(subject=_subject_out(subject)) + + +@router.patch("/subjects/{subject_id}", response_model=SubjectSavedOut) +async def subject_update( + subject_id: int, + payload: SubjectPatch, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> SubjectSavedOut: + """Rename a subject, or set its short name, teacher or colour. + + A rename is a cascade: the timetable, the homework and the substitutions store the + subject as text, so all three move with it in this one transaction, and + ``moved`` says how many rows did. Renaming onto a name the class already + uses is refused - merging two subjects is a different operation, and doing + it by accident cannot be undone. + """ + subject = await _subject_or_404(session, school_class, subject_id) + changes = payload.model_dump(exclude_unset=True) + new_name = changes.pop("name", None) + moved = 0 + + if new_name is not None and new_name != subject.name: + if await _name_taken(session, school_class.id, new_name, besides=subject.id): + raise _conflict("a subject with that name is already in this class") + # The dictionary check above cannot see this one: homework may be + # written under a name that is not a dictionary entry, and homework is + # unique per subject per day. See `structure.homework_clashing`. + clash = await structure.homework_clashing( + session, school_class.id, subject.name, new_name + ) + if clash: + days = ", ".join(day.isoformat() for day in clash) + raise _conflict( + f"homework under both names on the same day: {days}" + ) + old_name = subject.name + moved = await structure.rename_subject(session, school_class.id, subject, new_name) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "subject.rename", + f"предмет «{old_name}» → «{new_name}», строк обновлено: {moved}", + ) + + #: Column -> (audit tag, the word the log line uses). The bot writes the + #: colour as «цвет», not «color», and the two logs are read side by side. + labels = { + "short_name": ("subject.short_name", "сокращение"), + "teacher": ("subject.teacher", "учитель"), + "color": ("subject.colour", "цвет"), + } + for column, value in changes.items(): + setattr(subject, column, value) + action, label = labels[column] + await audit.record( + session, + school_class.id, + actor.telegram_id, + action, + f"{label} предмета «{subject.name}»: {value or 'убрано'}", + ) + + await session.commit() + await session.refresh(subject) + return SubjectSavedOut(subject=_subject_out(subject), moved=moved) + + +@router.delete("/subjects/{subject_id}", response_model=DeletedOut) +async def subject_delete( + subject_id: int, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> DeletedOut: + """Deleting a subject the timetable still uses is refused. + + It used to be allowed, and it left the lessons alone: the timetable stores + the name as well as the link, so the class kept its timetable and lost + only the colour and the teacher. That stopped being true when the + dictionary started keeping itself. The name is still in the template, so + the next read adopts it again - the entry returns within one poll, without + its colour, its short name or its teacher, and the admin is left believing + they deleted something. + + So the two halves of one list are deleted in one order: take the subject + out of the weekly template, and then out of the dictionary. A subject + nothing teaches still deletes in one step, which is the case this endpoint + was really for. + """ + subject = await _subject_or_404(session, school_class, subject_id) + in_use = await subjects_service.lessons_using(session, school_class.id, subject) + if in_use: + raise _conflict(f"{in_use} lesson(s) still use this subject") + name = subject.name + await session.delete(subject) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "subject.delete", + f"удалён предмет «{name}»", + ) + await session.commit() + return DeletedOut(id=subject_id) diff --git a/server/app/api/manage/terms.py b/server/app/api/manage/terms.py new file mode 100644 index 00000000..83dee910 --- /dev/null +++ b/server/app/api/manage/terms.py @@ -0,0 +1,134 @@ +"""``/terms``: the class's quarters or half-years, as «🗓 Четверти» edits them. + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from datetime import datetime + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.models import SchoolClass, TermKind +from app.schemas import TermBoundsIn, TermOut, TermSchemeIn, TermsOut +from app.services import audit +from app.services import terms as terms_service + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# Quarters and half-years +# +# The same service the bot's editor calls, for the same reason the rest of +# this module does it that way: «пересекается с периодом 2» decided twice +# disagrees within a month. +# -------------------------------------------------------------------------- + + +def _terms_out(school_class: SchoolClass, year: int, rows) -> TermsOut: + return TermsOut( + kind=terms_service.scheme_of(school_class).value, + year=year, + terms=[ + TermOut( + index=term.index, + kind=term.kind.value, + starts_on=term.starts_on, + ends_on=term.ends_on, + ) + for term in rows + ], + ) + + +def _term_year(school_class: SchoolClass) -> int: + """The school year in force for this class, in the class's own zone.""" + return terms_service.opening_year_of(datetime.now(school_class.tz).date()) + + +@router.get("/terms", response_model=TermsOut) +async def terms_list( + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> TermsOut: + """This class's terms, seeding the conventional set if it has none.""" + year = _term_year(school_class) + rows = await terms_service.ensure(session, school_class, year) + await session.commit() + return _terms_out(school_class, year, rows) + + +@router.put("/terms/scheme", response_model=TermsOut) +async def terms_set_scheme( + payload: TermSchemeIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> TermsOut: + """Switch between quarters and half-years, reseeding the year. + + A replacement rather than an edit: four quarters and two halves do not map + onto each other, and a leftover third quarter inside a year that has two is + not a state worth keeping. + """ + year = _term_year(school_class) + wanted = TermKind(payload.kind) + rows = await terms_service.set_scheme(session, school_class, wanted, year) + await audit.record( + session, + school_class.id, + actor.telegram_id, + "class.term_kind", + f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", + ) + await session.commit() + return _terms_out(school_class, year, rows) + + +@router.put("/terms/{index}", response_model=TermsOut) +async def terms_set_bounds( + index: int, + payload: TermBoundsIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> TermsOut: + """Move one term's edges. + + 422 with the service's own Russian sentence rather than a field-shaped + error: what is wrong is the relationship between this term and the year or + its neighbours, and «конец периода раньше его начала» is the thing worth + putting on the screen. + """ + year = _term_year(school_class) + await terms_service.ensure(session, school_class, year) + try: + await terms_service.set_bounds( + session, school_class, year, index, payload.starts_on, payload.ends_on + ) + except terms_service.TermError as error: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) + ) from error + + await audit.record( + session, + school_class.id, + actor.telegram_id, + "class.term", + f"период {index}: {payload.starts_on:%d.%m.%Y} — {payload.ends_on:%d.%m.%Y}", + ) + await session.commit() + rows = await terms_service.read(session, school_class.id, year) + return _terms_out(school_class, year, rows) diff --git a/server/app/api/manage/timetable.py b/server/app/api/manage/timetable.py new file mode 100644 index 00000000..9d99650e --- /dev/null +++ b/server/app/api/manage/timetable.py @@ -0,0 +1,148 @@ +"""``/timetable``: the weekly template as text, «📤 Экспорт» and «📥 Импорт». + +Part of :mod:`app.api.manage`; the rules every endpoint of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.deps import current_class +from app.api.manage._common import Actor, admin_actor +from app.api.routing import DishkaAnnotatedRoute +from app.bot.render import WEEKDAYS +from app.models import BellSchedule, SchoolClass, TimetableEntry +from app.schemas import ImportConflictOut, TimetableExportOut, TimetableImportIn, TimetableImportOut +from app.services import audit, structure, timetable_io + +router = APIRouter(route_class=DishkaAnnotatedRoute) + + +# -------------------------------------------------------------------------- +# 📤 Export and 📥 import +# -------------------------------------------------------------------------- + + +@router.get("/timetable", response_model=TimetableExportOut) +async def timetable_export( + _: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> TimetableExportOut: + """The weekly template as the text «📤 Экспорт» sends. + + The same format in both directions, which is what makes it a backup: a + text saved out of the bot goes back in through the app, and the other way + round. An empty timetable is an empty string, not a 404 - there is nothing + wrong with a class that has not filled one in yet. + """ + entries = list( + await session.scalars( + select(TimetableEntry) + .where(TimetableEntry.class_id == school_class.id) + .order_by(TimetableEntry.weekday, TimetableEntry.index) + ) + ) + periods = [] + if school_class.bell_schedule_id: + schedule = await session.get(BellSchedule, school_class.bell_schedule_id) + if schedule is not None: + periods = list(schedule.periods) + return TimetableExportOut( + text=timetable_io.export_timetable(entries, periods), lessons=len(entries) + ) + + +@router.post("/timetable/import", response_model=TimetableImportOut) +async def timetable_import( + payload: TimetableImportIn, + actor: Actor = Depends(admin_actor), + school_class: SchoolClass = Depends(current_class), + *, + session: FromDishka[AsyncSession], +) -> TimetableImportOut: + """Parse a paste and replace exactly the weekdays it names. + + The bot shows a preview and asks «Применить»; an API has no screen to show + one on, so the preview is the refusal: if a weekday in the paste already + has lessons, nothing is written and the response lists what stands to be + overwritten. Sending it again with ``replace: true`` is the second tap. + + Days the paste does not mention are left alone, so importing one day's + block is a legitimate thing to do, and a day named with nothing under it is + emptied - that is how a paste says «в четверг уроков нет». A + ``== Звонки ==`` block replaces the default schedule's rows outright, as it + does in the bot; it is a schedule, not a day, and nothing else points at it. + """ + days, rejected = timetable_io.parse_timetable_block(payload.text) + bells, _rejected_bells = timetable_io.parse_bells_block(payload.text) + if not days and not bells: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="no weekday header and no bells block found in the text", + ) + + existing = await structure.lessons_per_weekday(session, school_class.id, list(days)) + conflicts = [ + ImportConflictOut(weekday=weekday, existing=count, incoming=len(days[weekday])) + for weekday, count in sorted(existing.items()) + if count + ] + if conflicts and not payload.replace: + return TimetableImportOut( + applied=False, + days=sorted(days), + lessons=sum(len(rows) for rows in days.values()), + bells=len(bells), + conflicts=conflicts, + rejected=rejected, + ) + + result = await structure.apply_timetable(session, school_class, days, bells) + total = result.written + schedule = result.schedule + # Reported, not silently dropped: a lesson past the last bell has nowhere + # to be drawn, and «applied: true, lessons: N» with N short of what was + # pasted is exactly the answer that hides it. One line per dropped row, + # named by its weekday: the same number under two weekdays is two lessons + # gone, and while this counted the distinct numbers it admitted to one. + rejected = rejected + [ + f"{WEEKDAYS[weekday - 1]}, урок {index}: " + "нет такого звонка в расписании звонков" + for weekday, index in result.dropped + ] + # The other direction, and the one nothing used to report: these lessons + # were already stored and the bells this import wrote no longer ring them, + # so they are still in the database and drawn nowhere. + rejected = rejected + [ + f"{WEEKDAYS[weekday - 1]}, урок {index}: " + "больше не звонит — новые звонки короче" + for weekday, index in result.orphaned + ] + summary = f"импорт расписания: дней {len(days)}, уроков {total}" + if bells: + summary += f", звонков {len(bells)}" + if result.dropped: + summary += f", без звонка пропущено {len(result.dropped)}" + if result.orphaned: + summary += f", перестали звонить {len(result.orphaned)}" + await audit.record( + session, school_class.id, actor.telegram_id, "timetable.import", summary + ) + await session.commit() + if schedule is not None: + await session.refresh(schedule, ["periods"]) + + return TimetableImportOut( + applied=True, + days=sorted(days), + lessons=total, + bells=len(bells), + conflicts=conflicts, + rejected=rejected, + ) diff --git a/server/app/bot/handlers/manage.py b/server/app/bot/handlers/manage.py deleted file mode 100644 index cb4d118b..00000000 --- a/server/app/bot/handlers/manage.py +++ /dev/null @@ -1,3434 +0,0 @@ -"""Running the class: subjects, special days, bells, devices, the log, import. - -This is the structural half of the bot - everything that shapes what the -day-to-day flows in ``content.py`` and ``timetable.py`` are allowed to say. - -Three rules hold everywhere in this module, and each of them is the answer to -a way the previous shape of this code could be abused: - -* **A role check at the top of every handler, including every FSM step.** - FSM state is per-user and therefore attacker-controlled: a client can set - itself into ``EditSubject.name`` and send a message, so a step that trusted - the step before it would be a rename with no permission check at all. -* **Every id arrives as text and is re-scoped by the query that reads it.** - Callback data is user-supplied. A subject is never fetched by id alone but - by ``(id, class_id)``, so a crafted payload naming another class's row finds - nothing rather than editing it. -* **No state in the process.** Every Vercel invocation is a fresh Python - process, so anything that has to survive a step lives in FSM storage (the - database) or in the callback payload - never in a module-level dict. - -User-supplied text is escaped once, at render time, by ``manage_render``; the -few strings built here are escaped in place for the same reason. -""" - -from __future__ import annotations - -import logging -import re -from datetime import UTC, datetime, timedelta -from datetime import date as Date -from html import escape - -from aiogram import F, Router -from aiogram.filters import Command, CommandObject -from aiogram.fsm.context import FSMContext -from aiogram.types import CallbackQuery, InlineKeyboardButton, Message -from sqlalchemy import func, select -from sqlalchemy.ext.asyncio import AsyncSession - -from app.bot import manage_render as mr -from app.bot import render -from app.bot.handlers.calendar import open_month -from app.bot.handlers.timetable import REJECTED_MAX -from app.bot.keyboards import ( - WEEKDAY_FULL, - DiarySchoolPick, - Menu, - back_to_menu, - cancel_keyboard, -) -from app.bot.manage_keyboards import ( - COLOUR_PRESETS, - DIARY_SCHOOLS_MAX, - PERIOD_KINDS, - AuditAction, - BellsAction, - DayKindAction, - DeviceAction, - ImportAction, - ManageAction, - RequestAction, - SubjectAction, - TermAction, - audit_keyboard, - back_to, - bells_list_keyboard, - bells_pick_keyboard, - class_menu, - colour_keyboard, - day_kind_keyboard, - device_keyboard, - diary_provider_menu, - diary_region_menu, - diary_school_menu, - holiday_list_keyboard, - import_keyboard, - period_kind_keyboard, - request_keyboard, - subject_card_keyboard, - subject_list_keyboard, - switch_keyboard, - terms_menu, -) -from app.bot.manage_states import ( - AddHoliday, - DeleteClass, - EditBellRows, - EditClassField, - EditSubject, - EditTerm, - ImportTimetable, - NewBellSchedule, - RequestAccess, -) -from app.bot.middlewares import prefs_key -from app.bot.render import clamp, more_line, plural -from app.bot.roles import list_memberships -from app.bot.states import BindDiary -from app.config import get_settings -from app.db import SessionLocal -from app.fsm_storage import DatabaseStorage -from app.models import ( - AccessRequest, - BellPeriod, - BellSchedule, - BotUser, - DayKind, - DayOverride, - DeviceToken, - Homework, - Role, - SchoolClass, - Subject, - TermKind, - TimetableEntry, -) -from app.providers.diary.errors import AddressRefused, DiaryError, SignInUnsupported -from app.providers.diary.registry import NETSCHOOL, PETERSBURG -from app.providers.diary.registry import binding as diary_binding -from app.providers.netschool import regions as ns_regions -from app.providers.netschool.client import NetSchoolClient -from app.services import access as access_service -from app.services import audit, diary_link, linking, structure, timetable_io -from app.services import calendar as calendar_service -from app.services import diary as diary_service -from app.services import stats as stats_service -from app.services import subjects as subjects_service -from app.services import terms as terms_service -from app.timezones import label_for - -log = logging.getLogger(__name__) - -router = Router(name="manage") - -NO_ACCESS = "Нет доступа. Откройте /start, чтобы получить его." -NEED_ADMIN = "Только для администраторов" -NEED_EDITOR = "Нужна роль редактора" -NEED_OWNER = "Только для владельца класса" - -#: Days a «📆 Период» may cover in one go. A school year is longer than this, -#: but a period typed by hand is a holiday, and a typo in the year would -#: otherwise write thousands of rows before anybody noticed. -PERIOD_MAX_DAYS = 120 - -#: Homework rows one search may answer with. -SEARCH_MAX = 15 - -#: How far back a search looks. Older homework is history nobody is looking -#: for, and including it makes every search slower and noisier. -SEARCH_BACK_DAYS = 30 - -COLOUR_RE = re.compile(r"^#?([0-9a-fA-F]{6})$") - -SUBJECT_NAME_MAX = 120 -SHORT_NAME_MAX = 16 -TEACHER_MAX = 120 -NOTE_MAX = 300 - - -# -------------------------------------------------------------------------- -# Guards and small parsers -# -------------------------------------------------------------------------- - - -def _allowed(school_class: SchoolClass | None, role: Role | None, minimum: Role) -> bool: - """The whole of the permission check, in one place so no handler invents - its own version of it.""" - return school_class is not None and role is not None and role.at_least(minimum) - - -def _refusal(role: Role | None, minimum: Role) -> str: - if role is None: - return NO_ACCESS - if minimum is Role.OWNER: - return NEED_OWNER - return NEED_ADMIN if minimum is Role.ADMIN else NEED_EDITOR - - -def _int_or_none(raw: str) -> int | None: - """An id out of callback data, or ``None`` for anything a crafted one carries.""" - try: - return int(raw) - except (TypeError, ValueError): - return None - - -def _day_kind_or_none(raw: str) -> DayKind | None: - """A day kind out of callback data or FSM state, or ``None``. - - `DayKind(raw)` raises on anything else, and a raise here leaves the button - spinning until Telegram gives up rather than answering — the same trap the - `_int_or_none` above exists for, on a value that arrives from the client. - """ - try: - return DayKind(raw) - except ValueError: - return None - - -def _date_or_none(raw: str) -> Date | None: - try: - return Date.fromisoformat(raw) - except (TypeError, ValueError): - return None - - -def _today(school_class: SchoolClass) -> Date: - """Today on the class's own wall clock, never the server's.""" - return datetime.now(school_class.tz).date() - - -def _bot_of(event: Message | CallbackQuery): - """The Bot behind an update, or ``None``. - - The handler tests call these functions with plain stubs that have no bot - at all, and a notification is never worth failing the edit it describes. - """ - return getattr(event, "bot", None) - - -def _parse_day(raw: str, today: Date) -> Date | None: - """«12.09» or «12.09.2026» -> a date. - - A bare day and month is read in the current year unless that lands well in - the past: a school year straddles New Year, so «10.01» typed in December - means the January that is coming, not the one that has gone. - - Both conversions are inside the ``try``, and it catches ``OverflowError`` - as well, because ``str.isdigit()`` is not the same question as «will - ``int()`` take this» and ``date()`` does not raise only ``ValueError``. - Every character of «²2.09» is a digit to ``isdigit`` and «²2» is a - ``ValueError`` to ``int``; «12.09.99999999999999999999» converts happily - and then overflows the C long ``date()`` is built on. Either way the - exception went straight past the ``except ValueError`` and out of the - handler — and both callers are `Message` handlers with no callback to - apologise on, so a stuck key on the year bought an answer that never came - and a prompt still waiting for a date, which the next thing typed would be - read as. - """ - parts = [part for part in re.split(r"[.\-/\s]+", raw.strip()) if part] - if len(parts) not in (2, 3) or not all(part.isdigit() for part in parts): - return None - try: - day, month = int(parts[0]), int(parts[1]) - if len(parts) == 3: - year = int(parts[2]) - if year < 100: - year += 2000 - else: - year = today.year - result = Date(year, month, day) - except (ValueError, OverflowError): - return None - if len(parts) == 2 and (today - result).days > 90: - try: - result = Date(year + 1, month, day) - except ValueError: # pragma: no cover - 29 February in a common year - return None - return result - - -async def _pending_requests(session: AsyncSession, class_id: int) -> list[AccessRequest]: - return list( - await session.scalars( - select(AccessRequest) - .where(AccessRequest.class_id == class_id, AccessRequest.status == "pending") - .order_by(AccessRequest.id) - ) - ) - - -async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: - """Telegram id -> the name to show, already escaped by ``manage_render``.""" - members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) - return { - member.telegram_id: mr.person(member.full_name, member.username, member.telegram_id) - for member in members - } - - -# -------------------------------------------------------------------------- -# 📚 Subjects -# -------------------------------------------------------------------------- -# -# The subject dictionary is what keeps «Алгебра», «алгебра» and «Алг.» from -# being three different subjects in the timetable, the homework and the app's -# colour scheme. Renaming one therefore has to move every row that spells the -# old name, in the same transaction - see :func:`_rename_subject`. - - -async def _subjects_of(session: AsyncSession, class_id: int) -> list[Subject]: - return list( - await session.scalars( - select(Subject).where(Subject.class_id == class_id).order_by(Subject.name) - ) - ) - - -async def _subject_view(session: AsyncSession, school_class: SchoolClass, role: Role): - # «📚 Предметы» adopts the timetable's names on the way in, so the list - # cannot be empty while the class has a full timetable. «Собрать из - # расписания» stays: it is now the button for "I have just pasted a day and - # want to see its subjects without leaving", and it is still free to press. - await subjects_service.sync_from_timetable(session, school_class.id) - subjects = await _subjects_of(session, school_class.id) - return mr.render_subjects(subjects), subject_list_keyboard( - subjects, - can_edit=role.at_least(Role.ADMIN), - can_collect=role.at_least(Role.EDITOR), - ) - - -async def _subject_by_id( - session: AsyncSession, school_class: SchoolClass, raw: str -) -> Subject | None: - """Scoped by the query itself: an id naming another class's subject finds - nothing, whatever the callback payload claims.""" - subject_id = _int_or_none(raw) - if subject_id is None: - return None - return await session.scalar( - select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) - ) - - -@router.message(Command("subjects")) -async def cmd_subjects( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return - await state.clear() - text, keyboard = await _subject_view(session, school_class, role) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(SubjectAction.filter(F.action == "list")) -async def subjects_list( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - await state.clear() - text, keyboard = await _subject_view(session, school_class, role) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -@router.callback_query(SubjectAction.filter(F.action == "open")) -async def subject_open( - callback: CallbackQuery, - callback_data: SubjectAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - subject = await _subject_by_id(session, school_class, callback_data.value) - if subject is None: - await callback.answer("Предмет уже удалён", show_alert=True) - return - - await state.clear() - await callback.message.edit_text( - mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) - ) - await callback.answer() - - -#: field tag -> (state to wait in, prompt). The tag travels in callback data, -#: so an unknown one is refused rather than mapped to a default. -_SUBJECT_FIELDS = { - "name": (EditSubject.name, "Новое название предмета:"), - "short": ( - EditSubject.short_name, - "Сокращение для узких экранов, до 16 символов. «-» — убрать:", - ), - "teacher": (EditSubject.teacher, "Кто ведёт предмет? «-» — убрать:"), -} - - -@router.callback_query(SubjectAction.filter(F.action == "field")) -async def subject_field( - callback: CallbackQuery, - callback_data: SubjectAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - field, _, raw_id = callback_data.value.partition(":") - subject = await _subject_by_id(session, school_class, raw_id) - if subject is None: - await callback.answer("Предмет уже удалён", show_alert=True) - return - - await state.update_data(subject_id=subject.id) - - if field == "colour": - await state.set_state(EditSubject.colour) - await callback.message.edit_text( - f"Цвет предмета <b>{escape(subject.name)}</b>: сейчас {mr.swatch(subject.color)}.\n\n" - "Выберите из готовых или пришлите свой в виде <code>#5B6ABF</code>.", - reply_markup=colour_keyboard(subject.id), - ) - await callback.answer() - return - - target = _SUBJECT_FIELDS.get(field) - if target is None: - await callback.answer("Неизвестное поле", show_alert=True) - return - next_state, prompt = target - await state.set_state(next_state) - await callback.message.edit_text( - f"<b>{escape(subject.name)}</b>\n\n{prompt}", reply_markup=cancel_keyboard() - ) - await callback.answer() - - -async def _subject_from_state( - state: FSMContext, session: AsyncSession, school_class: SchoolClass -) -> Subject | None: - data = await state.get_data() - return await _subject_by_id(session, school_class, str(data.get("subject_id", ""))) - - -@router.message(EditSubject.name) -async def subject_rename( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - name = " ".join((message.text or "").split()) - if not 1 <= len(name) <= SUBJECT_NAME_MAX: - await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") - return - - subject = await _subject_from_state(state, session, school_class) - if subject is None: - await state.clear() - await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) - return - if name == subject.name: - await state.clear() - await message.answer("Название не изменилось.", reply_markup=back_to_menu()) - return - - clash = await subjects_service.clashing(session, school_class.id, name, besides=subject.id) - if clash is not None: - await message.answer( - f"Предмет <b>{escape(name)}</b> уже есть. Придумайте другое название:" - ) - return - - days = await structure.homework_clashing(session, school_class.id, subject.name, name) - if days: - listed = ", ".join(f"{day:%d.%m}" for day in days[:5]) - await message.answer( - f"На эти дни уже есть задания и по <b>{escape(subject.name)}</b>, и по " - f"<b>{escape(name)}</b>: {listed}. Уберите одно из них и повторите — " - "иначе переименование потеряется целиком.", - reply_markup=back_to_menu(), - ) - await state.clear() - return - - old_name = subject.name - moved = await structure.rename_subject(session, school_class.id, subject, name) - await audit.record( - session, - school_class.id, - message.from_user.id, - "subject.rename", - f"предмет «{old_name}» → «{name}», строк обновлено: {moved}", - ) - await session.commit() - await state.clear() - - await message.answer( - f"✅ <b>{escape(old_name)}</b> → <b>{escape(name)}</b>.\n" - f"Переименовано в расписании, заданиях и заменах: {moved}.", - reply_markup=subject_card_keyboard(subject.id), - ) - - -async def _save_subject_text( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass, - field: str, - limit: int, - label: str, -) -> None: - """The short-name and teacher steps: same shape, different column.""" - raw = " ".join((message.text or "").split()) - subject = await _subject_from_state(state, session, school_class) - if subject is None: - await state.clear() - await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) - return - - value = None if raw in {"-", "—", ""} else raw[:limit] - setattr(subject, field, value) - await audit.record( - session, - school_class.id, - message.from_user.id, - f"subject.{field}", - f"{label} предмета «{subject.name}»: {value or 'убрано'}", - ) - await session.commit() - await state.clear() - await message.answer( - mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) - ) - - -@router.message(EditSubject.short_name) -async def subject_short_name( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - await _save_subject_text( - message, state, session, school_class, "short_name", SHORT_NAME_MAX, "сокращение" - ) - - -@router.message(EditSubject.teacher) -async def subject_teacher( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - await _save_subject_text( - message, state, session, school_class, "teacher", TEACHER_MAX, "учитель" - ) - - -async def _apply_colour( - session: AsyncSession, - school_class: SchoolClass, - subject: Subject, - telegram_id: int, - colour: str | None, -) -> None: - subject.color = colour - await audit.record( - session, - school_class.id, - telegram_id, - "subject.colour", - f"цвет предмета «{subject.name}»: {colour or 'убран'}", - ) - await session.commit() - - -@router.callback_query(SubjectAction.filter(F.action == "colour")) -async def subject_colour_pick( - callback: CallbackQuery, - callback_data: SubjectAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - raw_id, _, raw_colour = callback_data.value.partition(":") - subject = await _subject_by_id(session, school_class, raw_id) - if subject is None: - await callback.answer("Предмет уже удалён", show_alert=True) - return - - if raw_colour == "none": - colour = None - else: - match = COLOUR_RE.match(raw_colour) - if match is None: - await callback.answer("Неизвестный цвет", show_alert=True) - return - colour = f"#{match.group(1).upper()}" - - await _apply_colour(session, school_class, subject, callback.from_user.id, colour) - await state.clear() - await callback.message.edit_text( - mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) - ) - await callback.answer("Цвет сохранён") - - -@router.message(EditSubject.colour) -async def subject_colour_typed( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - raw = (message.text or "").strip() - subject = await _subject_from_state(state, session, school_class) - if subject is None: - await state.clear() - await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) - return - - if raw in {"-", "—"}: - colour = None - else: - match = COLOUR_RE.match(raw) - if match is None: - presets = ", ".join(value for _, value in COLOUR_PRESETS[:3]) - await message.answer( - "Цвет пишется как <code>#5B6ABF</code> — шесть шестнадцатеричных цифр. " - f"Например: {escape(presets)}. «-» — убрать цвет." - ) - return - colour = f"#{match.group(1).upper()}" - - await _apply_colour(session, school_class, subject, message.from_user.id, colour) - await state.clear() - await message.answer( - mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) - ) - - -@router.callback_query(SubjectAction.filter(F.action == "add")) -async def subject_add( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.set_state(EditSubject.create) - await callback.message.edit_text( - "Название нового предмета:", reply_markup=cancel_keyboard() - ) - await callback.answer() - - -@router.message(EditSubject.create) -async def subject_create( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - name = " ".join((message.text or "").split()) - if not 1 <= len(name) <= SUBJECT_NAME_MAX: - await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") - return - - # Ignores case, so «физика» opens the class's «Физика» instead of founding - # a second row beside it. - existing = await subjects_service.find(session, school_class.id, name) - if existing is not None: - await state.clear() - await message.answer( - f"Предмет <b>{escape(existing.name)}</b> уже есть.", - reply_markup=subject_card_keyboard(existing.id), - ) - return - - subject = Subject(class_id=school_class.id, name=name) - session.add(subject) - await audit.record( - session, school_class.id, message.from_user.id, "subject.add", f"добавлен предмет «{name}»" - ) - await session.commit() - await state.clear() - await message.answer( - mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) - ) - - -@router.callback_query(SubjectAction.filter(F.action == "delete")) -async def subject_delete( - callback: CallbackQuery, - callback_data: SubjectAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Deleting a subject the timetable still uses is refused. - - It used to be allowed, and it left the lessons alone: the template stores - the name as well as the link, so the class kept its timetable and lost - only the colour and the teacher. That stopped being true when the - dictionary started keeping itself — the name is still in the template, so - the next read adopts it back, stripped of its colour and its teacher, and - the admin is left believing they deleted something. - - The order is now stated instead: out of the timetable first, out of the - dictionary second. A subject nothing teaches still goes in one tap. - """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - subject = await _subject_by_id(session, school_class, callback_data.value) - if subject is None: - await callback.answer("Предмет уже удалён", show_alert=True) - return - - in_use = await subjects_service.lessons_using(session, school_class.id, subject) - if in_use: - await callback.answer( - # ``plural`` carries the number itself — printing it again beside - # the call produced «стоит в расписании: 1 1 урок». - f"«{subject.name}» стоит в расписании: " - f"{plural(in_use, 'урок', 'урока', 'уроков')}. " - "Сначала уберите их из расписания.", - show_alert=True, - ) - return - - name = subject.name - await session.delete(subject) - await audit.record( - session, school_class.id, callback.from_user.id, "subject.delete", - f"удалён предмет «{name}»", - ) - await session.commit() - await state.clear() - - text, keyboard = await _subject_view(session, school_class, role) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer(f"Удалён: {name}"[:200]) - - -@router.callback_query(SubjectAction.filter(F.action == "collect")) -async def subjects_collect( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Create a Subject row for every name the timetable already uses. - - An editor may run this: it invents nothing, it only writes down the names - that are already in the class's timetable. - """ - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - names = list( - await session.scalars( - select(TimetableEntry.subject_name) - .where(TimetableEntry.class_id == school_class.id) - .distinct() - ) - ) - known = {subject.name for subject in await _subjects_of(session, school_class.id)} - created = [name for name in sorted(names) if name and name not in known] - for name in created: - session.add(Subject(class_id=school_class.id, name=name[:SUBJECT_NAME_MAX])) - - if created: - await audit.record( - session, - school_class.id, - callback.from_user.id, - "subject.collect", - f"собрано предметов из расписания: {len(created)}", - ) - await session.commit() - - await state.clear() - text, keyboard = await _subject_view(session, school_class, role) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer( - f"Добавлено: {len(created)}" if created else "Все предметы расписания уже в списке" - ) - - -# -------------------------------------------------------------------------- -# 🏖 Special days -# -------------------------------------------------------------------------- -# -# A DayOverride is how the class says "this date is not a normal school day". -# «Обычный день» is the absence of a row, not a kind of row, so choosing it -# deletes the override instead of storing DayKind.NORMAL — otherwise the -# resolver would have two ways to spell the same thing. - -_KIND_BY_TAG = { - "holiday": DayKind.HOLIDAY, - "shortened": DayKind.SHORTENED, - "remote": DayKind.REMOTE, - "self_study": DayKind.SELF_STUDY, - "day_off": DayKind.DAY_OFF, -} - -#: The kind said in the middle of a sentence, for the audit line and the -#: confirmation. Read by **subscript**, not `.get`, and deliberately: a kind -#: with no entry here is a `KeyError` out of a callback handler, which never -#: reaches `callback.answer()` and leaves the button spinning until Telegram -#: gives up. `test_every_day_kind_can_be_said` keeps the table complete so the -#: subscript stays safe, rather than papering over a gap with a default that -#: would print «День» at somebody who chose «самоподготовка». -_KIND_SUMMARY = { - DayKind.HOLIDAY: "каникулы / выходной", - DayKind.SHORTENED: "сокращённые уроки", - DayKind.REMOTE: "дистанционно", - DayKind.SELF_STUDY: "самоподготовка", - DayKind.DAY_OFF: "отгул", -} - -HOLIDAY_DATE_HELP = ( - "Выберите день или пришлите дату: <code>12.09</code> или <code>12.09.2026</code>." -) - - -async def _holiday_view( - session: AsyncSession, - school_class: SchoolClass, - role: Role, - only: DayKind | None = None, -): - """The list of marked days, optionally narrowed to one kind. - - The filter lives in the callback payload rather than in FSM state, which is - the rule the editor's pager already follows: a card on a screen is a card - somebody may come back to in an hour, and a filter held in state would - either have expired by then or be silently applied to a different screen. - Carried in the payload, the card *is* its own filter. - """ - today = _today(school_class) - query = ( - select(DayOverride) - .where(DayOverride.class_id == school_class.id, DayOverride.date >= today) - .order_by(DayOverride.date) - ) - if only is not None: - query = query.where(DayOverride.kind == only) - overrides = list(await session.scalars(query)) - schedules = { - schedule.id: schedule.name - for schedule in await session.scalars( - select(BellSchedule).where(BellSchedule.class_id == school_class.id) - ) - } - return mr.render_holidays(overrides, schedules, today, only), holiday_list_keyboard( - overrides, - only=only, - can_edit=role.at_least(Role.EDITOR), - can_period=role.at_least(Role.ADMIN), - ) - - -async def _override_for( - session: AsyncSession, class_id: int, day: Date -) -> DayOverride | None: - return await session.scalar( - select(DayOverride).where(DayOverride.class_id == class_id, DayOverride.date == day) - ) - - -async def _upsert_override( - session: AsyncSession, school_class: SchoolClass, day: Date, kind: DayKind -) -> DayOverride: - override = await _override_for(session, school_class.id, day) - if override is None: - override = DayOverride(class_id=school_class.id, date=day, kind=kind) - session.add(override) - override.kind = kind - if kind is not DayKind.SHORTENED: - # A bell schedule only means anything on a shortened day; leaving a - # stale one on a holiday would surface in the day view as a - # schedule nobody chose. - override.bell_schedule_id = None - elif override.bell_schedule_id is None: - # Never null on a shortened day. The picker opens next and is where - # the real answer comes from, but the row is committed before it is - # asked — so walking away used to leave «⏱ Сокращённые уроки» over a - # day that names no schedule, which `api/edit.day_put` refuses with a - # 422 and the resolver silently draws as a normal day. The class - # default is the honest starting value: it is what the day would ring - # anyway, and now it says so on the card. - override.bell_schedule_id = school_class.bell_schedule_id - return override - - -@router.message(Command("holidays")) -async def cmd_holidays( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return - await state.clear() - text, keyboard = await _holiday_view(session, school_class, role) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(DayKindAction.filter(F.action == "list")) -async def holidays_list( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - await state.clear() - # An unreadable filter narrows to nothing rather than raising: the value is - # whatever the client sent, and `DayKind(raw)` out of a callback handler - # never reaches `callback.answer()`. - only = _day_kind_or_none(callback_data.value) if callback_data.value else None - text, keyboard = await _holiday_view(session, school_class, role, only) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -@router.callback_query(DayKindAction.filter(F.action == "add")) -async def holiday_add( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - await state.set_state(AddHoliday.date) - await callback.message.edit_text( - f"🏖 <b>Особый день</b>\n\n{HOLIDAY_DATE_HELP}", - reply_markup=open_month("dk", _today(school_class)), - ) - await callback.answer() - - -async def _ask_kind(editable, day: Date) -> None: - await editable.edit_text( - f"<b>{day:%d.%m.%Y}</b>\n\nЧто это за день?", - reply_markup=day_kind_keyboard(day.isoformat()), - ) - - -@router.callback_query(DayKindAction.filter(F.action == "pick_date")) -async def holiday_pick_date( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - day = _date_or_none(callback_data.value) - if day is None: - await callback.answer("Непонятная дата", show_alert=True) - return - - # From here the date travels in the callback payload, so the flow no longer - # depends on a state the user could have set for something else. - await state.clear() - await _ask_kind(callback.message, day) - await callback.answer() - - -@router.message(AddHoliday.date) -async def holiday_typed_date( - message: Message, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await state.clear() - return - - day = _parse_day(message.text or "", _today(school_class)) - if day is None: - await message.answer(f"Не понял дату. {HOLIDAY_DATE_HELP}") - return - - await state.clear() - await message.answer( - f"<b>{day:%d.%m.%Y}</b>\n\nЧто это за день?", - reply_markup=day_kind_keyboard(day.isoformat()), - ) - - -@router.callback_query(DayKindAction.filter(F.action == "kind")) -async def holiday_kind( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - raw_date, _, tag = callback_data.value.partition(":") - day = _date_or_none(raw_date) - if day is None: - await callback.answer("Непонятная дата", show_alert=True) - return - - if tag == "normal": - override = await _override_for(session, school_class.id, day) - if override is not None: - await session.delete(override) - await audit.record( - session, school_class.id, callback.from_user.id, "dayoverride.delete", - f"{day:%d.%m}: снова обычный день", - ) - await session.commit() - await state.clear() - text, keyboard = await _holiday_view(session, school_class, role) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer("Обычный день") - return - - kind = _KIND_BY_TAG.get(tag) - if kind is None: - await callback.answer("Неизвестный тип дня", show_alert=True) - return - - await _upsert_override(session, school_class, day, kind) - await audit.record( - session, school_class.id, callback.from_user.id, "dayoverride.set", - f"{day:%d.%m}: {_KIND_SUMMARY[kind]}", - ) - await session.commit() - - if kind is DayKind.SHORTENED: - schedules = list( - await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == school_class.id) - .order_by(BellSchedule.id) - ) - ) - await state.clear() - await callback.message.edit_text( - f"<b>{day:%d.%m}</b> — сокращённые уроки.\n\nПо какому расписанию звонков?", - reply_markup=bells_pick_keyboard(schedules, day.isoformat()), - ) - await callback.answer() - return - - await _ask_note(callback.message, state, day, kind) - await callback.answer() - - -async def _ask_note(editable, state: FSMContext, day: Date, kind: DayKind) -> None: - await state.set_state(AddHoliday.note) - await state.update_data(date=day.isoformat()) - await editable.edit_text( - f"✅ <b>{day:%d.%m}</b> — {_KIND_SUMMARY[kind]}.\n\n" - "Пришлите заметку (например, «осенние каникулы») или <code>-</code>, " - "чтобы оставить без неё.", - reply_markup=cancel_keyboard(), - ) - - -@router.callback_query(DayKindAction.filter(F.action == "bells")) -async def holiday_bells( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - raw_date, _, raw_id = callback_data.value.partition(":") - day = _date_or_none(raw_date) - if day is None: - await callback.answer("Непонятная дата", show_alert=True) - return - - override = await _override_for(session, school_class.id, day) - if override is None: - await callback.answer("День уже не отмечен", show_alert=True) - return - - schedule_id = _int_or_none(raw_id) - if schedule_id: - schedule = await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) - if schedule is None: - await callback.answer("Расписание звонков не найдено", show_alert=True) - return - # A schedule with no rows is legitimate — «🔔 Звонки» creates it empty - # and the times are typed in afterwards — but a day pointed at one - # draws no lessons at all, because the resolver takes a lesson's times - # from the bell row of its own number. The card would say «⏱ Сокращённые - # уроки» over an empty day on every phone, in the widget and in the - # calendar feed, and nothing would be logged. `api/edit.day_put` refuses - # the same thing for the same reason. - rings = await session.scalar( - select(BellPeriod.id).where(BellPeriod.schedule_id == schedule.id).limit(1) - ) - if rings is None: - await callback.answer( - f"В «{schedule.name}» ещё нет ни одного урока — " - "заполните звонки, иначе день будет пустым.", - show_alert=True, - ) - return - override.bell_schedule_id = schedule.id - summary = f"{day:%d.%m}: звонки «{schedule.name}»" - else: - # The keyboard no longer draws this button; a card left open from - # before it was removed still can. - await callback.answer( - "У сокращённого дня должно быть своё расписание звонков — " - "выберите его в списке.", - show_alert=True, - ) - return - - await audit.record( - session, school_class.id, callback.from_user.id, "dayoverride.bells", summary - ) - await session.commit() - await _ask_note(callback.message, state, day, DayKind.SHORTENED) - await callback.answer() - - -@router.message(AddHoliday.note) -async def holiday_note( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await state.clear() - return - - data = await state.get_data() - day = _date_or_none(str(data.get("date", ""))) - if day is None: - await state.clear() - await message.answer("Начните заново: /holidays", reply_markup=back_to_menu()) - return - - override = await _override_for(session, school_class.id, day) - if override is None: - await state.clear() - await message.answer("День уже не отмечен.", reply_markup=back_to_menu()) - return - - raw = " ".join((message.text or "").split()) - if raw not in {"-", "—", ""}: - override.note = raw[:NOTE_MAX] - await audit.record( - session, school_class.id, message.from_user.id, "dayoverride.note", - f"{day:%d.%m}: заметка «{override.note}»", - ) - await session.commit() - - await state.clear() - text, keyboard = await _holiday_view(session, school_class, role) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(DayKindAction.filter(F.action == "delete")) -async def holiday_delete( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - day = _date_or_none(callback_data.value) - if day is None: - await callback.answer("Непонятная дата", show_alert=True) - return - - override = await _override_for(session, school_class.id, day) - if override is not None: - await session.delete(override) - await audit.record( - session, school_class.id, callback.from_user.id, "dayoverride.delete", - f"{day:%d.%m}: отметка снята", - ) - await session.commit() - - await state.clear() - text, keyboard = await _holiday_view(session, school_class, role) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer("Снято" if override is not None else "Уже снято") - - -@router.callback_query(DayKindAction.filter(F.action == "period")) -async def holiday_period_start( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """A whole range of holiday days is admin-only: it rewrites weeks of the - class's calendar from one message.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - # Which kind first, dates second. The flow used to mark holidays and - # nothing else, so «самоподготовка с 12 по 16» meant marking five days one - # at a time — and a week of remote teaching, which is the shape this is - # actually needed in, meant five presses and five typos to make. - await state.clear() - await callback.message.edit_text( - "📆 <b>Отметить период</b>\n\n" - "Чем отметить каждый день внутри периода?", - reply_markup=period_kind_keyboard(), - ) - await callback.answer() - - -@router.callback_query(DayKindAction.filter(F.action == "period_kind")) -async def holiday_period_kind( - callback: CallbackQuery, - callback_data: DayKindAction, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """The kind is picked, now the dates. Re-checked here, not trusted from the - press that got this far: a card can sit on a screen after a role changes.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - kind = _day_kind_or_none(callback_data.value) - if kind is None or kind not in {chosen for chosen, _ in PERIOD_KINDS}: - # Not an exception. Callback data is whatever the client sent, and a - # bare conversion on it leaves the button spinning until Telegram - # gives up — see the guards in this module's siblings. - await callback.answer("Не знаю такого вида дня.", show_alert=True) - return - - label = next(text for chosen, text in PERIOD_KINDS if chosen is kind) - await state.set_state(AddHoliday.period) - await state.update_data(period_kind=kind.value) - await callback.message.edit_text( - f"📆 <b>{escape(label)}</b>\n\n" - "Пришлите период: <code>26.10-05.11</code>.\n" - f"Каждый день внутри будет отмечен так, не больше " - f"{PERIOD_MAX_DAYS} дней за раз.", - reply_markup=cancel_keyboard(), - ) - await callback.answer() - - -@router.message(AddHoliday.period) -async def holiday_period_apply( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - today = _today(school_class) - raw = (message.text or "").replace("—", "-").replace("–", "-") - parts = [part for part in raw.split("-") if part.strip()] - first = _parse_day(parts[0], today) if len(parts) >= 2 else None - last = _parse_day(parts[1], today) if len(parts) >= 2 else None - if first is None or last is None or last < first: - await message.answer( - "Не понял период. Формат: <code>26.10-05.11</code>, начало раньше конца." - ) - return - - span = (last - first).days + 1 - if span > PERIOD_MAX_DAYS: - await message.answer( - f"Это {span} дней — слишком много за один раз. " - f"Максимум {PERIOD_MAX_DAYS}; разбейте период на части." - ) - return - - # Read from the state the picker wrote, and defaulted rather than refused: - # a form that outlives a restart still has a date to apply, and holidays - # are what this flow did before there was anything to pick. - data = await state.get_data() - kind = _day_kind_or_none(str(data.get("period_kind", ""))) or DayKind.HOLIDAY - - for offset in range(span): - await _upsert_override(session, school_class, first + timedelta(days=offset), kind) - await audit.record( - session, - school_class.id, - message.from_user.id, - "dayoverride.period", - f"{kind.value}: {first:%d.%m}–{last:%d.%m}, дней: {span}", - ) - await session.commit() - await state.clear() - - await message.answer(mr.render_period_result(first, last, span, kind)) - text, keyboard = await _holiday_view(session, school_class, role) - await message.answer(text, reply_markup=keyboard) - - -# -------------------------------------------------------------------------- -# 🔔 Bells -# -------------------------------------------------------------------------- -# -# A class may keep several bell schedules — «Обычное», «Сокращённое», «Суббота» -# — and a shortened day points at one of them. One of them is the class -# default, and that one is what the day view uses when nothing else says -# otherwise. - -BELLS_ROWS_HELP = ( - "Пришлите строки расписания:\n\n" - "<code>1. 08:30-09:15\n" - "2. 09:25-10:10\n" - "3. 10:25-11:10</code>\n\n" - "Строка, которую я не разберу, не изменит сохранённое — " - "пустой присылкой звонки не стереть." -) - - -def _parse_bells(raw: str): - """Rows out of a paste, via the same grammar the week import uses. - - ``parse_bells_block`` only reads what is under a «== Звонки ==» header, - because a week paste must never touch the bells by accident. Here the - header is implied by the question that was asked, so it is prepended. - """ - return timetable_io.parse_bells_block("== Звонки ==\n" + (raw or "")) - - -async def _schedules_of(session: AsyncSession, class_id: int) -> list[BellSchedule]: - return list( - await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == class_id) - .order_by(BellSchedule.id) - ) - ) - - -async def _rung_by_default(session: AsyncSession, school_class: SchoolClass) -> set[int]: - """The lesson numbers the class rings today. Empty when it has no default.""" - if school_class.bell_schedule_id is None: - return set() - current = await session.scalar( - select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) - ) - return {period.index for period in current.periods} if current is not None else set() - - -async def _schedule_by_id( - session: AsyncSession, school_class: SchoolClass, raw: str -) -> BellSchedule | None: - schedule_id = _int_or_none(raw) - if schedule_id is None: - return None - return await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) - - -async def _bells_view(session: AsyncSession, school_class: SchoolClass): - schedules = await _schedules_of(session, school_class.id) - return mr.render_bells(schedules, school_class.bell_schedule_id), bells_list_keyboard( - schedules, school_class.bell_schedule_id - ) - - -@router.message(Command("bells")) -async def cmd_bells( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.clear() - text, keyboard = await _bells_view(session, school_class) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(BellsAction.filter(F.action == "list")) -async def bells_list( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.clear() - text, keyboard = await _bells_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -@router.callback_query(BellsAction.filter(F.action == "edit")) -async def bells_edit( - callback: CallbackQuery, - callback_data: BellsAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - schedule = await _schedule_by_id(session, school_class, callback_data.value) - if schedule is None: - await callback.answer("Расписание не найдено", show_alert=True) - return - - await state.set_state(EditBellRows.rows) - await state.update_data(schedule_id=schedule.id) - current = mr.render_bell_rows(schedule) - body = f"🔔 <b>{escape(schedule.name)}</b>\n\n" - if current: - body += f"<code>{escape(current)}</code>\n\n" - await callback.message.edit_text(body + BELLS_ROWS_HELP, reply_markup=cancel_keyboard()) - await callback.answer() - - -@router.message(EditBellRows.rows) -async def bells_rows_apply( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - data = await state.get_data() - schedule = await _schedule_by_id(session, school_class, str(data.get("schedule_id", ""))) - if schedule is None: - await state.clear() - await message.answer("Расписание уже удалено.", reply_markup=back_to_menu()) - return - - rows, rejected = _parse_bells(message.text or "") - if not rows: - # The stored schedule is the thing a class runs on; a paste that turned - # out to be prose must never be the reason it disappears. - await message.answer( - "Не удалось разобрать ни одной строки — звонки не изменены.\n\n" + BELLS_ROWS_HELP, - reply_markup=cancel_keyboard(), - ) - return - - orphaned = await structure.write_bell_periods(session, schedule, rows) - summary = f"звонки «{schedule.name}»: {len(rows)} уроков" - if orphaned: - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, - school_class.id, - message.from_user.id, - "bells.edit", - summary, - ) - await session.commit() - await session.refresh(schedule, ["periods"]) - await state.clear() - - lines = [f"✅ Звонки «{escape(schedule.name)}» сохранены: {len(rows)}."] - if orphaned: - # The lessons that were already there and no longer ring. They are not - # deleted — they are stored and drawn nowhere — so this sentence is the - # only place anybody is told, and it lives in `render` because the - # other bells editor has to say the very same thing. - lines.append("") - lines.append(render.silenced_lessons(orphaned)) - if rejected: - lines.append("") - lines.append("⚠️ Не разобрал строки:") - lines.extend(f"<code>{escape(line)}</code>" for line in rejected[:REJECTED_MAX]) - lines.extend(more_line(len(rejected), REJECTED_MAX)) - await message.answer(clamp(lines)) - - text, keyboard = await _bells_view(session, school_class) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(BellsAction.filter(F.action == "create")) -async def bells_create( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.set_state(NewBellSchedule.name) - await callback.message.edit_text( - "Название нового расписания звонков, например <code>Сокращённое</code>:", - reply_markup=cancel_keyboard(), - ) - await callback.answer() - - -@router.message(NewBellSchedule.name) -async def bells_new_name( - message: Message, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - name = " ".join((message.text or "").split()) - if not 1 <= len(name) <= 64: - await message.answer("Название от 1 до 64 символов. Ещё раз:") - return - - await state.update_data(name=name) - await state.set_state(NewBellSchedule.rows) - await message.answer( - f"<b>{escape(name)}</b>\n\n{BELLS_ROWS_HELP}", reply_markup=cancel_keyboard() - ) - - -@router.message(NewBellSchedule.rows) -async def bells_new_rows( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - data = await state.get_data() - name = str(data.get("name", "")).strip() - if not name: - await state.clear() - await message.answer("Начните заново: /bells", reply_markup=back_to_menu()) - return - - rows, rejected = _parse_bells(message.text or "") - if not rows: - await message.answer( - "Не удалось разобрать ни одной строки.\n\n" + BELLS_ROWS_HELP, - reply_markup=cancel_keyboard(), - ) - return - - schedule = BellSchedule(class_id=school_class.id, name=name[:64]) - session.add(schedule) - await session.flush() - await structure.write_bell_periods(session, schedule, rows) - await audit.record( - session, - school_class.id, - message.from_user.id, - "bells.create", - f"создано расписание звонков «{name}»: {len(rows)} уроков", - ) - await session.commit() - await session.refresh(schedule, ["periods"]) - await state.clear() - - lines = [f"✅ Расписание «{escape(name)}» создано: " - f"{plural(len(rows), 'урок', 'урока', 'уроков')}."] - if rejected: - # The same shape as `bells_rows_apply` above and `timetable_apply`: - # a row cap *and* a character budget. Five was the row cap alone, and - # a rejected line is echoed whole — one 4094-character paste whose - # first line is a real bell row and whose other five are prose came to - # 4152 characters, which Telegram refuses. The schedule had been - # created and committed by then, and this is a `Message` handler with - # no callback to apologise on, so the admin saw neither the - # confirmation nor the «🔔 Расписания звонков» list that follows it. - lines.append("") - lines.append("⚠️ Не разобрал строки:") - lines.extend(f"<code>{escape(line)}</code>" for line in rejected[:REJECTED_MAX]) - lines.extend(more_line(len(rejected), REJECTED_MAX)) - await message.answer(clamp(lines)) - - text, keyboard = await _bells_view(session, school_class) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(BellsAction.filter(F.action == "default")) -async def bells_make_default( - callback: CallbackQuery, - callback_data: BellsAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - schedule = await _schedule_by_id(session, school_class, callback_data.value) - if schedule is None: - await callback.answer("Расписание не найдено", show_alert=True) - return - - # A schedule may be created empty — that is the two-step flow, and the rows - # are the next screen. Making an empty one the *class default* is another - # thing: every ordinary day rings it, and a day that rings nothing draws - # nothing. `/bundle` answers zero lessons, `/now` answers «выходной» on a - # Monday, and the phone, the widget, the calendar feed and the morning - # digest go blank together with nothing anywhere reporting a problem — - # while the class's own timetable sits untouched underneath, which is what - # makes it so hard to see. Worse, `rung_indexes` then returns an empty set, - # which `can_ring` reads as «this class has not set its bells up yet» and - # waves every lesson number through. `api/manage.bells_update` has refused - # this since it was written and the «⭐» beside it did not; one rule, two - # shells, is the whole reason `services/` exists. - if not schedule.periods: - await callback.answer( - "В этом расписании звонков нет ни одного урока — сделать его " - "основным нельзя. Сначала добавьте времена.", - show_alert=True, - ) - return - - # Moving the default to a *shorter* schedule takes lessons off every - # weekday exactly as shrinking the current one does, and nothing rewrites a - # row, so `write_bell_periods` never runs and never counts them. Asked here - # through the same function the API asks, so the two answer alike. - was = await _rung_by_default(session, school_class) - orphaned = await structure.lessons_silenced_by( - session, school_class.id, was, {period.index for period in schedule.periods} - ) - school_class.bell_schedule_id = schedule.id - summary = f"основное расписание звонков: «{schedule.name}»" - if orphaned: - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, school_class.id, callback.from_user.id, "bells.default", summary, - ) - await session.commit() - - text, keyboard = await _bells_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - if orphaned: - # An alert rather than the log alone: the admin pressed a star and four - # lessons left every phone in the class, and the audit page is not - # where anybody looks next. - await callback.answer( - f"Основное расписание обновлено. Перестали звонить уроков: " - f"{len(orphaned)} — они остались в базе, но их никто не увидит.", - show_alert=True, - ) - return - await callback.answer("Основное расписание обновлено") - - -@router.callback_query(BellsAction.filter(F.action == "delete")) -async def bells_delete( - callback: CallbackQuery, - callback_data: BellsAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Refused for the class default and for anything a day still points at. - - Both are a ``SET NULL`` at the database level, which would silently move - those days onto the default schedule — a change nobody asked for, on dates - an admin is not looking at. - """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - schedule = await _schedule_by_id(session, school_class, callback_data.value) - if schedule is None: - await callback.answer("Расписание не найдено", show_alert=True) - return - - if schedule.id == school_class.bell_schedule_id: - await callback.answer( - "Это основное расписание класса. Сначала сделайте основным другое.", - show_alert=True, - ) - return - - used = await session.scalar( - select(func.count()) - .select_from(DayOverride) - .where( - DayOverride.class_id == school_class.id, - DayOverride.bell_schedule_id == schedule.id, - ) - ) - if used: - await callback.answer( - f"По нему идут особые дни ({used}). Сначала измените их.", show_alert=True - ) - return - - name = schedule.name - await session.delete(schedule) - await audit.record( - session, school_class.id, callback.from_user.id, "bells.delete", - f"удалено расписание звонков «{name}»", - ) - await session.commit() - - text, keyboard = await _bells_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer(f"Удалено: {name}"[:200]) - - -# -------------------------------------------------------------------------- -# 📱 Devices -# -------------------------------------------------------------------------- -# -# A device token is read-only until its owner links it to a Telegram account; -# from then on it writes with whatever role that account holds *right now* -# (``linking.effective_role``). Which is why this page shows the role as a -# lookup and not as something stored on the row: revoking somebody in «Доступ» -# has already revoked their phone by the time this page is drawn. - - -async def _device_view(session: AsyncSession, school_class: SchoolClass): - devices = await linking.devices_of(session, school_class.id) - owners: dict[int, tuple[str, Role | None]] = {} - names = await _member_names(session, school_class.id) - for device in devices: - if device.telegram_id is None or device.telegram_id in owners: - continue - owners[device.telegram_id] = ( - names.get(device.telegram_id, str(device.telegram_id)), - await linking.effective_role(session, device), - ) - return mr.render_devices(devices, owners), device_keyboard(devices) - - -async def _device_by_id( - session: AsyncSession, school_class: SchoolClass, raw: str -) -> DeviceToken | None: - device_id = _int_or_none(raw) - if device_id is None: - return None - return await session.scalar( - select(DeviceToken).where( - DeviceToken.id == device_id, DeviceToken.class_id == school_class.id - ) - ) - - -@router.message(Command("devices")) -async def cmd_devices( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.clear() - text, keyboard = await _device_view(session, school_class) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(DeviceAction.filter(F.action == "list")) -async def devices_list( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.clear() - text, keyboard = await _device_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -@router.callback_query(DeviceAction.filter(F.action == "revoke")) -async def device_revoke( - callback: CallbackQuery, - callback_data: DeviceAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Revoked, not deleted: the row is what the API checks a token against, - and keeping it is what makes the refusal instant and permanent.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - device = await _device_by_id(session, school_class, callback_data.value) - if device is None: - await callback.answer("Устройство не найдено", show_alert=True) - return - - device.revoked = True - name = device.device_name or f"Устройство {device.id}" - await audit.record( - session, school_class.id, callback.from_user.id, "device.revoke", - f"отключено устройство «{name}»", - ) - await session.commit() - - text, keyboard = await _device_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer(f"Отключено: {name}"[:200]) - - -@router.callback_query(DeviceAction.filter(F.action == "unlink")) -async def device_unlink( - callback: CallbackQuery, - callback_data: DeviceAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Back to read-only without taking the phone off the class.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - device = await _device_by_id(session, school_class, callback_data.value) - if device is None: - await callback.answer("Устройство не найдено", show_alert=True) - return - if device.telegram_id is None: - await callback.answer("Устройство и так не привязано", show_alert=True) - return - - name = device.device_name or f"Устройство {device.id}" - await linking.unlink_device(session, device) - await audit.record( - session, school_class.id, callback.from_user.id, "device.unlink", - f"отвязано устройство «{name}» — снова только чтение", - ) - await session.commit() - - text, keyboard = await _device_view(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer("Отвязано — теперь только чтение") - - -# -------------------------------------------------------------------------- -# 📜 The log -# -------------------------------------------------------------------------- - - -async def _audit_view(session: AsyncSession, school_class: SchoolClass, offset: int): - entries = await audit.recent(session, school_class.id, limit=mr.AUDIT_PAGE + 1, offset=offset) - more = len(entries) > mr.AUDIT_PAGE - entries = entries[:mr.AUDIT_PAGE] - names = await _member_names(session, school_class.id) - return ( - mr.render_audit(entries, names, school_class.tz, offset), - audit_keyboard(offset, more), - ) - - -@router.message(Command("log")) -async def cmd_log( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.clear() - text, keyboard = await _audit_view(session, school_class, 0) - await message.answer(text, reply_markup=keyboard) - - -@router.callback_query(AuditAction.filter(F.action == "page")) -async def audit_page( - callback: CallbackQuery, - callback_data: AuditAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - offset = _int_or_none(callback_data.value) or 0 - # A negative offset is not a page; SQL would take it as "no offset" and - # quietly show page one under a heading that says otherwise. - offset = max(0, offset) - - await state.clear() - text, keyboard = await _audit_view(session, school_class, offset) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -# -------------------------------------------------------------------------- -# ⚙️ The class -# -------------------------------------------------------------------------- - - -async def _class_card( - session: AsyncSession, school_class: SchoolClass, role: Role, telegram_id: int -): - memberships = await list_memberships(session, telegram_id) - members = int( - await session.scalar( - select(func.count()).select_from(BotUser).where(BotUser.class_id == school_class.id) - ) - or 0 - ) - devices = int( - await session.scalar( - select(func.count()) - .select_from(DeviceToken) - .where(DeviceToken.class_id == school_class.id, DeviceToken.revoked.is_(False)) - ) - or 0 - ) - pending = len(await _pending_requests(session, school_class.id)) - - text = mr.render_class_card( - school_class, - zone_label=label_for(school_class.timezone_name), - feed_ready=bool(school_class.calendar_token), - members=members, - devices=devices, - pending=pending, - diary_label=_diary_label(school_class), - ) - keyboard = class_menu( - is_owner=role.at_least(Role.OWNER), - # The button only appears for somebody who actually has somewhere to - # switch to; one membership is the overwhelmingly common case. - many_classes=len(memberships) > 1, - pending=pending, - diary_bound=bool(school_class.diary_provider), - ) - return text, keyboard - - -def _diary_label(school_class: SchoolClass) -> str: - """The diary line for the class card: the provider, and for «Сетевой город» - the region and school. Reads the binding, so a class bound to a region since - dropped from the allow-list reads «не привязан» rather than a dead name.""" - b = diary_binding(school_class) - if b is None: - return "не привязан" - if b.region: - from app.providers.netschool import regions - - region = regions.get(b.region) - parts = [b.provider.title] - if region is not None: - parts.append(region.title) - if b.school_name: - parts.append(b.school_name) - return " · ".join(parts) - return b.provider.title - - -@router.message(Command("class")) -async def cmd_class( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.clear() - text, keyboard = await _class_card(session, school_class, role, message.from_user.id) - await message.answer(text, reply_markup=keyboard) - - -# Two entry points, one card. The «⚙️ Класс» button in the main menu used to -# open a thinner version of this that lived in start.py, so half the settings -# were on whichever card you had not opened. -@router.callback_query(Menu.filter(F.action == "class")) -@router.callback_query(ManageAction.filter(F.action == "root")) -async def class_root( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.clear() - text, keyboard = await _class_card(session, school_class, role, callback.from_user.id) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -#: field tag -> (column, prompt, limit). Only these three are typed; the zone -#: and the join code have pickers of their own in ``start.py``. -_CLASS_FIELDS = { - "rename": ("name", "Новое название класса:", 64), - "school": ("school", "Название школы («-» — убрать):", 200), - "city": ("city", "Город («-» — убрать):", 120), -} - - -@router.callback_query(ManageAction.filter(F.action.in_({"rename", "school", "city"}))) -async def class_field_prompt( - callback: CallbackQuery, - callback_data: ManageAction, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - target = _CLASS_FIELDS.get(callback_data.action) - if target is None: # pragma: no cover - the filter already narrowed it - await callback.answer("Неизвестное поле", show_alert=True) - return - - _, prompt, _ = target - await state.set_state(EditClassField.value) - await state.update_data(field=callback_data.action) - await callback.message.edit_text(prompt, reply_markup=cancel_keyboard()) - await callback.answer() - - -@router.message(EditClassField.value) -async def class_field_apply( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - data = await state.get_data() - target = _CLASS_FIELDS.get(str(data.get("field", ""))) - if target is None: - await state.clear() - await message.answer("Начните заново: /class", reply_markup=back_to_menu()) - return - column, prompt, limit = target - - raw = " ".join((message.text or "").split()) - if column == "name": - # The name is what every other message calls this class, and what the - # delete confirmation is typed against; it cannot be empty. - if not 1 <= len(raw) <= limit: - await message.answer(f"От 1 до {limit} символов. {prompt}") - return - value = raw - else: - value = None if raw in {"-", "—", ""} else raw[:limit] - - setattr(school_class, column, value) - await audit.record( - session, - school_class.id, - message.from_user.id, - f"class.{column}", - f"{column}: {value or 'убрано'}", - ) - await session.commit() - await state.clear() - - text, keyboard = await _class_card(session, school_class, role, message.from_user.id) - await message.answer(text, reply_markup=keyboard) - - -# -------------------------------------------------------------------------- -# 🔀 Switching class -# -------------------------------------------------------------------------- - - -@router.callback_query(ManageAction.filter(F.action == "switch")) -async def class_switch( - callback: CallbackQuery, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await callback.answer(NO_ACCESS, show_alert=True) - return - - memberships = await list_memberships(session, callback.from_user.id) - classes: list[SchoolClass] = [] - for member in memberships: - found = await session.get(SchoolClass, member.class_id) - if found is not None: - classes.append(found) - if len(classes) < 2: - await callback.answer("Вы состоите только в одном классе", show_alert=True) - return - - await callback.message.edit_text( - "🔀 <b>Сменить класс</b>\n\nВ каком классе работаем дальше?", - reply_markup=switch_keyboard(classes), - ) - await callback.answer() - - -@router.callback_query(ManageAction.filter(F.action == "switch_to")) -async def class_switch_to( - callback: CallbackQuery, - callback_data: ManageAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Remember which class this person is working in. - - The preference is written to FSM storage — the database — under its own - key, and the middleware reads exactly that key on the next update. Nothing - is kept in the process: on Vercel the next message is a different one. - - The membership is checked here and checked again by the middleware every - time it reads the preference, so a class somebody is later removed from - stops being their default by itself. - """ - if school_class is None or role is None: - await callback.answer(NO_ACCESS, show_alert=True) - return - - class_id = _int_or_none(callback_data.value) - memberships = await list_memberships(session, callback.from_user.id) - if class_id is None or not any(member.class_id == class_id for member in memberships): - await callback.answer("Вы не состоите в этом классе", show_alert=True) - return - - target = await session.get(SchoolClass, class_id) - if target is None: - await callback.answer("Класс не найден", show_alert=True) - return - - storage = DatabaseStorage(SessionLocal) - await storage.set_data(prefs_key(callback.from_user.id), {"class_id": class_id}) - - await state.clear() - await callback.message.edit_text( - f"✅ Текущий класс: <b>{escape(target.name)}</b>.\n\n" - "Все команды теперь про него. Открыть меню: /start", - reply_markup=back_to_menu(), - ) - await callback.answer(f"Класс: {target.name}"[:200]) - - -# -------------------------------------------------------------------------- -# 🗑 Deleting a class -# -------------------------------------------------------------------------- - - -@router.callback_query(ManageAction.filter(F.action == "delete")) -async def class_delete_prompt( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.OWNER): - await callback.answer(NEED_OWNER, show_alert=True) - return - - await state.set_state(DeleteClass.confirm) - await callback.message.edit_text( - f"🗑 <b>Удалить класс {escape(school_class.name)}?</b>\n\n" - "Вместе с ним исчезнут расписание, домашние задания, замены, события, " - "журнал и все привязанные устройства. Это нельзя отменить.\n\n" - f"Чтобы подтвердить, пришлите название класса точно так: " - f"<code>{escape(school_class.name)}</code>", - reply_markup=cancel_keyboard(), - ) - await callback.answer() - - -@router.message(DeleteClass.confirm) -async def class_delete_apply( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Typing the name back is the confirmation, and the only one. - - A «вы уверены?» button is pressed by the same thumb that pressed the one - before it. Nothing here writes an audit line: the log lives in the class - and goes with it. - """ - if not _allowed(school_class, role, Role.OWNER): - await state.clear() - return - - typed = (message.text or "").strip() - if typed != school_class.name: - await message.answer( - "Название не совпало — класс не тронут.\n" - f"Чтобы удалить, пришлите ровно: <code>{escape(school_class.name)}</code>" - ) - return - - name = school_class.name - await session.delete(school_class) - await session.commit() - await state.clear() - await message.answer( - f"🗑 Класс <b>{escape(name)}</b> удалён вместе со всеми данными." - ) - - -# -------------------------------------------------------------------------- -# 📅 Calendar -# -------------------------------------------------------------------------- - - -async def _calendar_text(session: AsyncSession, school_class: SchoolClass, rotated: bool) -> str: - base = get_settings().public_base_url.rstrip("/") - if not base: - return mr.render_calendar(None) - if rotated: - token = await calendar_service.rotate_calendar_token(session, school_class) - else: - token = await calendar_service.ensure_calendar_token(session, school_class) - return mr.render_calendar(f"{base}/api/v1/calendar/{token}.ics", rotated=rotated) - - -def _calendar_keyboard(role: Role): - rows: list[list[InlineKeyboardButton]] = [] - if role.at_least(Role.ADMIN): - rows.append( - [ - InlineKeyboardButton( - text="🔁 Новая ссылка", - callback_data=ManageAction(action="rotate_feed").pack(), - ) - ] - ) - rows.append(back_to("root")) - return back_to_menu(rows) - - -@router.message(Command("calendar")) -async def cmd_calendar( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Any member may subscribe: the feed is read-only and its secret is not - the join code, so a calendar URL cannot be turned into write access.""" - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - await state.clear() - await message.answer( - await _calendar_text(session, school_class, rotated=False), - reply_markup=_calendar_keyboard(role), - ) - - -@router.callback_query(ManageAction.filter(F.action == "diary_bind")) -async def class_diary_bind( - callback: CallbackQuery, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Bind or unbind the class's electronic diary. - - Binding gives the class nothing and takes nothing: it puts «📒 Мой дневник» - on every member's menu, and what is behind that button is each member's own - account. Unbinding likewise only removes the door — the sessions people - opened stay theirs until they sign out, and are dropped with the class. - """ - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return - - if school_class.diary_provider: - # Bound → unbind. The door goes; the sessions people opened stay theirs - # until they sign out or the class is deleted, as three screens promise. - # Nothing is expired here, deliberately: with no binding the bot reads - # none of them anyway, and a later bind expires exactly those it does - # not read (`diary_service.expire_off_binding`) — which, unlike this, - # knows which diary the class went to. - school_class.diary_provider = None - school_class.diary_region = None - school_class.diary_school_id = None - school_class.diary_school_name = None - # An outstanding sign-in link would still open a form; the submit - # refuses an unbound class, but only a dropped ticket survives a - # rebind that follows at once (#137). - await diary_link.drop_for_class(session, school_class.id) - await audit.record( - session, school_class.id, callback.from_user.id, "class.diary", "дневник отвязан" - ) - await session.commit() - await _redraw_class(callback, session, school_class, role) - await callback.answer("Дневник отвязан") - return - - # Unbound → choose which diary. There is more than one now, so binding is a - # small chooser rather than a single toggle. - await callback.message.edit_text( - "📒 <b>Электронный дневник</b>\n\nВыберите, к какому дневнику привязать класс.", - reply_markup=diary_provider_menu(), - ) - await callback.answer() - - -@router.callback_query(ManageAction.filter(F.action == "diary_prov")) -async def class_diary_provider( - callback: CallbackQuery, - callback_data: ManageAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Second step of binding: the provider was picked.""" - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return - if callback_data.value == PETERSBURG: - school_class.diary_provider = PETERSBURG - school_class.diary_region = None - school_class.diary_school_id = None - school_class.diary_school_name = None - # The members' «Сетевой город» sessions read a diary the class has - # left; expired in the same commit as the binding they no longer fit. - # And the sign-in links minted under the old binding go with it, or a - # form drawn for one diary sends its password to the other (#137). - await diary_service.expire_off_binding(session, school_class) - await diary_link.drop_for_class(session, school_class.id) - await audit.record( - session, school_class.id, callback.from_user.id, "class.diary", - "привязан дневник Санкт-Петербурга", - ) - await session.commit() - await _redraw_class(callback, session, school_class, role) - await callback.answer("Привязан дневник Санкт-Петербурга") - return - if callback_data.value == NETSCHOOL: - await callback.message.edit_text( - "🌆 <b>Сетевой город</b>\n\nВыберите регион.", reply_markup=diary_region_menu() - ) - await callback.answer() - return - await callback.answer("Неизвестный дневник", show_alert=True) - - -@router.callback_query(ManageAction.filter(F.action == "diary_reg")) -async def class_diary_region( - callback: CallbackQuery, - callback_data: ManageAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, - state: FSMContext, -) -> None: - """Third step: the «Сетевой город» region was picked. Check the region - accepts a password from us before asking for the school, so the admin - learns once rather than every family finding out at sign-in.""" - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return - region = ns_regions.get(callback_data.value) - if region is None or not region.password: - await callback.answer("Этот регион недоступен", show_alert=True) - return - ok, why = await _probe_region(region) - if not ok: - await callback.answer(why, show_alert=True) - return - await state.set_state(BindDiary.school) - await state.update_data(diary_region=region.key, diary_class_id=school_class.id) - await callback.message.edit_text( - f"🌆 <b>Сетевой город</b> · {escape(region.title)}\n\n" - "Напишите часть названия школы — я поищу её на сайте региона.", - ) - await callback.answer() - - -async def _probe_region(region) -> tuple[bool, str]: # noqa: ANN001 - """Ask the region's sign-in options, so a class is not bound to a diary no - family can reach. @return (ok, message-if-not).""" - try: - await NetSchoolClient(region).login_allowed() - except SignInUnsupported: - return False, "Этот регион пускает только через Госуслуги — привязать нельзя." - except AddressRefused: - return False, "Сайт региона не отвечает нашему серверу. Сообщите владельцу проекта." - except DiaryError: - return False, "Сайт региона сейчас недоступен. Попробуйте позже." - return True, "" - - -@router.message(BindDiary.school) -async def class_diary_search( - message: Message, - session: AsyncSession, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Fourth step: a school-name query. Show what the region's search found. - - FSM state is per-user and attacker-controlled, so the role is re-checked - here as at every step — a non-admin who set itself into this state would - otherwise turn the class card into an outbound search against a region - server. - """ - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - data = await state.get_data() - region = ns_regions.get(data.get("diary_region")) - class_id = data.get("diary_class_id") - if region is None or class_id is None: - await state.clear() - return - query = (message.text or "").strip() - if len(query) < 2: - await message.answer("Введите хотя бы два символа названия школы.") - return - try: - schools = await NetSchoolClient(region).schools_search(query) - except DiaryError: - await message.answer("Не удалось найти школы — сайт региона не ответил. Попробуйте позже.") - return - if not schools: - await message.answer("Школа не найдена. Уточните запрос.") - return - shown = schools[:DIARY_SCHOOLS_MAX] - await state.update_data(diary_schools=shown) - caption = f"🌆 <b>Сетевой город</b> · {escape(region.title)}\n\nВыберите школу:" - more = len(schools) > len(shown) - if more: - caption += f"\n\nПоказаны первые {len(shown)} — уточните запрос, если нужной нет." - await message.answer(caption, reply_markup=diary_school_menu(shown, more=more)) - - -@router.callback_query(DiarySchoolPick.filter(F.action == "cancel")) -async def class_diary_cancel( - callback: CallbackQuery, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, - state: FSMContext, -) -> None: - # A role check like every other step: the callback payload is whatever the - # client sent, and this one redraws the (admin-only) class card, so a - # наблюдатель who pressed it would otherwise be shown it. - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await state.clear() - await callback.answer("Только для администраторов", show_alert=True) - return - await state.clear() - await _redraw_class(callback, session, school_class, role) - await callback.answer("Отменено") - - -@router.callback_query(DiarySchoolPick.filter(F.action == "pick")) -async def class_diary_school( - callback: CallbackQuery, - callback_data: DiarySchoolPick, - session: AsyncSession, - role: Role | None, - state: FSMContext, -) -> None: - """Last step: a school was picked. Bind the class to it.""" - data = await state.get_data() - schools = data.get("diary_schools") or [] - region = ns_regions.get(data.get("diary_region")) - class_id = data.get("diary_class_id") - index = callback_data.value - if region is None or class_id is None or not (0 <= index < len(schools)): - await state.clear() - await callback.answer("Список устарел — начните заново.", show_alert=True) - return - school_class = await session.get(SchoolClass, class_id) - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await state.clear() - await callback.answer("Только для администраторов", show_alert=True) - return - school = schools[index] - school_class.diary_provider = NETSCHOOL - school_class.diary_region = region.key - school_class.diary_school_id = int(school["id"]) - school_class.diary_school_name = str(school["name"])[:300] - # Sessions on another region's server, or Petersburg's, read a diary the - # class has left: expired with the binding, so the keep-alive stops - # pinging a server nobody here uses. The same region keeps them. The - # sign-in links go whatever the region: each names one school (#137). - await diary_service.expire_off_binding(session, school_class) - await diary_link.drop_for_class(session, school_class.id) - await audit.record( - session, school_class.id, callback.from_user.id, "class.diary", - f"привязан «Сетевой город»: {region.title}, {str(school['name'])[:200]}", - ) - await session.commit() - await state.clear() - await _redraw_class(callback, session, school_class, role) - await callback.answer("Дневник привязан") - - -async def _redraw_class( - callback: CallbackQuery, session: AsyncSession, school_class: SchoolClass, role: Role -) -> None: - text, keyboard = await _class_card(session, school_class, role, callback.from_user.id) - await callback.message.edit_text(text, reply_markup=keyboard) - - -@router.callback_query(ManageAction.filter(F.action == "calendar")) -async def calendar_card( - callback: CallbackQuery, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await callback.answer(NO_ACCESS, show_alert=True) - return - await callback.message.edit_text( - await _calendar_text(session, school_class, rotated=False), - reply_markup=_calendar_keyboard(role), - ) - await callback.answer() - - -@router.callback_query(ManageAction.filter(F.action == "rotate_feed")) -async def calendar_rotate( - callback: CallbackQuery, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Every existing subscription stops updating — that is the point.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - text = await _calendar_text(session, school_class, rotated=True) - await audit.record( - session, school_class.id, callback.from_user.id, "calendar.rotate", - "выдана новая ссылка на календарь, старая отключена", - ) - await session.commit() - await callback.message.edit_text(text, reply_markup=_calendar_keyboard(role)) - await callback.answer("Ссылка обновлена") - - -# -------------------------------------------------------------------------- -# 📤 Export and 📥 import of the timetable -# -------------------------------------------------------------------------- - - -# There is deliberately no `_export_parts` here any more. -# -# It re-split the export on the *escaped* length, on the reasoning that «every -# «&» costs four more characters and every «<» or «>» three». That reasoning is -# wrong, and the Bot API says so in one line: `sendMessage`'s `text` is -# «1-4096 characters **after entities parsing**». Telegram counts what it -# parses — `<code>` costs nothing and `&` counts as the one «&» it becomes -# — so an export could not overflow by being escaped, and the thing this -# defended against could not happen. -# -# What it did instead was real. Shrinking the limit by the expansion factor -# turned 200 lines of apostrophes from 6 messages into 34, and 34 consecutive -# `answer` calls into one chat is the per-chat flood limit: `TelegramRetryAfter` -# raised out of a `Message` handler, which has no callback to apologise on, so -# the export stopped partway with nothing said — the exact failure it was -# written to remove, moved to a different trigger. -# -# `split_text` at `CHUNK_LIMIT` is what the export uses, as it did before. - - -@router.message(Command("export")) -async def cmd_export( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """The whole template as text — which doubles as the backup. - - It is sent in ``<code>`` blocks so Telegram offers a copy button, split at - 4000 characters because the limit is 4096 and the header counts. - """ - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.clear() - - entries = list( - await session.scalars( - select(TimetableEntry) - .where(TimetableEntry.class_id == school_class.id) - .order_by(TimetableEntry.weekday, TimetableEntry.index) - ) - ) - periods: list[BellPeriod] = [] - if school_class.bell_schedule_id: - schedule = await session.get(BellSchedule, school_class.bell_schedule_id) - if schedule is not None: - periods = list(schedule.periods) - - body = timetable_io.export_timetable(entries, periods) - if not body: - await message.answer("Расписание пустое — экспортировать нечего.") - return - - parts = mr.split_text(body) - for number, part in enumerate(parts, start=1): - header = f"📤 Экспорт, часть {number}/{len(parts)}\n" if len(parts) > 1 else "" - await message.answer(f"{header}<code>{escape(part)}</code>") - - -IMPORT_HELP = ( - "Пришлите расписание одним сообщением, с заголовком перед каждым днём:\n\n" - "<code>== Понедельник ==\n" - "1. Алгебра, 214\n" - "2. Физика, 305, Иванова И.И.\n" - "3. История [чис]\n" - "3. Обществознание [знам]\n\n" - "== Вторник ==\n" - "1. Химия, 118</code>\n\n" - "Подойдёт и текст из /export — можно раз в четверть сохранять его себе " - "и возвращать обратно.\n" - "Блок <code>== Звонки ==</code> обновит основное расписание звонков." -) - - -@router.message(Command("import")) -async def cmd_import( - message: Message, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return - await state.set_state(ImportTimetable.paste) - await message.answer(f"📥 <b>Импорт расписания</b>\n\n{IMPORT_HELP}") - - -@router.message(ImportTimetable.paste) -async def import_preview( - message: Message, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Parse and show what would happen; nothing is written yet. - - The paste is kept in FSM storage rather than parsed twice into a process - variable: «Применить» may well arrive at a different instance. - """ - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - raw = message.text or "" - days, rejected = timetable_io.parse_timetable_block(raw) - bells, _ = timetable_io.parse_bells_block(raw) - if not days and not bells: - await message.answer( - "Не нашёл ни одного дня.\n\n" + IMPORT_HELP, reply_markup=cancel_keyboard() - ) - return - - await state.update_data(raw=raw) - preview = mr.render_import_preview(days, rejected, len(bells)) - await message.answer(preview, reply_markup=import_keyboard()) - - -@router.callback_query(ImportAction.filter(F.action == "cancel")) -async def import_cancel( - callback: CallbackQuery, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.clear() - await callback.message.edit_text("Импорт отменён — ничего не изменилось.") - await callback.answer() - - -@router.callback_query(ImportAction.filter(F.action == "apply")) -async def import_apply( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Replace exactly the weekdays the paste named, in one transaction. - - Days the paste did not mention are left alone, so importing a single day's - block is a legitimate thing to do. A day that appears with no lessons under - it is emptied — that is how a paste says «в четверг уроков нет». - """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - data = await state.get_data() - raw = str(data.get("raw", "")) - days, _ = timetable_io.parse_timetable_block(raw) - bells, _ = timetable_io.parse_bells_block(raw) - if not days and not bells: - await state.clear() - await callback.answer("Нечего применять — начните заново: /import", show_alert=True) - return - - result = await structure.apply_timetable(session, school_class, days, bells) - total = result.written - schedule = result.schedule - unrung = result.unrung - - summary = f"импорт расписания: дней {len(days)}, уроков {total}" - if bells: - summary += f", звонков {len(bells)}" - if result.dropped: - # Rows, not numbers. «8. Алгебра» under Monday and under Tuesday is two - # lessons nobody will see, and this line is the only record of them. - summary += f", без звонка пропущено {len(result.dropped)}" - await audit.record( - session, school_class.id, callback.from_user.id, "timetable.import", summary - ) - await session.commit() - if schedule is not None: - await session.refresh(schedule, ["periods"]) - await state.clear() - - lines = [f"✅ Импорт применён: {len(days)} дн., уроков — {total}."] - # What was written, not what was parsed. A lesson past the last bell is - # dropped by ``apply_timetable``, so printing the parsed count put «уроков - # — 7» directly above «Вторник: 9» — the card contradicting itself on two - # consecutive lines. The service says which rows it dropped, by weekday, so - # this counts them rather than re-deciding the rule a second time here. - dropped_per_day: dict[int, int] = {} - for weekday, _index in result.dropped: - dropped_per_day[weekday] = dropped_per_day.get(weekday, 0) + 1 - for weekday in sorted(days): - written = len(days[weekday]) - dropped_per_day.get(weekday, 0) - lines.append(f"• {WEEKDAY_FULL[weekday - 1]}: {written}") - if bells: - lines.append(f"• Звонки: {len(bells)}") - if unrung: - # Said out loud rather than left in the difference between two numbers: - # such a lesson is stored nowhere and drawn nowhere, and an admin who - # is not told simply believes the paste worked. - numbers = ", ".join(str(index) for index in unrung) - lines.append( - f"\n⚠️ Не добавлены уроки № {numbers}: в расписании звонков нет " - "таких номеров. Добавьте звонки в «🔔 Звонки» и вставьте день заново." - ) - await callback.message.edit_text("\n".join(lines), reply_markup=back_to_menu()) - await callback.answer("Готово") - - -# -------------------------------------------------------------------------- -# 📊 Statistics and 🔎 search -# -------------------------------------------------------------------------- - - -@router.message(Command("stats")) -async def cmd_stats( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return - await state.clear() - numbers = await stats_service.class_stats(session, school_class) - await message.answer( - stats_service.render_stats(numbers, school_class), reply_markup=back_to_menu() - ) - - -@router.message(Command("find")) -async def cmd_find( - message: Message, - command: CommandObject, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Search this class's homework. Any member may: it is the same text the - day view already shows them, only reachable by memory instead of by date.""" - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - - needle = (command.args or "").strip() - if len(needle) < 2: - await message.answer( - "🔎 <b>Поиск по домашним заданиям</b>\n\n" - "Напишите, что искать: <code>/find параграф 12</code>.\n" - "Ищу по тексту задания и по названию предмета, " - "минимум два символа." - ) - return - - today = _today(school_class) - # ``lower().contains()`` rather than ILIKE, which SQLite does not have. - # Both dialects fold Cyrillic: Postgres does it natively, and ``app.db`` - # replaces SQLite's ASCII-only ``lower()`` with Python's on every - # connection, so the search behaves the same for the developer and for the - # class. - pattern = needle.lower() - rows = list( - await session.scalars( - select(Homework) - .where( - Homework.class_id == school_class.id, - Homework.due_date >= today - timedelta(days=SEARCH_BACK_DAYS), - func.lower(Homework.text).contains(pattern) - | func.lower(Homework.subject_name).contains(pattern), - ) - .order_by(Homework.due_date.desc(), Homework.id.desc()) - .limit(SEARCH_MAX) - ) - ) - await message.answer(mr.render_search(needle, rows, today), reply_markup=back_to_menu()) - - -# -------------------------------------------------------------------------- -# 📱 /link and 🙋 /request -# -------------------------------------------------------------------------- - - -@router.message(Command("link")) -async def cmd_link( - message: Message, - command: CommandObject, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Attach the phone showing ``code`` to this account. - - No role check beyond membership: linking gives the phone *this* account's - role, whatever it is, so it can never be more than the person already has. - """ - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - - code = (command.args or "").strip() - if not 1 <= len(code) <= 16: - await message.answer( - "📱 <b>Привязка телефона</b>\n\n" - "Откройте в приложении экран привязки и пришлите код: " - "<code>/link ABC123</code>." - ) - return - - device = await linking.link_device(session, code, message.from_user.id) - if device is None: - await message.answer( - "Код не подошёл. Он действует один раз — откройте экран привязки " - "в приложении ещё раз и пришлите новый." - ) - return - - device_role = await linking.effective_role(session, device) - name = escape(device.device_name or "Телефон") - if device_role is not None and device_role.at_least(Role.EDITOR): - tail = f"Ваша роль: <b>{device_role.title_ru}</b> — приложение может редактировать." - else: - title = device_role.title_ru if device_role is not None else "нет роли" - tail = ( - f"Ваша роль: <b>{title}</b> — только чтение. " - "Запросить доступ редактора: /request" - ) - await audit.record( - session, - device.class_id, - message.from_user.id, - "device.link", - f"привязано устройство «{device.device_name or device.id}»", - ) - await session.commit() - await message.answer(f"📱 Устройство «{name}» привязано. {tail}") - - -async def _create_request( - session: AsyncSession, school_class: SchoolClass, telegram_id: int, text: str | None -) -> AccessRequest: - """One open request per person per class — a second one replaces the first, - so a nervous requester cannot fill an admin's screen.""" - existing = await session.scalar( - select(AccessRequest).where( - AccessRequest.class_id == school_class.id, - AccessRequest.telegram_id == telegram_id, - AccessRequest.status == "pending", - ) - ) - if existing is None: - existing = AccessRequest( - class_id=school_class.id, - telegram_id=telegram_id, - requested_role=Role.EDITOR, - status="pending", - ) - session.add(existing) - existing.requested_role = Role.EDITOR - existing.status = "pending" - existing.message = (text or None) and text[:300] - existing.decided_by = None - existing.decided_at = None - await session.flush() - return existing - - -async def _notify_admins( - session: AsyncSession, - bot, - school_class: SchoolClass, - request: AccessRequest, - who: str, -) -> None: - """Tell every admin, and let one bad recipient be nobody else's problem.""" - if bot is None: - return - - admins = await session.scalars( - select(BotUser).where( - BotUser.class_id == school_class.id, - BotUser.role.in_([Role.ADMIN, Role.OWNER]), - ) - ) - body = ( - f"🙋 <b>Запрос доступа</b>\n\n" - f"{who} просит роль <b>{Role.EDITOR.title_ru}</b> " - f"в классе <b>{escape(school_class.name)}</b>." - ) - if request.message: - body += f"\n\n<i>{escape(request.message)}</i>" - - for admin in admins: - try: - await bot.send_message( - admin.telegram_id, body, reply_markup=request_keyboard(request.id) - ) - except Exception: # noqa: BLE001 - one blocked admin is not the requester's problem - log.warning("could not notify admin %s", admin.telegram_id, exc_info=True) - - -@router.message(Command("request")) -async def cmd_request( - message: Message, - command: CommandObject, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - if role.at_least(Role.EDITOR): - await message.answer( - f"У вас уже роль <b>{role.title_ru}</b> — запрашивать нечего." - ) - return - - text = (command.args or "").strip() - if not text: - await state.set_state(RequestAccess.message) - await message.answer( - "🙋 <b>Запрос доступа редактора</b>\n\n" - "Напишите пару слов о себе — администратор увидит их вместе с запросом. " - "Или пришлите <code>-</code>, чтобы отправить без комментария.", - reply_markup=cancel_keyboard(), - ) - return - - await _submit_request(message, state, session, school_class, text) - - -@router.message(RequestAccess.message) -async def request_message( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.VIEWER) or role.at_least(Role.EDITOR): - await state.clear() - return - raw = " ".join((message.text or "").split()) - await _submit_request( - message, state, session, school_class, None if raw in {"-", "—", ""} else raw - ) - - -async def _submit_request( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass, - text: str | None, -) -> None: - request = await _create_request(session, school_class, message.from_user.id, text) - who = mr.person(message.from_user.full_name, message.from_user.username, message.from_user.id) - await audit.record( - session, - school_class.id, - message.from_user.id, - "access.request", - f"{message.from_user.full_name or message.from_user.id} просит роль редактора", - ) - await session.commit() - await state.clear() - - await _notify_admins(session, _bot_of(message), school_class, request, who) - await message.answer( - "✅ Запрос отправлен администраторам класса. Они ответят здесь же." - ) - - -async def _tell_requester(bot, telegram_id: int, text: str) -> None: - if bot is None: - return - try: - await bot.send_message(telegram_id, text) - except Exception: # noqa: BLE001 - the decision stands whether or not it was delivered - log.warning("could not tell %s about the decision", telegram_id, exc_info=True) - - -async def _request_by_id( - session: AsyncSession, school_class: SchoolClass, raw: str -) -> AccessRequest | None: - request_id = _int_or_none(raw) - if request_id is None: - return None - return await session.scalar( - select(AccessRequest).where( - AccessRequest.id == request_id, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ) - ) - - -@router.callback_query(RequestAction.filter(F.action == "approve")) -async def request_approve( - callback: CallbackQuery, - callback_data: RequestAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - """Grant the requested role through the same rules as «👥 Доступ». - - Literally the same rules: `services/access.approve_request` is also what - `PATCH /api/v1/manage/requests/{id}/approve` calls, so a phone and this - button cannot come to different answers. The refusal it raises carries the - Russian sentence this alert shows. - """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - request = await _request_by_id(session, school_class, callback_data.value) - if request is None: - await callback.answer("Запрос уже закрыт", show_alert=True) - return - - target_role = request.requested_role - try: - member = await access_service.approve_request( - session, - school_class, - request, - actor_id=callback.from_user.id, - actor_role=role, - role=target_role, - ) - except access_service.GrantRefused as refused: - await callback.answer(str(refused), show_alert=True) - return - - name = mr.person(member.full_name, member.username, member.telegram_id) - await session.commit() - - await _tell_requester( - _bot_of(callback), - request.telegram_id, - access_service.approval_notice(school_class, target_role), - ) - await callback.message.edit_text( - f"✅ {name} — теперь <b>{target_role.title_ru}</b>.", reply_markup=back_to_menu() - ) - await callback.answer("Выдано") - - -@router.callback_query(RequestAction.filter(F.action == "decline")) -async def request_decline( - callback: CallbackQuery, - callback_data: RequestAction, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - request = await _request_by_id(session, school_class, callback_data.value) - if request is None: - await callback.answer("Запрос уже закрыт", show_alert=True) - return - - request.status = "declined" - request.decided_by = callback.from_user.id - request.decided_at = datetime.now(UTC).replace(tzinfo=None) - await audit.record( - session, - school_class.id, - callback.from_user.id, - "access.decline", - f"отклонён запрос доступа от {request.telegram_id}", - ) - await session.commit() - - await _tell_requester( - _bot_of(callback), - request.telegram_id, - f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", - ) - await callback.message.edit_text("✖️ Запрос отклонён.", reply_markup=back_to_menu()) - await callback.answer("Отклонено") - - -# -------------------------------------------------------------------------- -# 🗓 Quarters and half-years -# -# The dates are a school's own: the holidays move, a region shifts its spring -# break, a quarantine eats a week. So this is an editor rather than a display, -# and the rules it edits against live in ``app/services/terms.py`` — the same -# ones `/api/v1/manage` uses, because two implementations of "does this term -# overlap" disagree within a month. -# -------------------------------------------------------------------------- - - -def _term_year(school_class: SchoolClass) -> int: - """The school year in force *for this class*, in the class's own zone. - - Not the server's: a class in Kamchatka turns the page on 1 September nine - hours before a class in Kaliningrad, and the server is in neither. - """ - return terms_service.opening_year_of(datetime.now(school_class.tz).date()) - - -async def _terms_card(session: AsyncSession, school_class: SchoolClass): - year = _term_year(school_class) - rows = await terms_service.ensure(session, school_class, year) - await session.commit() - - scheme = terms_service.scheme_of(school_class) - is_semester = scheme is TermKind.SEMESTER - heading = "полугодия" if is_semester else "четверти" - today = datetime.now(school_class.tz).date() - current = terms_service.term_at(rows, today) - - lines = [ - f"🗓 <b>{escape(school_class.name)}</b> — {heading} {year}/{year + 1}", - "", - ] - for term in rows: - mark = " ←" if current is not None and term.index == current.index else "" - lines.append( - f"<b>{term.index}.</b> {term.starts_on:%d.%m.%Y} — " - f"{term.ends_on:%d.%m.%Y} · {term.days} дн.{mark}" - ) - if current is None: - lines.append("") - lines.append("Сейчас каникулы.") - lines.append("") - lines.append("Нажмите период, чтобы изменить его даты.") - - return "\n".join(lines), terms_menu(rows, is_semester=is_semester) - - -@router.callback_query(TermAction.filter(F.action == "list")) -async def terms_list( - callback: CallbackQuery, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - await state.clear() - text, keyboard = await _terms_card(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer() - - -@router.callback_query(TermAction.filter(F.action == "scheme")) -async def terms_scheme( - callback: CallbackQuery, - callback_data: TermAction, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - wanted = TermKind.SEMESTER if callback_data.value == "semester" else TermKind.QUARTER - year = _term_year(school_class) - await terms_service.set_scheme(session, school_class, wanted, year) - await audit.record( - session, - school_class.id, - callback.from_user.id, - "class.term_kind", - f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", - ) - await session.commit() - await state.clear() - - text, keyboard = await _terms_card(session, school_class) - await callback.message.edit_text(text, reply_markup=keyboard) - await callback.answer("Схема изменена") - - -@router.callback_query(TermAction.filter(F.action == "edit")) -async def term_edit_prompt( - callback: CallbackQuery, - callback_data: TermAction, - state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - - # ``_int_or_none``, not ``isdigit`` and ``int``: those two do not ask the - # same question, so «²» passed the check and raised inside the conversion - # — out of the handler, before ``callback.answer`` was ever reached. - index = _int_or_none(callback_data.value) - if index is None or index < 1: - await callback.answer("Неизвестный период", show_alert=True) - return - - await state.set_state(EditTerm.span) - await state.update_data(term_index=index) - await callback.message.edit_text( - f"Период <b>{index}</b>. Пришлите обе даты одной строкой:\n\n" - "<code>01.09.2026 - 31.10.2026</code>", - reply_markup=cancel_keyboard(), - ) - await callback.answer() - - -@router.message(EditTerm.span) -async def term_edit_apply( - message: Message, - state: FSMContext, - session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, -) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - - data = await state.get_data() - index = int(data.get("term_index", 0)) - if index < 1: - await state.clear() - await message.answer("Начните заново: /class", reply_markup=back_to_menu()) - return - - span = terms_service.parse_span(message.text) - if span is None: - await message.answer( - "Не разобрал. Две даты через дефис:\n\n<code>01.09.2026 - 31.10.2026</code>" - ) - return - - try: - await terms_service.set_bounds( - session, school_class, _term_year(school_class), index, span[0], span[1] - ) - except terms_service.TermError as error: - # The message is the rule, in Russian, and the prompt stays open: the - # admin has one date to correct, not a form to start again. - await message.answer(str(error)) - return - - await audit.record( - session, - school_class.id, - message.from_user.id, - "class.term", - f"период {index}: {span[0]:%d.%m.%Y} — {span[1]:%d.%m.%Y}", - ) - await session.commit() - await state.clear() - - text, keyboard = await _terms_card(session, school_class) - await message.answer(text, reply_markup=keyboard) diff --git a/server/app/bot/handlers/manage/__init__.py b/server/app/bot/handlers/manage/__init__.py new file mode 100644 index 00000000..b8e6c6ae --- /dev/null +++ b/server/app/bot/handlers/manage/__init__.py @@ -0,0 +1,268 @@ +"""Running the class: subjects, special days, bells, devices, the log, import. + +This is the structural half of the bot - everything that shapes what the +day-to-day flows in ``content.py`` and ``timetable.py`` are allowed to say. + +Three rules hold everywhere in this package, and each of them is the answer to +a way the previous shape of this code could be abused: + +* **A role check at the top of every handler, including every FSM step.** + FSM state is per-user and therefore attacker-controlled: a client can set + itself into ``EditSubject.name`` and send a message, so a step that trusted + the step before it would be a rename with no permission check at all. +* **Every id arrives as text and is re-scoped by the query that reads it.** + Callback data is user-supplied. A subject is never fetched by id alone but + by ``(id, class_id)``, so a crafted payload naming another class's row finds + nothing rather than editing it. +* **No state in the process.** Every Vercel invocation is a fresh Python + process, so anything that has to survive a step lives in FSM storage (the + database) or in the callback payload - never in a module-level dict. + +User-supplied text is escaped once, at render time, by ``manage_render``; the +few strings built here are escaped in place for the same reason. + +One module per screen of «⚙️ Класс», each with a router of its own, and +``_common`` for what they share. This used to be one file of three and a half +thousand lines, where a change to the bells meant scrolling past the subjects. +The names every module defines are still importable from here, so +``from app.bot.handlers.manage import cmd_bells`` means what it always meant. +""" + +from aiogram import Router + +from app.bot.handlers.manage import ( + audit_log, + bells, + calendar_feed, + class_card, + devices, + diary_binding, + holidays, + import_export, + requests, + stats, + subjects, + terms, +) +from app.bot.handlers.manage._common import ( + NEED_ADMIN, + NEED_EDITOR, + NEED_OWNER, + NO_ACCESS, + _day_kind_or_none, +) +from app.bot.handlers.manage.audit_log import audit_page, cmd_log +from app.bot.handlers.manage.bells import ( + BELLS_ROWS_HELP, + _parse_bells, + bells_create, + bells_delete, + bells_edit, + bells_list, + bells_make_default, + bells_new_name, + bells_new_rows, + bells_rows_apply, + cmd_bells, +) +from app.bot.handlers.manage.calendar_feed import calendar_card, calendar_rotate, cmd_calendar +from app.bot.handlers.manage.class_card import ( + class_delete_apply, + class_delete_prompt, + class_field_apply, + class_field_prompt, + class_root, + class_switch, + class_switch_to, + cmd_class, +) +from app.bot.handlers.manage.devices import cmd_devices, device_revoke, device_unlink, devices_list +from app.bot.handlers.manage.diary_binding import ( + class_diary_bind, + class_diary_cancel, + class_diary_provider, + class_diary_region, + class_diary_school, + class_diary_search, +) +from app.bot.handlers.manage.holidays import ( + _KIND_BY_TAG, + _KIND_SUMMARY, + HOLIDAY_DATE_HELP, + NOTE_MAX, + PERIOD_MAX_DAYS, + _holiday_view, + cmd_holidays, + holiday_add, + holiday_bells, + holiday_delete, + holiday_kind, + holiday_note, + holiday_period_apply, + holiday_period_kind, + holiday_period_start, + holiday_pick_date, + holiday_typed_date, + holidays_list, +) +from app.bot.handlers.manage.import_export import ( + IMPORT_HELP, + cmd_export, + cmd_import, + import_apply, + import_cancel, + import_preview, +) +from app.bot.handlers.manage.requests import ( + cmd_link, + cmd_request, + request_approve, + request_decline, + request_message, +) +from app.bot.handlers.manage.stats import SEARCH_BACK_DAYS, SEARCH_MAX, cmd_find, cmd_stats +from app.bot.handlers.manage.subjects import ( + COLOUR_RE, + SHORT_NAME_MAX, + SUBJECT_NAME_MAX, + TEACHER_MAX, + cmd_subjects, + subject_add, + subject_colour_pick, + subject_colour_typed, + subject_create, + subject_delete, + subject_field, + subject_open, + subject_rename, + subject_short_name, + subject_teacher, + subjects_collect, + subjects_list, +) +from app.bot.handlers.manage.terms import ( + term_edit_apply, + term_edit_prompt, + terms_list, + terms_scheme, +) + +router = Router(name="manage") + +# The order an update is offered to the screens in, written down once here +# rather than implied by which module happens to import which. It is the +# order the handlers stood in when this was one file, with one exception that +# changes nothing: «📅 Календарь»'s two buttons used to sit after the diary +# binding's five, and every one of those seven matches its own +# `ManageAction.action` or `DiarySchoolPick`, so no press can match two. +router.include_routers( + subjects.router, + holidays.router, + bells.router, + devices.router, + audit_log.router, + class_card.router, + calendar_feed.router, + diary_binding.router, + import_export.router, + stats.router, + requests.router, + terms.router, +) + +__all__ = [ + "BELLS_ROWS_HELP", + "COLOUR_RE", + "HOLIDAY_DATE_HELP", + "IMPORT_HELP", + "NEED_ADMIN", + "NEED_EDITOR", + "NEED_OWNER", + "NOTE_MAX", + "NO_ACCESS", + "PERIOD_MAX_DAYS", + "SEARCH_BACK_DAYS", + "SEARCH_MAX", + "SHORT_NAME_MAX", + "SUBJECT_NAME_MAX", + "TEACHER_MAX", + "_KIND_BY_TAG", + "_KIND_SUMMARY", + "_day_kind_or_none", + "_holiday_view", + "_parse_bells", + "audit_page", + "bells_create", + "bells_delete", + "bells_edit", + "bells_list", + "bells_make_default", + "bells_new_name", + "bells_new_rows", + "bells_rows_apply", + "calendar_card", + "calendar_rotate", + "class_delete_apply", + "class_delete_prompt", + "class_diary_bind", + "class_diary_cancel", + "class_diary_provider", + "class_diary_region", + "class_diary_school", + "class_diary_search", + "class_field_apply", + "class_field_prompt", + "class_root", + "class_switch", + "class_switch_to", + "cmd_bells", + "cmd_calendar", + "cmd_class", + "cmd_devices", + "cmd_export", + "cmd_find", + "cmd_holidays", + "cmd_import", + "cmd_link", + "cmd_log", + "cmd_request", + "cmd_stats", + "cmd_subjects", + "device_revoke", + "device_unlink", + "devices_list", + "holiday_add", + "holiday_bells", + "holiday_delete", + "holiday_kind", + "holiday_note", + "holiday_period_apply", + "holiday_period_kind", + "holiday_period_start", + "holiday_pick_date", + "holiday_typed_date", + "holidays_list", + "import_apply", + "import_cancel", + "import_preview", + "request_approve", + "request_decline", + "request_message", + "router", + "subject_add", + "subject_colour_pick", + "subject_colour_typed", + "subject_create", + "subject_delete", + "subject_field", + "subject_open", + "subject_rename", + "subject_short_name", + "subject_teacher", + "subjects_collect", + "subjects_list", + "term_edit_apply", + "term_edit_prompt", + "terms_list", + "terms_scheme", +] diff --git a/server/app/bot/handlers/manage/_common.py b/server/app/bot/handlers/manage/_common.py new file mode 100644 index 00000000..e3ccf6d2 --- /dev/null +++ b/server/app/bot/handlers/manage/_common.py @@ -0,0 +1,144 @@ +"""What every screen of :mod:`app.bot.handlers.manage` shares. + +The refusal sentences, the one permission check, and the small parsers that +turn a value the client sent into one the handlers can trust or ``None``. +""" + +from __future__ import annotations + +import re +from datetime import date as Date +from datetime import datetime + +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.models import AccessRequest, BotUser, DayKind, Role, SchoolClass + +NO_ACCESS = "Нет доступа. Откройте /start, чтобы получить его." +NEED_ADMIN = "Только для администраторов" +NEED_EDITOR = "Нужна роль редактора" +NEED_OWNER = "Только для владельца класса" + + +# -------------------------------------------------------------------------- +# Guards and small parsers +# -------------------------------------------------------------------------- + + +def _allowed(school_class: SchoolClass | None, role: Role | None, minimum: Role) -> bool: + """The whole of the permission check, in one place so no handler invents + its own version of it.""" + return school_class is not None and role is not None and role.at_least(minimum) + + +def _refusal(role: Role | None, minimum: Role) -> str: + if role is None: + return NO_ACCESS + if minimum is Role.OWNER: + return NEED_OWNER + return NEED_ADMIN if minimum is Role.ADMIN else NEED_EDITOR + + +def _int_or_none(raw: str) -> int | None: + """An id out of callback data, or ``None`` for anything a crafted one carries.""" + try: + return int(raw) + except (TypeError, ValueError): + return None + + +def _day_kind_or_none(raw: str) -> DayKind | None: + """A day kind out of callback data or FSM state, or ``None``. + + `DayKind(raw)` raises on anything else, and a raise here leaves the button + spinning until Telegram gives up rather than answering — the same trap the + `_int_or_none` above exists for, on a value that arrives from the client. + """ + try: + return DayKind(raw) + except ValueError: + return None + + +def _date_or_none(raw: str) -> Date | None: + try: + return Date.fromisoformat(raw) + except (TypeError, ValueError): + return None + + +def _today(school_class: SchoolClass) -> Date: + """Today on the class's own wall clock, never the server's.""" + return datetime.now(school_class.tz).date() + + +def _bot_of(event: Message | CallbackQuery): + """The Bot behind an update, or ``None``. + + The handler tests call these functions with plain stubs that have no bot + at all, and a notification is never worth failing the edit it describes. + """ + return getattr(event, "bot", None) + + +def _parse_day(raw: str, today: Date) -> Date | None: + """«12.09» or «12.09.2026» -> a date. + + A bare day and month is read in the current year unless that lands well in + the past: a school year straddles New Year, so «10.01» typed in December + means the January that is coming, not the one that has gone. + + Both conversions are inside the ``try``, and it catches ``OverflowError`` + as well, because ``str.isdigit()`` is not the same question as «will + ``int()`` take this» and ``date()`` does not raise only ``ValueError``. + Every character of «²2.09» is a digit to ``isdigit`` and «²2» is a + ``ValueError`` to ``int``; «12.09.99999999999999999999» converts happily + and then overflows the C long ``date()`` is built on. Either way the + exception went straight past the ``except ValueError`` and out of the + handler — and both callers are `Message` handlers with no callback to + apologise on, so a stuck key on the year bought an answer that never came + and a prompt still waiting for a date, which the next thing typed would be + read as. + """ + parts = [part for part in re.split(r"[.\-/\s]+", raw.strip()) if part] + if len(parts) not in (2, 3) or not all(part.isdigit() for part in parts): + return None + try: + day, month = int(parts[0]), int(parts[1]) + if len(parts) == 3: + year = int(parts[2]) + if year < 100: + year += 2000 + else: + year = today.year + result = Date(year, month, day) + except (ValueError, OverflowError): + return None + if len(parts) == 2 and (today - result).days > 90: + try: + result = Date(year + 1, month, day) + except ValueError: # pragma: no cover - 29 February in a common year + return None + return result + + +async def _pending_requests(session: AsyncSession, class_id: int) -> list[AccessRequest]: + return list( + await session.scalars( + select(AccessRequest) + .where(AccessRequest.class_id == class_id, AccessRequest.status == "pending") + .order_by(AccessRequest.id) + ) + ) + + +async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: + """Telegram id -> the name to show, already escaped by ``manage_render``.""" + members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) + return { + member.telegram_id: mr.person(member.full_name, member.username, member.telegram_id) + for member in members + } diff --git a/server/app/bot/handlers/manage/audit_log.py b/server/app/bot/handlers/manage/audit_log.py new file mode 100644 index 00000000..78591e48 --- /dev/null +++ b/server/app/bot/handlers/manage/audit_log.py @@ -0,0 +1,77 @@ +"""«📜 Журнал»: who changed what, a page at a time. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal +from app.bot.manage_keyboards import AuditAction, audit_keyboard +from app.models import Role, SchoolClass +from app.services import audit + +router = Router(name="manage.audit_log") + + +# -------------------------------------------------------------------------- +# 📜 The log +# -------------------------------------------------------------------------- + + +async def _audit_view(session: AsyncSession, school_class: SchoolClass, offset: int): + entries = await audit.recent(session, school_class.id, limit=mr.AUDIT_PAGE + 1, offset=offset) + more = len(entries) > mr.AUDIT_PAGE + entries = entries[:mr.AUDIT_PAGE] + names = await _member_names(session, school_class.id) + return ( + mr.render_audit(entries, names, school_class.tz, offset), + audit_keyboard(offset, more), + ) + + +@router.message(Command("log")) +async def cmd_log( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.clear() + text, keyboard = await _audit_view(session, school_class, 0) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(AuditAction.filter(F.action == "page")) +async def audit_page( + callback: CallbackQuery, + callback_data: AuditAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + offset = _int_or_none(callback_data.value) or 0 + # A negative offset is not a page; SQL would take it as "no offset" and + # quietly show page one under a heading that says otherwise. + offset = max(0, offset) + + await state.clear() + text, keyboard = await _audit_view(session, school_class, offset) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() diff --git a/server/app/bot/handlers/manage/bells.py b/server/app/bot/handlers/manage/bells.py new file mode 100644 index 00000000..641fa3b0 --- /dev/null +++ b/server/app/bot/handlers/manage/bells.py @@ -0,0 +1,452 @@ +"""«🔔 Звонки»: the class's bell schedules and which one is the default. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot import render +from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.handlers.timetable import REJECTED_MAX +from app.bot.keyboards import back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import BellsAction, bells_list_keyboard +from app.bot.manage_states import EditBellRows, NewBellSchedule +from app.bot.render import clamp, more_line, plural +from app.models import BellSchedule, DayOverride, Role, SchoolClass +from app.services import audit, structure, timetable_io + +router = Router(name="manage.bells") + + +# -------------------------------------------------------------------------- +# 🔔 Bells +# -------------------------------------------------------------------------- +# +# A class may keep several bell schedules — «Обычное», «Сокращённое», «Суббота» +# — and a shortened day points at one of them. One of them is the class +# default, and that one is what the day view uses when nothing else says +# otherwise. + +BELLS_ROWS_HELP = ( + "Пришлите строки расписания:\n\n" + "<code>1. 08:30-09:15\n" + "2. 09:25-10:10\n" + "3. 10:25-11:10</code>\n\n" + "Строка, которую я не разберу, не изменит сохранённое — " + "пустой присылкой звонки не стереть." +) + + +def _parse_bells(raw: str): + """Rows out of a paste, via the same grammar the week import uses. + + ``parse_bells_block`` only reads what is under a «== Звонки ==» header, + because a week paste must never touch the bells by accident. Here the + header is implied by the question that was asked, so it is prepended. + """ + return timetable_io.parse_bells_block("== Звонки ==\n" + (raw or "")) + + +async def _schedules_of(session: AsyncSession, class_id: int) -> list[BellSchedule]: + return list( + await session.scalars( + select(BellSchedule) + .where(BellSchedule.class_id == class_id) + .order_by(BellSchedule.id) + ) + ) + + +async def _rung_by_default(session: AsyncSession, school_class: SchoolClass) -> set[int]: + """The lesson numbers the class rings today. Empty when it has no default.""" + if school_class.bell_schedule_id is None: + return set() + current = await session.scalar( + select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) + ) + return {period.index for period in current.periods} if current is not None else set() + + +async def _schedule_by_id( + session: AsyncSession, school_class: SchoolClass, raw: str +) -> BellSchedule | None: + schedule_id = _int_or_none(raw) + if schedule_id is None: + return None + return await session.scalar( + select(BellSchedule).where( + BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id + ) + ) + + +async def _bells_view(session: AsyncSession, school_class: SchoolClass): + schedules = await _schedules_of(session, school_class.id) + return mr.render_bells(schedules, school_class.bell_schedule_id), bells_list_keyboard( + schedules, school_class.bell_schedule_id + ) + + +@router.message(Command("bells")) +async def cmd_bells( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.clear() + text, keyboard = await _bells_view(session, school_class) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(BellsAction.filter(F.action == "list")) +async def bells_list( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.clear() + text, keyboard = await _bells_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +@router.callback_query(BellsAction.filter(F.action == "edit")) +async def bells_edit( + callback: CallbackQuery, + callback_data: BellsAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + schedule = await _schedule_by_id(session, school_class, callback_data.value) + if schedule is None: + await callback.answer("Расписание не найдено", show_alert=True) + return + + await state.set_state(EditBellRows.rows) + await state.update_data(schedule_id=schedule.id) + current = mr.render_bell_rows(schedule) + body = f"🔔 <b>{escape(schedule.name)}</b>\n\n" + if current: + body += f"<code>{escape(current)}</code>\n\n" + await callback.message.edit_text(body + BELLS_ROWS_HELP, reply_markup=cancel_keyboard()) + await callback.answer() + + +@router.message(EditBellRows.rows) +async def bells_rows_apply( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + data = await state.get_data() + schedule = await _schedule_by_id(session, school_class, str(data.get("schedule_id", ""))) + if schedule is None: + await state.clear() + await message.answer("Расписание уже удалено.", reply_markup=back_to_menu()) + return + + rows, rejected = _parse_bells(message.text or "") + if not rows: + # The stored schedule is the thing a class runs on; a paste that turned + # out to be prose must never be the reason it disappears. + await message.answer( + "Не удалось разобрать ни одной строки — звонки не изменены.\n\n" + BELLS_ROWS_HELP, + reply_markup=cancel_keyboard(), + ) + return + + orphaned = await structure.write_bell_periods(session, schedule, rows) + summary = f"звонки «{schedule.name}»: {len(rows)} уроков" + if orphaned: + summary += f", перестали звонить уроков: {len(orphaned)}" + await audit.record( + session, + school_class.id, + message.from_user.id, + "bells.edit", + summary, + ) + await session.commit() + await session.refresh(schedule, ["periods"]) + await state.clear() + + lines = [f"✅ Звонки «{escape(schedule.name)}» сохранены: {len(rows)}."] + if orphaned: + # The lessons that were already there and no longer ring. They are not + # deleted — they are stored and drawn nowhere — so this sentence is the + # only place anybody is told, and it lives in `render` because the + # other bells editor has to say the very same thing. + lines.append("") + lines.append(render.silenced_lessons(orphaned)) + if rejected: + lines.append("") + lines.append("⚠️ Не разобрал строки:") + lines.extend(f"<code>{escape(line)}</code>" for line in rejected[:REJECTED_MAX]) + lines.extend(more_line(len(rejected), REJECTED_MAX)) + await message.answer(clamp(lines)) + + text, keyboard = await _bells_view(session, school_class) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(BellsAction.filter(F.action == "create")) +async def bells_create( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.set_state(NewBellSchedule.name) + await callback.message.edit_text( + "Название нового расписания звонков, например <code>Сокращённое</code>:", + reply_markup=cancel_keyboard(), + ) + await callback.answer() + + +@router.message(NewBellSchedule.name) +async def bells_new_name( + message: Message, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + name = " ".join((message.text or "").split()) + if not 1 <= len(name) <= 64: + await message.answer("Название от 1 до 64 символов. Ещё раз:") + return + + await state.update_data(name=name) + await state.set_state(NewBellSchedule.rows) + await message.answer( + f"<b>{escape(name)}</b>\n\n{BELLS_ROWS_HELP}", reply_markup=cancel_keyboard() + ) + + +@router.message(NewBellSchedule.rows) +async def bells_new_rows( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + data = await state.get_data() + name = str(data.get("name", "")).strip() + if not name: + await state.clear() + await message.answer("Начните заново: /bells", reply_markup=back_to_menu()) + return + + rows, rejected = _parse_bells(message.text or "") + if not rows: + await message.answer( + "Не удалось разобрать ни одной строки.\n\n" + BELLS_ROWS_HELP, + reply_markup=cancel_keyboard(), + ) + return + + schedule = BellSchedule(class_id=school_class.id, name=name[:64]) + session.add(schedule) + await session.flush() + await structure.write_bell_periods(session, schedule, rows) + await audit.record( + session, + school_class.id, + message.from_user.id, + "bells.create", + f"создано расписание звонков «{name}»: {len(rows)} уроков", + ) + await session.commit() + await session.refresh(schedule, ["periods"]) + await state.clear() + + lines = [f"✅ Расписание «{escape(name)}» создано: " + f"{plural(len(rows), 'урок', 'урока', 'уроков')}."] + if rejected: + # The same shape as `bells_rows_apply` above and `timetable_apply`: + # a row cap *and* a character budget. Five was the row cap alone, and + # a rejected line is echoed whole — one 4094-character paste whose + # first line is a real bell row and whose other five are prose came to + # 4152 characters, which Telegram refuses. The schedule had been + # created and committed by then, and this is a `Message` handler with + # no callback to apologise on, so the admin saw neither the + # confirmation nor the «🔔 Расписания звонков» list that follows it. + lines.append("") + lines.append("⚠️ Не разобрал строки:") + lines.extend(f"<code>{escape(line)}</code>" for line in rejected[:REJECTED_MAX]) + lines.extend(more_line(len(rejected), REJECTED_MAX)) + await message.answer(clamp(lines)) + + text, keyboard = await _bells_view(session, school_class) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(BellsAction.filter(F.action == "default")) +async def bells_make_default( + callback: CallbackQuery, + callback_data: BellsAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + schedule = await _schedule_by_id(session, school_class, callback_data.value) + if schedule is None: + await callback.answer("Расписание не найдено", show_alert=True) + return + + # A schedule may be created empty — that is the two-step flow, and the rows + # are the next screen. Making an empty one the *class default* is another + # thing: every ordinary day rings it, and a day that rings nothing draws + # nothing. `/bundle` answers zero lessons, `/now` answers «выходной» on a + # Monday, and the phone, the widget, the calendar feed and the morning + # digest go blank together with nothing anywhere reporting a problem — + # while the class's own timetable sits untouched underneath, which is what + # makes it so hard to see. Worse, `rung_indexes` then returns an empty set, + # which `can_ring` reads as «this class has not set its bells up yet» and + # waves every lesson number through. `api/manage.bells_update` has refused + # this since it was written and the «⭐» beside it did not; one rule, two + # shells, is the whole reason `services/` exists. + if not schedule.periods: + await callback.answer( + "В этом расписании звонков нет ни одного урока — сделать его " + "основным нельзя. Сначала добавьте времена.", + show_alert=True, + ) + return + + # Moving the default to a *shorter* schedule takes lessons off every + # weekday exactly as shrinking the current one does, and nothing rewrites a + # row, so `write_bell_periods` never runs and never counts them. Asked here + # through the same function the API asks, so the two answer alike. + was = await _rung_by_default(session, school_class) + orphaned = await structure.lessons_silenced_by( + session, school_class.id, was, {period.index for period in schedule.periods} + ) + school_class.bell_schedule_id = schedule.id + summary = f"основное расписание звонков: «{schedule.name}»" + if orphaned: + summary += f", перестали звонить уроков: {len(orphaned)}" + await audit.record( + session, school_class.id, callback.from_user.id, "bells.default", summary, + ) + await session.commit() + + text, keyboard = await _bells_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + if orphaned: + # An alert rather than the log alone: the admin pressed a star and four + # lessons left every phone in the class, and the audit page is not + # where anybody looks next. + await callback.answer( + f"Основное расписание обновлено. Перестали звонить уроков: " + f"{len(orphaned)} — они остались в базе, но их никто не увидит.", + show_alert=True, + ) + return + await callback.answer("Основное расписание обновлено") + + +@router.callback_query(BellsAction.filter(F.action == "delete")) +async def bells_delete( + callback: CallbackQuery, + callback_data: BellsAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Refused for the class default and for anything a day still points at. + + Both are a ``SET NULL`` at the database level, which would silently move + those days onto the default schedule — a change nobody asked for, on dates + an admin is not looking at. + """ + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + schedule = await _schedule_by_id(session, school_class, callback_data.value) + if schedule is None: + await callback.answer("Расписание не найдено", show_alert=True) + return + + if schedule.id == school_class.bell_schedule_id: + await callback.answer( + "Это основное расписание класса. Сначала сделайте основным другое.", + show_alert=True, + ) + return + + used = await session.scalar( + select(func.count()) + .select_from(DayOverride) + .where( + DayOverride.class_id == school_class.id, + DayOverride.bell_schedule_id == schedule.id, + ) + ) + if used: + await callback.answer( + f"По нему идут особые дни ({used}). Сначала измените их.", show_alert=True + ) + return + + name = schedule.name + await session.delete(schedule) + await audit.record( + session, school_class.id, callback.from_user.id, "bells.delete", + f"удалено расписание звонков «{name}»", + ) + await session.commit() + + text, keyboard = await _bells_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer(f"Удалено: {name}"[:200]) diff --git a/server/app/bot/handlers/manage/calendar_feed.py b/server/app/bot/handlers/manage/calendar_feed.py new file mode 100644 index 00000000..659db94c --- /dev/null +++ b/server/app/bot/handlers/manage/calendar_feed.py @@ -0,0 +1,114 @@ +"""«📅 Календарь»: the class's read-only calendar feed and its secret link. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, InlineKeyboardButton, Message +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _refusal +from app.bot.keyboards import back_to_menu +from app.bot.manage_keyboards import ManageAction, back_to +from app.config import get_settings +from app.models import Role, SchoolClass +from app.services import audit +from app.services import calendar as calendar_service + +router = Router(name="manage.calendar_feed") + + +# -------------------------------------------------------------------------- +# 📅 Calendar +# -------------------------------------------------------------------------- + + +async def _calendar_text(session: AsyncSession, school_class: SchoolClass, rotated: bool) -> str: + base = get_settings().public_base_url.rstrip("/") + if not base: + return mr.render_calendar(None) + if rotated: + token = await calendar_service.rotate_calendar_token(session, school_class) + else: + token = await calendar_service.ensure_calendar_token(session, school_class) + return mr.render_calendar(f"{base}/api/v1/calendar/{token}.ics", rotated=rotated) + + +def _calendar_keyboard(role: Role): + rows: list[list[InlineKeyboardButton]] = [] + if role.at_least(Role.ADMIN): + rows.append( + [ + InlineKeyboardButton( + text="🔁 Новая ссылка", + callback_data=ManageAction(action="rotate_feed").pack(), + ) + ] + ) + rows.append(back_to("root")) + return back_to_menu(rows) + + +@router.message(Command("calendar")) +async def cmd_calendar( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Any member may subscribe: the feed is read-only and its secret is not + the join code, so a calendar URL cannot be turned into write access.""" + if not _allowed(school_class, role, Role.VIEWER): + await message.answer(NO_ACCESS) + return + await state.clear() + await message.answer( + await _calendar_text(session, school_class, rotated=False), + reply_markup=_calendar_keyboard(role), + ) + + +@router.callback_query(ManageAction.filter(F.action == "calendar")) +async def calendar_card( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.VIEWER): + await callback.answer(NO_ACCESS, show_alert=True) + return + await callback.message.edit_text( + await _calendar_text(session, school_class, rotated=False), + reply_markup=_calendar_keyboard(role), + ) + await callback.answer() + + +@router.callback_query(ManageAction.filter(F.action == "rotate_feed")) +async def calendar_rotate( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Every existing subscription stops updating — that is the point.""" + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + text = await _calendar_text(session, school_class, rotated=True) + await audit.record( + session, school_class.id, callback.from_user.id, "calendar.rotate", + "выдана новая ссылка на календарь, старая отключена", + ) + await session.commit() + await callback.message.edit_text(text, reply_markup=_calendar_keyboard(role)) + await callback.answer("Ссылка обновлена") diff --git a/server/app/bot/handlers/manage/class_card.py b/server/app/bot/handlers/manage/class_card.py new file mode 100644 index 00000000..9da7e22d --- /dev/null +++ b/server/app/bot/handlers/manage/class_card.py @@ -0,0 +1,362 @@ +"""«⚙️ Класс»: the class card, its typed fields, switching class and deleting it. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import ( + NEED_OWNER, + NO_ACCESS, + _allowed, + _int_or_none, + _pending_requests, + _refusal, +) +from app.bot.keyboards import Menu, back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import ManageAction, class_menu, switch_keyboard +from app.bot.manage_states import DeleteClass, EditClassField +from app.bot.middlewares import prefs_key +from app.bot.roles import list_memberships +from app.db import SessionLocal +from app.fsm_storage import DatabaseStorage +from app.models import BotUser, DeviceToken, Role, SchoolClass +from app.providers.diary.registry import binding as diary_binding +from app.services import audit +from app.timezones import label_for + +router = Router(name="manage.class_card") + + +# -------------------------------------------------------------------------- +# ⚙️ The class +# -------------------------------------------------------------------------- + + +async def _class_card( + session: AsyncSession, school_class: SchoolClass, role: Role, telegram_id: int +): + memberships = await list_memberships(session, telegram_id) + members = int( + await session.scalar( + select(func.count()).select_from(BotUser).where(BotUser.class_id == school_class.id) + ) + or 0 + ) + devices = int( + await session.scalar( + select(func.count()) + .select_from(DeviceToken) + .where(DeviceToken.class_id == school_class.id, DeviceToken.revoked.is_(False)) + ) + or 0 + ) + pending = len(await _pending_requests(session, school_class.id)) + + text = mr.render_class_card( + school_class, + zone_label=label_for(school_class.timezone_name), + feed_ready=bool(school_class.calendar_token), + members=members, + devices=devices, + pending=pending, + diary_label=_diary_label(school_class), + ) + keyboard = class_menu( + is_owner=role.at_least(Role.OWNER), + # The button only appears for somebody who actually has somewhere to + # switch to; one membership is the overwhelmingly common case. + many_classes=len(memberships) > 1, + pending=pending, + diary_bound=bool(school_class.diary_provider), + ) + return text, keyboard + + +def _diary_label(school_class: SchoolClass) -> str: + """The diary line for the class card: the provider, and for «Сетевой город» + the region and school. Reads the binding, so a class bound to a region since + dropped from the allow-list reads «не привязан» rather than a dead name.""" + b = diary_binding(school_class) + if b is None: + return "не привязан" + if b.region: + from app.providers.netschool import regions + + region = regions.get(b.region) + parts = [b.provider.title] + if region is not None: + parts.append(region.title) + if b.school_name: + parts.append(b.school_name) + return " · ".join(parts) + return b.provider.title + + +@router.message(Command("class")) +async def cmd_class( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.clear() + text, keyboard = await _class_card(session, school_class, role, message.from_user.id) + await message.answer(text, reply_markup=keyboard) + + +# Two entry points, one card. The «⚙️ Класс» button in the main menu used to +# open a thinner version of this that lived in start.py, so half the settings +# were on whichever card you had not opened. +@router.callback_query(Menu.filter(F.action == "class")) +@router.callback_query(ManageAction.filter(F.action == "root")) +async def class_root( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.clear() + text, keyboard = await _class_card(session, school_class, role, callback.from_user.id) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +#: field tag -> (column, prompt, limit). Only these three are typed; the zone +#: and the join code have pickers of their own in ``start.py``. +_CLASS_FIELDS = { + "rename": ("name", "Новое название класса:", 64), + "school": ("school", "Название школы («-» — убрать):", 200), + "city": ("city", "Город («-» — убрать):", 120), +} + + +@router.callback_query(ManageAction.filter(F.action.in_({"rename", "school", "city"}))) +async def class_field_prompt( + callback: CallbackQuery, + callback_data: ManageAction, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + target = _CLASS_FIELDS.get(callback_data.action) + if target is None: # pragma: no cover - the filter already narrowed it + await callback.answer("Неизвестное поле", show_alert=True) + return + + _, prompt, _ = target + await state.set_state(EditClassField.value) + await state.update_data(field=callback_data.action) + await callback.message.edit_text(prompt, reply_markup=cancel_keyboard()) + await callback.answer() + + +@router.message(EditClassField.value) +async def class_field_apply( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + data = await state.get_data() + target = _CLASS_FIELDS.get(str(data.get("field", ""))) + if target is None: + await state.clear() + await message.answer("Начните заново: /class", reply_markup=back_to_menu()) + return + column, prompt, limit = target + + raw = " ".join((message.text or "").split()) + if column == "name": + # The name is what every other message calls this class, and what the + # delete confirmation is typed against; it cannot be empty. + if not 1 <= len(raw) <= limit: + await message.answer(f"От 1 до {limit} символов. {prompt}") + return + value = raw + else: + value = None if raw in {"-", "—", ""} else raw[:limit] + + setattr(school_class, column, value) + await audit.record( + session, + school_class.id, + message.from_user.id, + f"class.{column}", + f"{column}: {value or 'убрано'}", + ) + await session.commit() + await state.clear() + + text, keyboard = await _class_card(session, school_class, role, message.from_user.id) + await message.answer(text, reply_markup=keyboard) + + +# -------------------------------------------------------------------------- +# 🔀 Switching class +# -------------------------------------------------------------------------- + + +@router.callback_query(ManageAction.filter(F.action == "switch")) +async def class_switch( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.VIEWER): + await callback.answer(NO_ACCESS, show_alert=True) + return + + memberships = await list_memberships(session, callback.from_user.id) + classes: list[SchoolClass] = [] + for member in memberships: + found = await session.get(SchoolClass, member.class_id) + if found is not None: + classes.append(found) + if len(classes) < 2: + await callback.answer("Вы состоите только в одном классе", show_alert=True) + return + + await callback.message.edit_text( + "🔀 <b>Сменить класс</b>\n\nВ каком классе работаем дальше?", + reply_markup=switch_keyboard(classes), + ) + await callback.answer() + + +@router.callback_query(ManageAction.filter(F.action == "switch_to")) +async def class_switch_to( + callback: CallbackQuery, + callback_data: ManageAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Remember which class this person is working in. + + The preference is written to FSM storage — the database — under its own + key, and the middleware reads exactly that key on the next update. Nothing + is kept in the process: on Vercel the next message is a different one. + + The membership is checked here and checked again by the middleware every + time it reads the preference, so a class somebody is later removed from + stops being their default by itself. + """ + if school_class is None or role is None: + await callback.answer(NO_ACCESS, show_alert=True) + return + + class_id = _int_or_none(callback_data.value) + memberships = await list_memberships(session, callback.from_user.id) + if class_id is None or not any(member.class_id == class_id for member in memberships): + await callback.answer("Вы не состоите в этом классе", show_alert=True) + return + + target = await session.get(SchoolClass, class_id) + if target is None: + await callback.answer("Класс не найден", show_alert=True) + return + + storage = DatabaseStorage(SessionLocal) + await storage.set_data(prefs_key(callback.from_user.id), {"class_id": class_id}) + + await state.clear() + await callback.message.edit_text( + f"✅ Текущий класс: <b>{escape(target.name)}</b>.\n\n" + "Все команды теперь про него. Открыть меню: /start", + reply_markup=back_to_menu(), + ) + await callback.answer(f"Класс: {target.name}"[:200]) + + +# -------------------------------------------------------------------------- +# 🗑 Deleting a class +# -------------------------------------------------------------------------- + + +@router.callback_query(ManageAction.filter(F.action == "delete")) +async def class_delete_prompt( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.OWNER): + await callback.answer(NEED_OWNER, show_alert=True) + return + + await state.set_state(DeleteClass.confirm) + await callback.message.edit_text( + f"🗑 <b>Удалить класс {escape(school_class.name)}?</b>\n\n" + "Вместе с ним исчезнут расписание, домашние задания, замены, события, " + "журнал и все привязанные устройства. Это нельзя отменить.\n\n" + f"Чтобы подтвердить, пришлите название класса точно так: " + f"<code>{escape(school_class.name)}</code>", + reply_markup=cancel_keyboard(), + ) + await callback.answer() + + +@router.message(DeleteClass.confirm) +async def class_delete_apply( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Typing the name back is the confirmation, and the only one. + + A «вы уверены?» button is pressed by the same thumb that pressed the one + before it. Nothing here writes an audit line: the log lives in the class + and goes with it. + """ + if not _allowed(school_class, role, Role.OWNER): + await state.clear() + return + + typed = (message.text or "").strip() + if typed != school_class.name: + await message.answer( + "Название не совпало — класс не тронут.\n" + f"Чтобы удалить, пришлите ровно: <code>{escape(school_class.name)}</code>" + ) + return + + name = school_class.name + await session.delete(school_class) + await session.commit() + await state.clear() + await message.answer( + f"🗑 Класс <b>{escape(name)}</b> удалён вместе со всеми данными." + ) diff --git a/server/app/bot/handlers/manage/devices.py b/server/app/bot/handlers/manage/devices.py new file mode 100644 index 00000000..11d8af45 --- /dev/null +++ b/server/app/bot/handlers/manage/devices.py @@ -0,0 +1,159 @@ +"""«📱 Устройства»: the phones on the class, revoked or unlinked from here. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal +from app.bot.manage_keyboards import DeviceAction, device_keyboard +from app.models import DeviceToken, Role, SchoolClass +from app.services import audit, linking + +router = Router(name="manage.devices") + + +# -------------------------------------------------------------------------- +# 📱 Devices +# -------------------------------------------------------------------------- +# +# A device token is read-only until its owner links it to a Telegram account; +# from then on it writes with whatever role that account holds *right now* +# (``linking.effective_role``). Which is why this page shows the role as a +# lookup and not as something stored on the row: revoking somebody in «Доступ» +# has already revoked their phone by the time this page is drawn. + + +async def _device_view(session: AsyncSession, school_class: SchoolClass): + devices = await linking.devices_of(session, school_class.id) + owners: dict[int, tuple[str, Role | None]] = {} + names = await _member_names(session, school_class.id) + for device in devices: + if device.telegram_id is None or device.telegram_id in owners: + continue + owners[device.telegram_id] = ( + names.get(device.telegram_id, str(device.telegram_id)), + await linking.effective_role(session, device), + ) + return mr.render_devices(devices, owners), device_keyboard(devices) + + +async def _device_by_id( + session: AsyncSession, school_class: SchoolClass, raw: str +) -> DeviceToken | None: + device_id = _int_or_none(raw) + if device_id is None: + return None + return await session.scalar( + select(DeviceToken).where( + DeviceToken.id == device_id, DeviceToken.class_id == school_class.id + ) + ) + + +@router.message(Command("devices")) +async def cmd_devices( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.clear() + text, keyboard = await _device_view(session, school_class) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(DeviceAction.filter(F.action == "list")) +async def devices_list( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.clear() + text, keyboard = await _device_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +@router.callback_query(DeviceAction.filter(F.action == "revoke")) +async def device_revoke( + callback: CallbackQuery, + callback_data: DeviceAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Revoked, not deleted: the row is what the API checks a token against, + and keeping it is what makes the refusal instant and permanent.""" + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + device = await _device_by_id(session, school_class, callback_data.value) + if device is None: + await callback.answer("Устройство не найдено", show_alert=True) + return + + device.revoked = True + name = device.device_name or f"Устройство {device.id}" + await audit.record( + session, school_class.id, callback.from_user.id, "device.revoke", + f"отключено устройство «{name}»", + ) + await session.commit() + + text, keyboard = await _device_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer(f"Отключено: {name}"[:200]) + + +@router.callback_query(DeviceAction.filter(F.action == "unlink")) +async def device_unlink( + callback: CallbackQuery, + callback_data: DeviceAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Back to read-only without taking the phone off the class.""" + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + device = await _device_by_id(session, school_class, callback_data.value) + if device is None: + await callback.answer("Устройство не найдено", show_alert=True) + return + if device.telegram_id is None: + await callback.answer("Устройство и так не привязано", show_alert=True) + return + + name = device.device_name or f"Устройство {device.id}" + await linking.unlink_device(session, device) + await audit.record( + session, school_class.id, callback.from_user.id, "device.unlink", + f"отвязано устройство «{name}» — снова только чтение", + ) + await session.commit() + + text, keyboard = await _device_view(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer("Отвязано — теперь только чтение") diff --git a/server/app/bot/handlers/manage/diary_binding.py b/server/app/bot/handlers/manage/diary_binding.py new file mode 100644 index 00000000..960dfda7 --- /dev/null +++ b/server/app/bot/handlers/manage/diary_binding.py @@ -0,0 +1,287 @@ +"""«📒 Дневник» on the class card: binding the class to an electronic diary. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from html import escape + +from aiogram import F, Router +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot.handlers.manage._common import _allowed +from app.bot.handlers.manage.class_card import _class_card +from app.bot.keyboards import DiarySchoolPick +from app.bot.manage_keyboards import ( + DIARY_SCHOOLS_MAX, + ManageAction, + diary_provider_menu, + diary_region_menu, + diary_school_menu, +) +from app.bot.states import BindDiary +from app.models import Role, SchoolClass +from app.providers.diary.errors import AddressRefused, DiaryError, SignInUnsupported +from app.providers.diary.registry import NETSCHOOL, PETERSBURG +from app.providers.netschool import regions as ns_regions +from app.providers.netschool.client import NetSchoolClient +from app.services import audit, diary_link +from app.services import diary as diary_service + +router = Router(name="manage.diary_binding") + + +@router.callback_query(ManageAction.filter(F.action == "diary_bind")) +async def class_diary_bind( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Bind or unbind the class's electronic diary. + + Binding gives the class nothing and takes nothing: it puts «📒 Мой дневник» + on every member's menu, and what is behind that button is each member's own + account. Unbinding likewise only removes the door — the sessions people + opened stay theirs until they sign out, and are dropped with the class. + """ + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await callback.answer("Только для администраторов", show_alert=True) + return + + if school_class.diary_provider: + # Bound → unbind. The door goes; the sessions people opened stay theirs + # until they sign out or the class is deleted, as three screens promise. + # Nothing is expired here, deliberately: with no binding the bot reads + # none of them anyway, and a later bind expires exactly those it does + # not read (`diary_service.expire_off_binding`) — which, unlike this, + # knows which diary the class went to. + school_class.diary_provider = None + school_class.diary_region = None + school_class.diary_school_id = None + school_class.diary_school_name = None + # An outstanding sign-in link would still open a form; the submit + # refuses an unbound class, but only a dropped ticket survives a + # rebind that follows at once (#137). + await diary_link.drop_for_class(session, school_class.id) + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", "дневник отвязан" + ) + await session.commit() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Дневник отвязан") + return + + # Unbound → choose which diary. There is more than one now, so binding is a + # small chooser rather than a single toggle. + await callback.message.edit_text( + "📒 <b>Электронный дневник</b>\n\nВыберите, к какому дневнику привязать класс.", + reply_markup=diary_provider_menu(), + ) + await callback.answer() + + +@router.callback_query(ManageAction.filter(F.action == "diary_prov")) +async def class_diary_provider( + callback: CallbackQuery, + callback_data: ManageAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Second step of binding: the provider was picked.""" + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await callback.answer("Только для администраторов", show_alert=True) + return + if callback_data.value == PETERSBURG: + school_class.diary_provider = PETERSBURG + school_class.diary_region = None + school_class.diary_school_id = None + school_class.diary_school_name = None + # The members' «Сетевой город» sessions read a diary the class has + # left; expired in the same commit as the binding they no longer fit. + # And the sign-in links minted under the old binding go with it, or a + # form drawn for one diary sends its password to the other (#137). + await diary_service.expire_off_binding(session, school_class) + await diary_link.drop_for_class(session, school_class.id) + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", + "привязан дневник Санкт-Петербурга", + ) + await session.commit() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Привязан дневник Санкт-Петербурга") + return + if callback_data.value == NETSCHOOL: + await callback.message.edit_text( + "🌆 <b>Сетевой город</b>\n\nВыберите регион.", reply_markup=diary_region_menu() + ) + await callback.answer() + return + await callback.answer("Неизвестный дневник", show_alert=True) + + +@router.callback_query(ManageAction.filter(F.action == "diary_reg")) +async def class_diary_region( + callback: CallbackQuery, + callback_data: ManageAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, + state: FSMContext, +) -> None: + """Third step: the «Сетевой город» region was picked. Check the region + accepts a password from us before asking for the school, so the admin + learns once rather than every family finding out at sign-in.""" + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await callback.answer("Только для администраторов", show_alert=True) + return + region = ns_regions.get(callback_data.value) + if region is None or not region.password: + await callback.answer("Этот регион недоступен", show_alert=True) + return + ok, why = await _probe_region(region) + if not ok: + await callback.answer(why, show_alert=True) + return + await state.set_state(BindDiary.school) + await state.update_data(diary_region=region.key, diary_class_id=school_class.id) + await callback.message.edit_text( + f"🌆 <b>Сетевой город</b> · {escape(region.title)}\n\n" + "Напишите часть названия школы — я поищу её на сайте региона.", + ) + await callback.answer() + + +async def _probe_region(region) -> tuple[bool, str]: # noqa: ANN001 + """Ask the region's sign-in options, so a class is not bound to a diary no + family can reach. @return (ok, message-if-not).""" + try: + await NetSchoolClient(region).login_allowed() + except SignInUnsupported: + return False, "Этот регион пускает только через Госуслуги — привязать нельзя." + except AddressRefused: + return False, "Сайт региона не отвечает нашему серверу. Сообщите владельцу проекта." + except DiaryError: + return False, "Сайт региона сейчас недоступен. Попробуйте позже." + return True, "" + + +@router.message(BindDiary.school) +async def class_diary_search( + message: Message, + session: AsyncSession, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Fourth step: a school-name query. Show what the region's search found. + + FSM state is per-user and attacker-controlled, so the role is re-checked + here as at every step — a non-admin who set itself into this state would + otherwise turn the class card into an outbound search against a region + server. + """ + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + data = await state.get_data() + region = ns_regions.get(data.get("diary_region")) + class_id = data.get("diary_class_id") + if region is None or class_id is None: + await state.clear() + return + query = (message.text or "").strip() + if len(query) < 2: + await message.answer("Введите хотя бы два символа названия школы.") + return + try: + schools = await NetSchoolClient(region).schools_search(query) + except DiaryError: + await message.answer("Не удалось найти школы — сайт региона не ответил. Попробуйте позже.") + return + if not schools: + await message.answer("Школа не найдена. Уточните запрос.") + return + shown = schools[:DIARY_SCHOOLS_MAX] + await state.update_data(diary_schools=shown) + caption = f"🌆 <b>Сетевой город</b> · {escape(region.title)}\n\nВыберите школу:" + more = len(schools) > len(shown) + if more: + caption += f"\n\nПоказаны первые {len(shown)} — уточните запрос, если нужной нет." + await message.answer(caption, reply_markup=diary_school_menu(shown, more=more)) + + +@router.callback_query(DiarySchoolPick.filter(F.action == "cancel")) +async def class_diary_cancel( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, + state: FSMContext, +) -> None: + # A role check like every other step: the callback payload is whatever the + # client sent, and this one redraws the (admin-only) class card, so a + # наблюдатель who pressed it would otherwise be shown it. + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await state.clear() + await callback.answer("Только для администраторов", show_alert=True) + return + await state.clear() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Отменено") + + +@router.callback_query(DiarySchoolPick.filter(F.action == "pick")) +async def class_diary_school( + callback: CallbackQuery, + callback_data: DiarySchoolPick, + session: AsyncSession, + role: Role | None, + state: FSMContext, +) -> None: + """Last step: a school was picked. Bind the class to it.""" + data = await state.get_data() + schools = data.get("diary_schools") or [] + region = ns_regions.get(data.get("diary_region")) + class_id = data.get("diary_class_id") + index = callback_data.value + if region is None or class_id is None or not (0 <= index < len(schools)): + await state.clear() + await callback.answer("Список устарел — начните заново.", show_alert=True) + return + school_class = await session.get(SchoolClass, class_id) + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await state.clear() + await callback.answer("Только для администраторов", show_alert=True) + return + school = schools[index] + school_class.diary_provider = NETSCHOOL + school_class.diary_region = region.key + school_class.diary_school_id = int(school["id"]) + school_class.diary_school_name = str(school["name"])[:300] + # Sessions on another region's server, or Petersburg's, read a diary the + # class has left: expired with the binding, so the keep-alive stops + # pinging a server nobody here uses. The same region keeps them. The + # sign-in links go whatever the region: each names one school (#137). + await diary_service.expire_off_binding(session, school_class) + await diary_link.drop_for_class(session, school_class.id) + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", + f"привязан «Сетевой город»: {region.title}, {str(school['name'])[:200]}", + ) + await session.commit() + await state.clear() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Дневник привязан") + + +async def _redraw_class( + callback: CallbackQuery, session: AsyncSession, school_class: SchoolClass, role: Role +) -> None: + text, keyboard = await _class_card(session, school_class, role, callback.from_user.id) + await callback.message.edit_text(text, reply_markup=keyboard) diff --git a/server/app/bot/handlers/manage/holidays.py b/server/app/bot/handlers/manage/holidays.py new file mode 100644 index 00000000..7fea1eb9 --- /dev/null +++ b/server/app/bot/handlers/manage/holidays.py @@ -0,0 +1,604 @@ +"""«🏖 Особые дни»: holidays, shortened, remote and other marked days. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import timedelta +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.calendar import open_month +from app.bot.handlers.manage._common import ( + _allowed, + _date_or_none, + _day_kind_or_none, + _int_or_none, + _parse_day, + _refusal, + _today, +) +from app.bot.keyboards import back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import ( + PERIOD_KINDS, + DayKindAction, + bells_pick_keyboard, + day_kind_keyboard, + holiday_list_keyboard, + period_kind_keyboard, +) +from app.bot.manage_states import AddHoliday +from app.models import BellPeriod, BellSchedule, DayKind, DayOverride, Role, SchoolClass +from app.services import audit + +router = Router(name="manage.holidays") + +#: Days a «📆 Период» may cover in one go. A school year is longer than this, +#: but a period typed by hand is a holiday, and a typo in the year would +#: otherwise write thousands of rows before anybody noticed. +PERIOD_MAX_DAYS = 120 + +NOTE_MAX = 300 + + +# -------------------------------------------------------------------------- +# 🏖 Special days +# -------------------------------------------------------------------------- +# +# A DayOverride is how the class says "this date is not a normal school day". +# «Обычный день» is the absence of a row, not a kind of row, so choosing it +# deletes the override instead of storing DayKind.NORMAL — otherwise the +# resolver would have two ways to spell the same thing. + +_KIND_BY_TAG = { + "holiday": DayKind.HOLIDAY, + "shortened": DayKind.SHORTENED, + "remote": DayKind.REMOTE, + "self_study": DayKind.SELF_STUDY, + "day_off": DayKind.DAY_OFF, +} + +#: The kind said in the middle of a sentence, for the audit line and the +#: confirmation. Read by **subscript**, not `.get`, and deliberately: a kind +#: with no entry here is a `KeyError` out of a callback handler, which never +#: reaches `callback.answer()` and leaves the button spinning until Telegram +#: gives up. `test_every_day_kind_can_be_said` keeps the table complete so the +#: subscript stays safe, rather than papering over a gap with a default that +#: would print «День» at somebody who chose «самоподготовка». +_KIND_SUMMARY = { + DayKind.HOLIDAY: "каникулы / выходной", + DayKind.SHORTENED: "сокращённые уроки", + DayKind.REMOTE: "дистанционно", + DayKind.SELF_STUDY: "самоподготовка", + DayKind.DAY_OFF: "отгул", +} + +HOLIDAY_DATE_HELP = ( + "Выберите день или пришлите дату: <code>12.09</code> или <code>12.09.2026</code>." +) + + +async def _holiday_view( + session: AsyncSession, + school_class: SchoolClass, + role: Role, + only: DayKind | None = None, +): + """The list of marked days, optionally narrowed to one kind. + + The filter lives in the callback payload rather than in FSM state, which is + the rule the editor's pager already follows: a card on a screen is a card + somebody may come back to in an hour, and a filter held in state would + either have expired by then or be silently applied to a different screen. + Carried in the payload, the card *is* its own filter. + """ + today = _today(school_class) + query = ( + select(DayOverride) + .where(DayOverride.class_id == school_class.id, DayOverride.date >= today) + .order_by(DayOverride.date) + ) + if only is not None: + query = query.where(DayOverride.kind == only) + overrides = list(await session.scalars(query)) + schedules = { + schedule.id: schedule.name + for schedule in await session.scalars( + select(BellSchedule).where(BellSchedule.class_id == school_class.id) + ) + } + return mr.render_holidays(overrides, schedules, today, only), holiday_list_keyboard( + overrides, + only=only, + can_edit=role.at_least(Role.EDITOR), + can_period=role.at_least(Role.ADMIN), + ) + + +async def _override_for( + session: AsyncSession, class_id: int, day: Date +) -> DayOverride | None: + return await session.scalar( + select(DayOverride).where(DayOverride.class_id == class_id, DayOverride.date == day) + ) + + +async def _upsert_override( + session: AsyncSession, school_class: SchoolClass, day: Date, kind: DayKind +) -> DayOverride: + override = await _override_for(session, school_class.id, day) + if override is None: + override = DayOverride(class_id=school_class.id, date=day, kind=kind) + session.add(override) + override.kind = kind + if kind is not DayKind.SHORTENED: + # A bell schedule only means anything on a shortened day; leaving a + # stale one on a holiday would surface in the day view as a + # schedule nobody chose. + override.bell_schedule_id = None + elif override.bell_schedule_id is None: + # Never null on a shortened day. The picker opens next and is where + # the real answer comes from, but the row is committed before it is + # asked — so walking away used to leave «⏱ Сокращённые уроки» over a + # day that names no schedule, which `api/edit.day_put` refuses with a + # 422 and the resolver silently draws as a normal day. The class + # default is the honest starting value: it is what the day would ring + # anyway, and now it says so on the card. + override.bell_schedule_id = school_class.bell_schedule_id + return override + + +@router.message(Command("holidays")) +async def cmd_holidays( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await message.answer(_refusal(role, Role.EDITOR)) + return + await state.clear() + text, keyboard = await _holiday_view(session, school_class, role) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(DayKindAction.filter(F.action == "list")) +async def holidays_list( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + await state.clear() + # An unreadable filter narrows to nothing rather than raising: the value is + # whatever the client sent, and `DayKind(raw)` out of a callback handler + # never reaches `callback.answer()`. + only = _day_kind_or_none(callback_data.value) if callback_data.value else None + text, keyboard = await _holiday_view(session, school_class, role, only) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +@router.callback_query(DayKindAction.filter(F.action == "add")) +async def holiday_add( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + await state.set_state(AddHoliday.date) + await callback.message.edit_text( + f"🏖 <b>Особый день</b>\n\n{HOLIDAY_DATE_HELP}", + reply_markup=open_month("dk", _today(school_class)), + ) + await callback.answer() + + +async def _ask_kind(editable, day: Date) -> None: + await editable.edit_text( + f"<b>{day:%d.%m.%Y}</b>\n\nЧто это за день?", + reply_markup=day_kind_keyboard(day.isoformat()), + ) + + +@router.callback_query(DayKindAction.filter(F.action == "pick_date")) +async def holiday_pick_date( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + day = _date_or_none(callback_data.value) + if day is None: + await callback.answer("Непонятная дата", show_alert=True) + return + + # From here the date travels in the callback payload, so the flow no longer + # depends on a state the user could have set for something else. + await state.clear() + await _ask_kind(callback.message, day) + await callback.answer() + + +@router.message(AddHoliday.date) +async def holiday_typed_date( + message: Message, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await state.clear() + return + + day = _parse_day(message.text or "", _today(school_class)) + if day is None: + await message.answer(f"Не понял дату. {HOLIDAY_DATE_HELP}") + return + + await state.clear() + await message.answer( + f"<b>{day:%d.%m.%Y}</b>\n\nЧто это за день?", + reply_markup=day_kind_keyboard(day.isoformat()), + ) + + +@router.callback_query(DayKindAction.filter(F.action == "kind")) +async def holiday_kind( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + raw_date, _, tag = callback_data.value.partition(":") + day = _date_or_none(raw_date) + if day is None: + await callback.answer("Непонятная дата", show_alert=True) + return + + if tag == "normal": + override = await _override_for(session, school_class.id, day) + if override is not None: + await session.delete(override) + await audit.record( + session, school_class.id, callback.from_user.id, "dayoverride.delete", + f"{day:%d.%m}: снова обычный день", + ) + await session.commit() + await state.clear() + text, keyboard = await _holiday_view(session, school_class, role) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer("Обычный день") + return + + kind = _KIND_BY_TAG.get(tag) + if kind is None: + await callback.answer("Неизвестный тип дня", show_alert=True) + return + + await _upsert_override(session, school_class, day, kind) + await audit.record( + session, school_class.id, callback.from_user.id, "dayoverride.set", + f"{day:%d.%m}: {_KIND_SUMMARY[kind]}", + ) + await session.commit() + + if kind is DayKind.SHORTENED: + schedules = list( + await session.scalars( + select(BellSchedule) + .where(BellSchedule.class_id == school_class.id) + .order_by(BellSchedule.id) + ) + ) + await state.clear() + await callback.message.edit_text( + f"<b>{day:%d.%m}</b> — сокращённые уроки.\n\nПо какому расписанию звонков?", + reply_markup=bells_pick_keyboard(schedules, day.isoformat()), + ) + await callback.answer() + return + + await _ask_note(callback.message, state, day, kind) + await callback.answer() + + +async def _ask_note(editable, state: FSMContext, day: Date, kind: DayKind) -> None: + await state.set_state(AddHoliday.note) + await state.update_data(date=day.isoformat()) + await editable.edit_text( + f"✅ <b>{day:%d.%m}</b> — {_KIND_SUMMARY[kind]}.\n\n" + "Пришлите заметку (например, «осенние каникулы») или <code>-</code>, " + "чтобы оставить без неё.", + reply_markup=cancel_keyboard(), + ) + + +@router.callback_query(DayKindAction.filter(F.action == "bells")) +async def holiday_bells( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + raw_date, _, raw_id = callback_data.value.partition(":") + day = _date_or_none(raw_date) + if day is None: + await callback.answer("Непонятная дата", show_alert=True) + return + + override = await _override_for(session, school_class.id, day) + if override is None: + await callback.answer("День уже не отмечен", show_alert=True) + return + + schedule_id = _int_or_none(raw_id) + if schedule_id: + schedule = await session.scalar( + select(BellSchedule).where( + BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id + ) + ) + if schedule is None: + await callback.answer("Расписание звонков не найдено", show_alert=True) + return + # A schedule with no rows is legitimate — «🔔 Звонки» creates it empty + # and the times are typed in afterwards — but a day pointed at one + # draws no lessons at all, because the resolver takes a lesson's times + # from the bell row of its own number. The card would say «⏱ Сокращённые + # уроки» over an empty day on every phone, in the widget and in the + # calendar feed, and nothing would be logged. `api/edit.day_put` refuses + # the same thing for the same reason. + rings = await session.scalar( + select(BellPeriod.id).where(BellPeriod.schedule_id == schedule.id).limit(1) + ) + if rings is None: + await callback.answer( + f"В «{schedule.name}» ещё нет ни одного урока — " + "заполните звонки, иначе день будет пустым.", + show_alert=True, + ) + return + override.bell_schedule_id = schedule.id + summary = f"{day:%d.%m}: звонки «{schedule.name}»" + else: + # The keyboard no longer draws this button; a card left open from + # before it was removed still can. + await callback.answer( + "У сокращённого дня должно быть своё расписание звонков — " + "выберите его в списке.", + show_alert=True, + ) + return + + await audit.record( + session, school_class.id, callback.from_user.id, "dayoverride.bells", summary + ) + await session.commit() + await _ask_note(callback.message, state, day, DayKind.SHORTENED) + await callback.answer() + + +@router.message(AddHoliday.note) +async def holiday_note( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await state.clear() + return + + data = await state.get_data() + day = _date_or_none(str(data.get("date", ""))) + if day is None: + await state.clear() + await message.answer("Начните заново: /holidays", reply_markup=back_to_menu()) + return + + override = await _override_for(session, school_class.id, day) + if override is None: + await state.clear() + await message.answer("День уже не отмечен.", reply_markup=back_to_menu()) + return + + raw = " ".join((message.text or "").split()) + if raw not in {"-", "—", ""}: + override.note = raw[:NOTE_MAX] + await audit.record( + session, school_class.id, message.from_user.id, "dayoverride.note", + f"{day:%d.%m}: заметка «{override.note}»", + ) + await session.commit() + + await state.clear() + text, keyboard = await _holiday_view(session, school_class, role) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(DayKindAction.filter(F.action == "delete")) +async def holiday_delete( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + day = _date_or_none(callback_data.value) + if day is None: + await callback.answer("Непонятная дата", show_alert=True) + return + + override = await _override_for(session, school_class.id, day) + if override is not None: + await session.delete(override) + await audit.record( + session, school_class.id, callback.from_user.id, "dayoverride.delete", + f"{day:%d.%m}: отметка снята", + ) + await session.commit() + + await state.clear() + text, keyboard = await _holiday_view(session, school_class, role) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer("Снято" if override is not None else "Уже снято") + + +@router.callback_query(DayKindAction.filter(F.action == "period")) +async def holiday_period_start( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """A whole range of holiday days is admin-only: it rewrites weeks of the + class's calendar from one message.""" + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + # Which kind first, dates second. The flow used to mark holidays and + # nothing else, so «самоподготовка с 12 по 16» meant marking five days one + # at a time — and a week of remote teaching, which is the shape this is + # actually needed in, meant five presses and five typos to make. + await state.clear() + await callback.message.edit_text( + "📆 <b>Отметить период</b>\n\n" + "Чем отметить каждый день внутри периода?", + reply_markup=period_kind_keyboard(), + ) + await callback.answer() + + +@router.callback_query(DayKindAction.filter(F.action == "period_kind")) +async def holiday_period_kind( + callback: CallbackQuery, + callback_data: DayKindAction, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """The kind is picked, now the dates. Re-checked here, not trusted from the + press that got this far: a card can sit on a screen after a role changes.""" + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + kind = _day_kind_or_none(callback_data.value) + if kind is None or kind not in {chosen for chosen, _ in PERIOD_KINDS}: + # Not an exception. Callback data is whatever the client sent, and a + # bare conversion on it leaves the button spinning until Telegram + # gives up — see the guards in this module's siblings. + await callback.answer("Не знаю такого вида дня.", show_alert=True) + return + + label = next(text for chosen, text in PERIOD_KINDS if chosen is kind) + await state.set_state(AddHoliday.period) + await state.update_data(period_kind=kind.value) + await callback.message.edit_text( + f"📆 <b>{escape(label)}</b>\n\n" + "Пришлите период: <code>26.10-05.11</code>.\n" + f"Каждый день внутри будет отмечен так, не больше " + f"{PERIOD_MAX_DAYS} дней за раз.", + reply_markup=cancel_keyboard(), + ) + await callback.answer() + + +@router.message(AddHoliday.period) +async def holiday_period_apply( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + today = _today(school_class) + raw = (message.text or "").replace("—", "-").replace("–", "-") + parts = [part for part in raw.split("-") if part.strip()] + first = _parse_day(parts[0], today) if len(parts) >= 2 else None + last = _parse_day(parts[1], today) if len(parts) >= 2 else None + if first is None or last is None or last < first: + await message.answer( + "Не понял период. Формат: <code>26.10-05.11</code>, начало раньше конца." + ) + return + + span = (last - first).days + 1 + if span > PERIOD_MAX_DAYS: + await message.answer( + f"Это {span} дней — слишком много за один раз. " + f"Максимум {PERIOD_MAX_DAYS}; разбейте период на части." + ) + return + + # Read from the state the picker wrote, and defaulted rather than refused: + # a form that outlives a restart still has a date to apply, and holidays + # are what this flow did before there was anything to pick. + data = await state.get_data() + kind = _day_kind_or_none(str(data.get("period_kind", ""))) or DayKind.HOLIDAY + + for offset in range(span): + await _upsert_override(session, school_class, first + timedelta(days=offset), kind) + await audit.record( + session, + school_class.id, + message.from_user.id, + "dayoverride.period", + f"{kind.value}: {first:%d.%m}–{last:%d.%m}, дней: {span}", + ) + await session.commit() + await state.clear() + + await message.answer(mr.render_period_result(first, last, span, kind)) + text, keyboard = await _holiday_view(session, school_class, role) + await message.answer(text, reply_markup=keyboard) diff --git a/server/app/bot/handlers/manage/import_export.py b/server/app/bot/handlers/manage/import_export.py new file mode 100644 index 00000000..69513241 --- /dev/null +++ b/server/app/bot/handlers/manage/import_export.py @@ -0,0 +1,241 @@ +"""«📤 Экспорт» and «📥 Импорт»: the weekly template as text, both ways. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import _allowed, _refusal +from app.bot.keyboards import WEEKDAY_FULL, back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import ImportAction, import_keyboard +from app.bot.manage_states import ImportTimetable +from app.models import BellPeriod, BellSchedule, Role, SchoolClass, TimetableEntry +from app.services import audit, structure, timetable_io + +router = Router(name="manage.import_export") + + +# -------------------------------------------------------------------------- +# 📤 Export and 📥 import of the timetable +# -------------------------------------------------------------------------- + + +# There is deliberately no `_export_parts` here any more. +# +# It re-split the export on the *escaped* length, on the reasoning that «every +# «&» costs four more characters and every «<» or «>» three». That reasoning is +# wrong, and the Bot API says so in one line: `sendMessage`'s `text` is +# «1-4096 characters **after entities parsing**». Telegram counts what it +# parses — `<code>` costs nothing and `&` counts as the one «&» it becomes +# — so an export could not overflow by being escaped, and the thing this +# defended against could not happen. +# +# What it did instead was real. Shrinking the limit by the expansion factor +# turned 200 lines of apostrophes from 6 messages into 34, and 34 consecutive +# `answer` calls into one chat is the per-chat flood limit: `TelegramRetryAfter` +# raised out of a `Message` handler, which has no callback to apologise on, so +# the export stopped partway with nothing said — the exact failure it was +# written to remove, moved to a different trigger. +# +# `split_text` at `CHUNK_LIMIT` is what the export uses, as it did before. + + +@router.message(Command("export")) +async def cmd_export( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """The whole template as text — which doubles as the backup. + + It is sent in ``<code>`` blocks so Telegram offers a copy button, split at + 4000 characters because the limit is 4096 and the header counts. + """ + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.clear() + + entries = list( + await session.scalars( + select(TimetableEntry) + .where(TimetableEntry.class_id == school_class.id) + .order_by(TimetableEntry.weekday, TimetableEntry.index) + ) + ) + periods: list[BellPeriod] = [] + if school_class.bell_schedule_id: + schedule = await session.get(BellSchedule, school_class.bell_schedule_id) + if schedule is not None: + periods = list(schedule.periods) + + body = timetable_io.export_timetable(entries, periods) + if not body: + await message.answer("Расписание пустое — экспортировать нечего.") + return + + parts = mr.split_text(body) + for number, part in enumerate(parts, start=1): + header = f"📤 Экспорт, часть {number}/{len(parts)}\n" if len(parts) > 1 else "" + await message.answer(f"{header}<code>{escape(part)}</code>") + + +IMPORT_HELP = ( + "Пришлите расписание одним сообщением, с заголовком перед каждым днём:\n\n" + "<code>== Понедельник ==\n" + "1. Алгебра, 214\n" + "2. Физика, 305, Иванова И.И.\n" + "3. История [чис]\n" + "3. Обществознание [знам]\n\n" + "== Вторник ==\n" + "1. Химия, 118</code>\n\n" + "Подойдёт и текст из /export — можно раз в четверть сохранять его себе " + "и возвращать обратно.\n" + "Блок <code>== Звонки ==</code> обновит основное расписание звонков." +) + + +@router.message(Command("import")) +async def cmd_import( + message: Message, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await message.answer(_refusal(role, Role.ADMIN)) + return + await state.set_state(ImportTimetable.paste) + await message.answer(f"📥 <b>Импорт расписания</b>\n\n{IMPORT_HELP}") + + +@router.message(ImportTimetable.paste) +async def import_preview( + message: Message, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Parse and show what would happen; nothing is written yet. + + The paste is kept in FSM storage rather than parsed twice into a process + variable: «Применить» may well arrive at a different instance. + """ + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + raw = message.text or "" + days, rejected = timetable_io.parse_timetable_block(raw) + bells, _ = timetable_io.parse_bells_block(raw) + if not days and not bells: + await message.answer( + "Не нашёл ни одного дня.\n\n" + IMPORT_HELP, reply_markup=cancel_keyboard() + ) + return + + await state.update_data(raw=raw) + preview = mr.render_import_preview(days, rejected, len(bells)) + await message.answer(preview, reply_markup=import_keyboard()) + + +@router.callback_query(ImportAction.filter(F.action == "cancel")) +async def import_cancel( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.clear() + await callback.message.edit_text("Импорт отменён — ничего не изменилось.") + await callback.answer() + + +@router.callback_query(ImportAction.filter(F.action == "apply")) +async def import_apply( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Replace exactly the weekdays the paste named, in one transaction. + + Days the paste did not mention are left alone, so importing a single day's + block is a legitimate thing to do. A day that appears with no lessons under + it is emptied — that is how a paste says «в четверг уроков нет». + """ + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + data = await state.get_data() + raw = str(data.get("raw", "")) + days, _ = timetable_io.parse_timetable_block(raw) + bells, _ = timetable_io.parse_bells_block(raw) + if not days and not bells: + await state.clear() + await callback.answer("Нечего применять — начните заново: /import", show_alert=True) + return + + result = await structure.apply_timetable(session, school_class, days, bells) + total = result.written + schedule = result.schedule + unrung = result.unrung + + summary = f"импорт расписания: дней {len(days)}, уроков {total}" + if bells: + summary += f", звонков {len(bells)}" + if result.dropped: + # Rows, not numbers. «8. Алгебра» under Monday and under Tuesday is two + # lessons nobody will see, and this line is the only record of them. + summary += f", без звонка пропущено {len(result.dropped)}" + await audit.record( + session, school_class.id, callback.from_user.id, "timetable.import", summary + ) + await session.commit() + if schedule is not None: + await session.refresh(schedule, ["periods"]) + await state.clear() + + lines = [f"✅ Импорт применён: {len(days)} дн., уроков — {total}."] + # What was written, not what was parsed. A lesson past the last bell is + # dropped by ``apply_timetable``, so printing the parsed count put «уроков + # — 7» directly above «Вторник: 9» — the card contradicting itself on two + # consecutive lines. The service says which rows it dropped, by weekday, so + # this counts them rather than re-deciding the rule a second time here. + dropped_per_day: dict[int, int] = {} + for weekday, _index in result.dropped: + dropped_per_day[weekday] = dropped_per_day.get(weekday, 0) + 1 + for weekday in sorted(days): + written = len(days[weekday]) - dropped_per_day.get(weekday, 0) + lines.append(f"• {WEEKDAY_FULL[weekday - 1]}: {written}") + if bells: + lines.append(f"• Звонки: {len(bells)}") + if unrung: + # Said out loud rather than left in the difference between two numbers: + # such a lesson is stored nowhere and drawn nowhere, and an admin who + # is not told simply believes the paste worked. + numbers = ", ".join(str(index) for index in unrung) + lines.append( + f"\n⚠️ Не добавлены уроки № {numbers}: в расписании звонков нет " + "таких номеров. Добавьте звонки в «🔔 Звонки» и вставьте день заново." + ) + await callback.message.edit_text("\n".join(lines), reply_markup=back_to_menu()) + await callback.answer("Готово") diff --git a/server/app/bot/handlers/manage/requests.py b/server/app/bot/handlers/manage/requests.py new file mode 100644 index 00000000..0906978c --- /dev/null +++ b/server/app/bot/handlers/manage/requests.py @@ -0,0 +1,342 @@ +"""«📱 /link» and «🙋 /request»: what a member does for themselves, and the admins' answer. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +import logging +from datetime import UTC, datetime +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command, CommandObject +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _bot_of, _int_or_none, _refusal +from app.bot.keyboards import back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import RequestAction, request_keyboard +from app.bot.manage_states import RequestAccess +from app.models import AccessRequest, BotUser, Role, SchoolClass +from app.services import access as access_service +from app.services import audit, linking + +log = logging.getLogger(__name__) + +router = Router(name="manage.requests") + + +# -------------------------------------------------------------------------- +# 📱 /link and 🙋 /request +# -------------------------------------------------------------------------- + + +@router.message(Command("link")) +async def cmd_link( + message: Message, + command: CommandObject, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Attach the phone showing ``code`` to this account. + + No role check beyond membership: linking gives the phone *this* account's + role, whatever it is, so it can never be more than the person already has. + """ + if not _allowed(school_class, role, Role.VIEWER): + await message.answer(NO_ACCESS) + return + + code = (command.args or "").strip() + if not 1 <= len(code) <= 16: + await message.answer( + "📱 <b>Привязка телефона</b>\n\n" + "Откройте в приложении экран привязки и пришлите код: " + "<code>/link ABC123</code>." + ) + return + + device = await linking.link_device(session, code, message.from_user.id) + if device is None: + await message.answer( + "Код не подошёл. Он действует один раз — откройте экран привязки " + "в приложении ещё раз и пришлите новый." + ) + return + + device_role = await linking.effective_role(session, device) + name = escape(device.device_name or "Телефон") + if device_role is not None and device_role.at_least(Role.EDITOR): + tail = f"Ваша роль: <b>{device_role.title_ru}</b> — приложение может редактировать." + else: + title = device_role.title_ru if device_role is not None else "нет роли" + tail = ( + f"Ваша роль: <b>{title}</b> — только чтение. " + "Запросить доступ редактора: /request" + ) + await audit.record( + session, + device.class_id, + message.from_user.id, + "device.link", + f"привязано устройство «{device.device_name or device.id}»", + ) + await session.commit() + await message.answer(f"📱 Устройство «{name}» привязано. {tail}") + + +async def _create_request( + session: AsyncSession, school_class: SchoolClass, telegram_id: int, text: str | None +) -> AccessRequest: + """One open request per person per class — a second one replaces the first, + so a nervous requester cannot fill an admin's screen.""" + existing = await session.scalar( + select(AccessRequest).where( + AccessRequest.class_id == school_class.id, + AccessRequest.telegram_id == telegram_id, + AccessRequest.status == "pending", + ) + ) + if existing is None: + existing = AccessRequest( + class_id=school_class.id, + telegram_id=telegram_id, + requested_role=Role.EDITOR, + status="pending", + ) + session.add(existing) + existing.requested_role = Role.EDITOR + existing.status = "pending" + existing.message = (text or None) and text[:300] + existing.decided_by = None + existing.decided_at = None + await session.flush() + return existing + + +async def _notify_admins( + session: AsyncSession, + bot, + school_class: SchoolClass, + request: AccessRequest, + who: str, +) -> None: + """Tell every admin, and let one bad recipient be nobody else's problem.""" + if bot is None: + return + + admins = await session.scalars( + select(BotUser).where( + BotUser.class_id == school_class.id, + BotUser.role.in_([Role.ADMIN, Role.OWNER]), + ) + ) + body = ( + f"🙋 <b>Запрос доступа</b>\n\n" + f"{who} просит роль <b>{Role.EDITOR.title_ru}</b> " + f"в классе <b>{escape(school_class.name)}</b>." + ) + if request.message: + body += f"\n\n<i>{escape(request.message)}</i>" + + for admin in admins: + try: + await bot.send_message( + admin.telegram_id, body, reply_markup=request_keyboard(request.id) + ) + except Exception: # noqa: BLE001 - one blocked admin is not the requester's problem + log.warning("could not notify admin %s", admin.telegram_id, exc_info=True) + + +@router.message(Command("request")) +async def cmd_request( + message: Message, + command: CommandObject, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.VIEWER): + await message.answer(NO_ACCESS) + return + if role.at_least(Role.EDITOR): + await message.answer( + f"У вас уже роль <b>{role.title_ru}</b> — запрашивать нечего." + ) + return + + text = (command.args or "").strip() + if not text: + await state.set_state(RequestAccess.message) + await message.answer( + "🙋 <b>Запрос доступа редактора</b>\n\n" + "Напишите пару слов о себе — администратор увидит их вместе с запросом. " + "Или пришлите <code>-</code>, чтобы отправить без комментария.", + reply_markup=cancel_keyboard(), + ) + return + + await _submit_request(message, state, session, school_class, text) + + +@router.message(RequestAccess.message) +async def request_message( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.VIEWER) or role.at_least(Role.EDITOR): + await state.clear() + return + raw = " ".join((message.text or "").split()) + await _submit_request( + message, state, session, school_class, None if raw in {"-", "—", ""} else raw + ) + + +async def _submit_request( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass, + text: str | None, +) -> None: + request = await _create_request(session, school_class, message.from_user.id, text) + who = mr.person(message.from_user.full_name, message.from_user.username, message.from_user.id) + await audit.record( + session, + school_class.id, + message.from_user.id, + "access.request", + f"{message.from_user.full_name or message.from_user.id} просит роль редактора", + ) + await session.commit() + await state.clear() + + await _notify_admins(session, _bot_of(message), school_class, request, who) + await message.answer( + "✅ Запрос отправлен администраторам класса. Они ответят здесь же." + ) + + +async def _tell_requester(bot, telegram_id: int, text: str) -> None: + if bot is None: + return + try: + await bot.send_message(telegram_id, text) + except Exception: # noqa: BLE001 - the decision stands whether or not it was delivered + log.warning("could not tell %s about the decision", telegram_id, exc_info=True) + + +async def _request_by_id( + session: AsyncSession, school_class: SchoolClass, raw: str +) -> AccessRequest | None: + request_id = _int_or_none(raw) + if request_id is None: + return None + return await session.scalar( + select(AccessRequest).where( + AccessRequest.id == request_id, + AccessRequest.class_id == school_class.id, + AccessRequest.status == "pending", + ) + ) + + +@router.callback_query(RequestAction.filter(F.action == "approve")) +async def request_approve( + callback: CallbackQuery, + callback_data: RequestAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Grant the requested role through the same rules as «👥 Доступ». + + Literally the same rules: `services/access.approve_request` is also what + `PATCH /api/v1/manage/requests/{id}/approve` calls, so a phone and this + button cannot come to different answers. The refusal it raises carries the + Russian sentence this alert shows. + """ + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + request = await _request_by_id(session, school_class, callback_data.value) + if request is None: + await callback.answer("Запрос уже закрыт", show_alert=True) + return + + target_role = request.requested_role + try: + member = await access_service.approve_request( + session, + school_class, + request, + actor_id=callback.from_user.id, + actor_role=role, + role=target_role, + ) + except access_service.GrantRefused as refused: + await callback.answer(str(refused), show_alert=True) + return + + name = mr.person(member.full_name, member.username, member.telegram_id) + await session.commit() + + await _tell_requester( + _bot_of(callback), + request.telegram_id, + access_service.approval_notice(school_class, target_role), + ) + await callback.message.edit_text( + f"✅ {name} — теперь <b>{target_role.title_ru}</b>.", reply_markup=back_to_menu() + ) + await callback.answer("Выдано") + + +@router.callback_query(RequestAction.filter(F.action == "decline")) +async def request_decline( + callback: CallbackQuery, + callback_data: RequestAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + request = await _request_by_id(session, school_class, callback_data.value) + if request is None: + await callback.answer("Запрос уже закрыт", show_alert=True) + return + + request.status = "declined" + request.decided_by = callback.from_user.id + request.decided_at = datetime.now(UTC).replace(tzinfo=None) + await audit.record( + session, + school_class.id, + callback.from_user.id, + "access.decline", + f"отклонён запрос доступа от {request.telegram_id}", + ) + await session.commit() + + await _tell_requester( + _bot_of(callback), + request.telegram_id, + f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", + ) + await callback.message.edit_text("✖️ Запрос отклонён.", reply_markup=back_to_menu()) + await callback.answer("Отклонено") diff --git a/server/app/bot/handlers/manage/stats.py b/server/app/bot/handlers/manage/stats.py new file mode 100644 index 00000000..1dd3691d --- /dev/null +++ b/server/app/bot/handlers/manage/stats.py @@ -0,0 +1,101 @@ +"""«📊 Статистика» and «🔎 Поиск»: the class's numbers and a homework search. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from datetime import timedelta + +from aiogram import Router +from aiogram.filters import Command, CommandObject +from aiogram.fsm.context import FSMContext +from aiogram.types import Message +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _refusal, _today +from app.bot.keyboards import back_to_menu +from app.models import Homework, Role, SchoolClass +from app.services import stats as stats_service + +router = Router(name="manage.stats") + +#: Homework rows one search may answer with. +SEARCH_MAX = 15 + +#: How far back a search looks. Older homework is history nobody is looking +#: for, and including it makes every search slower and noisier. +SEARCH_BACK_DAYS = 30 + + +# -------------------------------------------------------------------------- +# 📊 Statistics and 🔎 search +# -------------------------------------------------------------------------- + + +@router.message(Command("stats")) +async def cmd_stats( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await message.answer(_refusal(role, Role.EDITOR)) + return + await state.clear() + numbers = await stats_service.class_stats(session, school_class) + await message.answer( + stats_service.render_stats(numbers, school_class), reply_markup=back_to_menu() + ) + + +@router.message(Command("find")) +async def cmd_find( + message: Message, + command: CommandObject, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Search this class's homework. Any member may: it is the same text the + day view already shows them, only reachable by memory instead of by date.""" + if not _allowed(school_class, role, Role.VIEWER): + await message.answer(NO_ACCESS) + return + + needle = (command.args or "").strip() + if len(needle) < 2: + await message.answer( + "🔎 <b>Поиск по домашним заданиям</b>\n\n" + "Напишите, что искать: <code>/find параграф 12</code>.\n" + "Ищу по тексту задания и по названию предмета, " + "минимум два символа." + ) + return + + today = _today(school_class) + # ``lower().contains()`` rather than ILIKE, which SQLite does not have. + # Both dialects fold Cyrillic: Postgres does it natively, and ``app.db`` + # replaces SQLite's ASCII-only ``lower()`` with Python's on every + # connection, so the search behaves the same for the developer and for the + # class. + pattern = needle.lower() + rows = list( + await session.scalars( + select(Homework) + .where( + Homework.class_id == school_class.id, + Homework.due_date >= today - timedelta(days=SEARCH_BACK_DAYS), + func.lower(Homework.text).contains(pattern) + | func.lower(Homework.subject_name).contains(pattern), + ) + .order_by(Homework.due_date.desc(), Homework.id.desc()) + .limit(SEARCH_MAX) + ) + ) + await message.answer(mr.render_search(needle, rows, today), reply_markup=back_to_menu()) diff --git a/server/app/bot/handlers/manage/subjects.py b/server/app/bot/handlers/manage/subjects.py new file mode 100644 index 00000000..a87b618d --- /dev/null +++ b/server/app/bot/handlers/manage/subjects.py @@ -0,0 +1,589 @@ +"""«📚 Предметы»: the class's subject dictionary. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +import re +from html import escape + +from aiogram import F, Router +from aiogram.filters import Command +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import manage_render as mr +from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.keyboards import back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import ( + COLOUR_PRESETS, + SubjectAction, + colour_keyboard, + subject_card_keyboard, + subject_list_keyboard, +) +from app.bot.manage_states import EditSubject +from app.bot.render import plural +from app.models import Role, SchoolClass, Subject, TimetableEntry +from app.services import audit, structure +from app.services import subjects as subjects_service + +router = Router(name="manage.subjects") + +COLOUR_RE = re.compile(r"^#?([0-9a-fA-F]{6})$") + +SUBJECT_NAME_MAX = 120 +SHORT_NAME_MAX = 16 +TEACHER_MAX = 120 + + +# -------------------------------------------------------------------------- +# 📚 Subjects +# -------------------------------------------------------------------------- +# +# The subject dictionary is what keeps «Алгебра», «алгебра» and «Алг.» from +# being three different subjects in the timetable, the homework and the app's +# colour scheme. Renaming one therefore has to move every row that spells the +# old name, in the same transaction - see :func:`_rename_subject`. + + +async def _subjects_of(session: AsyncSession, class_id: int) -> list[Subject]: + return list( + await session.scalars( + select(Subject).where(Subject.class_id == class_id).order_by(Subject.name) + ) + ) + + +async def _subject_view(session: AsyncSession, school_class: SchoolClass, role: Role): + # «📚 Предметы» adopts the timetable's names on the way in, so the list + # cannot be empty while the class has a full timetable. «Собрать из + # расписания» stays: it is now the button for "I have just pasted a day and + # want to see its subjects without leaving", and it is still free to press. + await subjects_service.sync_from_timetable(session, school_class.id) + subjects = await _subjects_of(session, school_class.id) + return mr.render_subjects(subjects), subject_list_keyboard( + subjects, + can_edit=role.at_least(Role.ADMIN), + can_collect=role.at_least(Role.EDITOR), + ) + + +async def _subject_by_id( + session: AsyncSession, school_class: SchoolClass, raw: str +) -> Subject | None: + """Scoped by the query itself: an id naming another class's subject finds + nothing, whatever the callback payload claims.""" + subject_id = _int_or_none(raw) + if subject_id is None: + return None + return await session.scalar( + select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) + ) + + +@router.message(Command("subjects")) +async def cmd_subjects( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await message.answer(_refusal(role, Role.EDITOR)) + return + await state.clear() + text, keyboard = await _subject_view(session, school_class, role) + await message.answer(text, reply_markup=keyboard) + + +@router.callback_query(SubjectAction.filter(F.action == "list")) +async def subjects_list( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + await state.clear() + text, keyboard = await _subject_view(session, school_class, role) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +@router.callback_query(SubjectAction.filter(F.action == "open")) +async def subject_open( + callback: CallbackQuery, + callback_data: SubjectAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + subject = await _subject_by_id(session, school_class, callback_data.value) + if subject is None: + await callback.answer("Предмет уже удалён", show_alert=True) + return + + await state.clear() + await callback.message.edit_text( + mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) + ) + await callback.answer() + + +#: field tag -> (state to wait in, prompt). The tag travels in callback data, +#: so an unknown one is refused rather than mapped to a default. +_SUBJECT_FIELDS = { + "name": (EditSubject.name, "Новое название предмета:"), + "short": ( + EditSubject.short_name, + "Сокращение для узких экранов, до 16 символов. «-» — убрать:", + ), + "teacher": (EditSubject.teacher, "Кто ведёт предмет? «-» — убрать:"), +} + + +@router.callback_query(SubjectAction.filter(F.action == "field")) +async def subject_field( + callback: CallbackQuery, + callback_data: SubjectAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + field, _, raw_id = callback_data.value.partition(":") + subject = await _subject_by_id(session, school_class, raw_id) + if subject is None: + await callback.answer("Предмет уже удалён", show_alert=True) + return + + await state.update_data(subject_id=subject.id) + + if field == "colour": + await state.set_state(EditSubject.colour) + await callback.message.edit_text( + f"Цвет предмета <b>{escape(subject.name)}</b>: сейчас {mr.swatch(subject.color)}.\n\n" + "Выберите из готовых или пришлите свой в виде <code>#5B6ABF</code>.", + reply_markup=colour_keyboard(subject.id), + ) + await callback.answer() + return + + target = _SUBJECT_FIELDS.get(field) + if target is None: + await callback.answer("Неизвестное поле", show_alert=True) + return + next_state, prompt = target + await state.set_state(next_state) + await callback.message.edit_text( + f"<b>{escape(subject.name)}</b>\n\n{prompt}", reply_markup=cancel_keyboard() + ) + await callback.answer() + + +async def _subject_from_state( + state: FSMContext, session: AsyncSession, school_class: SchoolClass +) -> Subject | None: + data = await state.get_data() + return await _subject_by_id(session, school_class, str(data.get("subject_id", ""))) + + +@router.message(EditSubject.name) +async def subject_rename( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + name = " ".join((message.text or "").split()) + if not 1 <= len(name) <= SUBJECT_NAME_MAX: + await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") + return + + subject = await _subject_from_state(state, session, school_class) + if subject is None: + await state.clear() + await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) + return + if name == subject.name: + await state.clear() + await message.answer("Название не изменилось.", reply_markup=back_to_menu()) + return + + clash = await subjects_service.clashing(session, school_class.id, name, besides=subject.id) + if clash is not None: + await message.answer( + f"Предмет <b>{escape(name)}</b> уже есть. Придумайте другое название:" + ) + return + + days = await structure.homework_clashing(session, school_class.id, subject.name, name) + if days: + listed = ", ".join(f"{day:%d.%m}" for day in days[:5]) + await message.answer( + f"На эти дни уже есть задания и по <b>{escape(subject.name)}</b>, и по " + f"<b>{escape(name)}</b>: {listed}. Уберите одно из них и повторите — " + "иначе переименование потеряется целиком.", + reply_markup=back_to_menu(), + ) + await state.clear() + return + + old_name = subject.name + moved = await structure.rename_subject(session, school_class.id, subject, name) + await audit.record( + session, + school_class.id, + message.from_user.id, + "subject.rename", + f"предмет «{old_name}» → «{name}», строк обновлено: {moved}", + ) + await session.commit() + await state.clear() + + await message.answer( + f"✅ <b>{escape(old_name)}</b> → <b>{escape(name)}</b>.\n" + f"Переименовано в расписании, заданиях и заменах: {moved}.", + reply_markup=subject_card_keyboard(subject.id), + ) + + +async def _save_subject_text( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass, + field: str, + limit: int, + label: str, +) -> None: + """The short-name and teacher steps: same shape, different column.""" + raw = " ".join((message.text or "").split()) + subject = await _subject_from_state(state, session, school_class) + if subject is None: + await state.clear() + await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) + return + + value = None if raw in {"-", "—", ""} else raw[:limit] + setattr(subject, field, value) + await audit.record( + session, + school_class.id, + message.from_user.id, + f"subject.{field}", + f"{label} предмета «{subject.name}»: {value or 'убрано'}", + ) + await session.commit() + await state.clear() + await message.answer( + mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) + ) + + +@router.message(EditSubject.short_name) +async def subject_short_name( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + await _save_subject_text( + message, state, session, school_class, "short_name", SHORT_NAME_MAX, "сокращение" + ) + + +@router.message(EditSubject.teacher) +async def subject_teacher( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + await _save_subject_text( + message, state, session, school_class, "teacher", TEACHER_MAX, "учитель" + ) + + +async def _apply_colour( + session: AsyncSession, + school_class: SchoolClass, + subject: Subject, + telegram_id: int, + colour: str | None, +) -> None: + subject.color = colour + await audit.record( + session, + school_class.id, + telegram_id, + "subject.colour", + f"цвет предмета «{subject.name}»: {colour or 'убран'}", + ) + await session.commit() + + +@router.callback_query(SubjectAction.filter(F.action == "colour")) +async def subject_colour_pick( + callback: CallbackQuery, + callback_data: SubjectAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + raw_id, _, raw_colour = callback_data.value.partition(":") + subject = await _subject_by_id(session, school_class, raw_id) + if subject is None: + await callback.answer("Предмет уже удалён", show_alert=True) + return + + if raw_colour == "none": + colour = None + else: + match = COLOUR_RE.match(raw_colour) + if match is None: + await callback.answer("Неизвестный цвет", show_alert=True) + return + colour = f"#{match.group(1).upper()}" + + await _apply_colour(session, school_class, subject, callback.from_user.id, colour) + await state.clear() + await callback.message.edit_text( + mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) + ) + await callback.answer("Цвет сохранён") + + +@router.message(EditSubject.colour) +async def subject_colour_typed( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + raw = (message.text or "").strip() + subject = await _subject_from_state(state, session, school_class) + if subject is None: + await state.clear() + await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) + return + + if raw in {"-", "—"}: + colour = None + else: + match = COLOUR_RE.match(raw) + if match is None: + presets = ", ".join(value for _, value in COLOUR_PRESETS[:3]) + await message.answer( + "Цвет пишется как <code>#5B6ABF</code> — шесть шестнадцатеричных цифр. " + f"Например: {escape(presets)}. «-» — убрать цвет." + ) + return + colour = f"#{match.group(1).upper()}" + + await _apply_colour(session, school_class, subject, message.from_user.id, colour) + await state.clear() + await message.answer( + mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) + ) + + +@router.callback_query(SubjectAction.filter(F.action == "add")) +async def subject_add( + callback: CallbackQuery, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.set_state(EditSubject.create) + await callback.message.edit_text( + "Название нового предмета:", reply_markup=cancel_keyboard() + ) + await callback.answer() + + +@router.message(EditSubject.create) +async def subject_create( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + name = " ".join((message.text or "").split()) + if not 1 <= len(name) <= SUBJECT_NAME_MAX: + await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") + return + + # Ignores case, so «физика» opens the class's «Физика» instead of founding + # a second row beside it. + existing = await subjects_service.find(session, school_class.id, name) + if existing is not None: + await state.clear() + await message.answer( + f"Предмет <b>{escape(existing.name)}</b> уже есть.", + reply_markup=subject_card_keyboard(existing.id), + ) + return + + subject = Subject(class_id=school_class.id, name=name) + session.add(subject) + await audit.record( + session, school_class.id, message.from_user.id, "subject.add", f"добавлен предмет «{name}»" + ) + await session.commit() + await state.clear() + await message.answer( + mr.render_subject_card(subject), reply_markup=subject_card_keyboard(subject.id) + ) + + +@router.callback_query(SubjectAction.filter(F.action == "delete")) +async def subject_delete( + callback: CallbackQuery, + callback_data: SubjectAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Deleting a subject the timetable still uses is refused. + + It used to be allowed, and it left the lessons alone: the template stores + the name as well as the link, so the class kept its timetable and lost + only the colour and the teacher. That stopped being true when the + dictionary started keeping itself — the name is still in the template, so + the next read adopts it back, stripped of its colour and its teacher, and + the admin is left believing they deleted something. + + The order is now stated instead: out of the timetable first, out of the + dictionary second. A subject nothing teaches still goes in one tap. + """ + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + subject = await _subject_by_id(session, school_class, callback_data.value) + if subject is None: + await callback.answer("Предмет уже удалён", show_alert=True) + return + + in_use = await subjects_service.lessons_using(session, school_class.id, subject) + if in_use: + await callback.answer( + # ``plural`` carries the number itself — printing it again beside + # the call produced «стоит в расписании: 1 1 урок». + f"«{subject.name}» стоит в расписании: " + f"{plural(in_use, 'урок', 'урока', 'уроков')}. " + "Сначала уберите их из расписания.", + show_alert=True, + ) + return + + name = subject.name + await session.delete(subject) + await audit.record( + session, school_class.id, callback.from_user.id, "subject.delete", + f"удалён предмет «{name}»", + ) + await session.commit() + await state.clear() + + text, keyboard = await _subject_view(session, school_class, role) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer(f"Удалён: {name}"[:200]) + + +@router.callback_query(SubjectAction.filter(F.action == "collect")) +async def subjects_collect( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Create a Subject row for every name the timetable already uses. + + An editor may run this: it invents nothing, it only writes down the names + that are already in the class's timetable. + """ + if not _allowed(school_class, role, Role.EDITOR): + await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) + return + + names = list( + await session.scalars( + select(TimetableEntry.subject_name) + .where(TimetableEntry.class_id == school_class.id) + .distinct() + ) + ) + known = {subject.name for subject in await _subjects_of(session, school_class.id)} + created = [name for name in sorted(names) if name and name not in known] + for name in created: + session.add(Subject(class_id=school_class.id, name=name[:SUBJECT_NAME_MAX])) + + if created: + await audit.record( + session, + school_class.id, + callback.from_user.id, + "subject.collect", + f"собрано предметов из расписания: {len(created)}", + ) + await session.commit() + + await state.clear() + text, keyboard = await _subject_view(session, school_class, role) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer( + f"Добавлено: {len(created)}" if created else "Все предметы расписания уже в списке" + ) diff --git a/server/app/bot/handlers/manage/terms.py b/server/app/bot/handlers/manage/terms.py new file mode 100644 index 00000000..c9057d43 --- /dev/null +++ b/server/app/bot/handlers/manage/terms.py @@ -0,0 +1,203 @@ +"""«🗓 Четверти»: the class's quarters or half-years, edited against the shared rules. + +Part of :mod:`app.bot.handlers.manage`; the rules every screen of it +follows are in that package's docstring. +""" + +from __future__ import annotations + +from datetime import datetime +from html import escape + +from aiogram import F, Router +from aiogram.fsm.context import FSMContext +from aiogram.types import CallbackQuery, Message +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.keyboards import back_to_menu, cancel_keyboard +from app.bot.manage_keyboards import TermAction, terms_menu +from app.bot.manage_states import EditTerm +from app.models import Role, SchoolClass, TermKind +from app.services import audit +from app.services import terms as terms_service + +router = Router(name="manage.terms") + + +# -------------------------------------------------------------------------- +# 🗓 Quarters and half-years +# +# The dates are a school's own: the holidays move, a region shifts its spring +# break, a quarantine eats a week. So this is an editor rather than a display, +# and the rules it edits against live in ``app/services/terms.py`` — the same +# ones `/api/v1/manage` uses, because two implementations of "does this term +# overlap" disagree within a month. +# -------------------------------------------------------------------------- + + +def _term_year(school_class: SchoolClass) -> int: + """The school year in force *for this class*, in the class's own zone. + + Not the server's: a class in Kamchatka turns the page on 1 September nine + hours before a class in Kaliningrad, and the server is in neither. + """ + return terms_service.opening_year_of(datetime.now(school_class.tz).date()) + + +async def _terms_card(session: AsyncSession, school_class: SchoolClass): + year = _term_year(school_class) + rows = await terms_service.ensure(session, school_class, year) + await session.commit() + + scheme = terms_service.scheme_of(school_class) + is_semester = scheme is TermKind.SEMESTER + heading = "полугодия" if is_semester else "четверти" + today = datetime.now(school_class.tz).date() + current = terms_service.term_at(rows, today) + + lines = [ + f"🗓 <b>{escape(school_class.name)}</b> — {heading} {year}/{year + 1}", + "", + ] + for term in rows: + mark = " ←" if current is not None and term.index == current.index else "" + lines.append( + f"<b>{term.index}.</b> {term.starts_on:%d.%m.%Y} — " + f"{term.ends_on:%d.%m.%Y} · {term.days} дн.{mark}" + ) + if current is None: + lines.append("") + lines.append("Сейчас каникулы.") + lines.append("") + lines.append("Нажмите период, чтобы изменить его даты.") + + return "\n".join(lines), terms_menu(rows, is_semester=is_semester) + + +@router.callback_query(TermAction.filter(F.action == "list")) +async def terms_list( + callback: CallbackQuery, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + await state.clear() + text, keyboard = await _terms_card(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer() + + +@router.callback_query(TermAction.filter(F.action == "scheme")) +async def terms_scheme( + callback: CallbackQuery, + callback_data: TermAction, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + wanted = TermKind.SEMESTER if callback_data.value == "semester" else TermKind.QUARTER + year = _term_year(school_class) + await terms_service.set_scheme(session, school_class, wanted, year) + await audit.record( + session, + school_class.id, + callback.from_user.id, + "class.term_kind", + f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", + ) + await session.commit() + await state.clear() + + text, keyboard = await _terms_card(session, school_class) + await callback.message.edit_text(text, reply_markup=keyboard) + await callback.answer("Схема изменена") + + +@router.callback_query(TermAction.filter(F.action == "edit")) +async def term_edit_prompt( + callback: CallbackQuery, + callback_data: TermAction, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) + return + + # ``_int_or_none``, not ``isdigit`` and ``int``: those two do not ask the + # same question, so «²» passed the check and raised inside the conversion + # — out of the handler, before ``callback.answer`` was ever reached. + index = _int_or_none(callback_data.value) + if index is None or index < 1: + await callback.answer("Неизвестный период", show_alert=True) + return + + await state.set_state(EditTerm.span) + await state.update_data(term_index=index) + await callback.message.edit_text( + f"Период <b>{index}</b>. Пришлите обе даты одной строкой:\n\n" + "<code>01.09.2026 - 31.10.2026</code>", + reply_markup=cancel_keyboard(), + ) + await callback.answer() + + +@router.message(EditTerm.span) +async def term_edit_apply( + message: Message, + state: FSMContext, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + + data = await state.get_data() + index = int(data.get("term_index", 0)) + if index < 1: + await state.clear() + await message.answer("Начните заново: /class", reply_markup=back_to_menu()) + return + + span = terms_service.parse_span(message.text) + if span is None: + await message.answer( + "Не разобрал. Две даты через дефис:\n\n<code>01.09.2026 - 31.10.2026</code>" + ) + return + + try: + await terms_service.set_bounds( + session, school_class, _term_year(school_class), index, span[0], span[1] + ) + except terms_service.TermError as error: + # The message is the rule, in Russian, and the prompt stays open: the + # admin has one date to correct, not a form to start again. + await message.answer(str(error)) + return + + await audit.record( + session, + school_class.id, + message.from_user.id, + "class.term", + f"период {index}: {span[0]:%d.%m.%Y} — {span[1]:%d.%m.%Y}", + ) + await session.commit() + await state.clear() + + text, keyboard = await _terms_card(session, school_class) + await message.answer(text, reply_markup=keyboard) diff --git a/server/tests/test_access_service.py b/server/tests/test_access_service.py index 3df52217..3d9b6a2c 100644 --- a/server/tests/test_access_service.py +++ b/server/tests/test_access_service.py @@ -164,8 +164,8 @@ async def watched(*args, **kwargs): return await real(*args, **kwargs) monkeypatch.setattr(access, "approve_request", watched) - monkeypatch.setattr(api_manage, "_tell", lambda *_, **__: _noop()) - monkeypatch.setattr(bot_manage, "_bot_of", lambda _: None) + monkeypatch.setattr(api_manage.requests, "_tell", lambda *_, **__: _noop()) + monkeypatch.setattr(bot_manage.requests, "_bot_of", lambda _: None) from_bot = await _request(session, school_class) await bot_manage.request_approve( diff --git a/server/tests/test_api_manage.py b/server/tests/test_api_manage.py index 7dac0b33..373d401d 100644 --- a/server/tests/test_api_manage.py +++ b/server/tests/test_api_manage.py @@ -43,7 +43,7 @@ Subject, TimetableEntry, ) -from app.services import linking +from app.services import audit, linking MONDAY = date(2026, 9, 7) @@ -84,7 +84,7 @@ def recording_bot(monkeypatch): """Give the decision endpoints a bot, and record what it sends.""" bot = FakeBot() monkeypatch.setattr(get_settings(), "bot_token", "123456:TEST") - monkeypatch.setattr(manage, "_build_bot", lambda: bot) + monkeypatch.setattr(manage.requests, "_build_bot", lambda: bot) return bot @@ -1710,7 +1710,7 @@ async def test_a_failed_log_line_leaves_the_phone_linked( async def explode(*args: Any, **kwargs: Any) -> None: raise RuntimeError("the log is full") - monkeypatch.setattr(manage.audit, "record", explode) + monkeypatch.setattr(audit, "record", explode) with pytest.raises(RuntimeError): await client.post( f"/api/v1/manage/devices/{device.id}/unlink", headers=_auth(admin_token) diff --git a/server/tests/test_bot_manage.py b/server/tests/test_bot_manage.py index d7dbfe84..264ed4af 100644 --- a/server/tests/test_bot_manage.py +++ b/server/tests/test_bot_manage.py @@ -2493,7 +2493,7 @@ async def schools_search(self, query: str) -> list[dict]: def _patch_netschool(monkeypatch, *, login_error=None, schools=None) -> None: _FakeNetSchool.login_error = login_error _FakeNetSchool.schools = schools or [] - monkeypatch.setattr("app.bot.handlers.manage.NetSchoolClient", _FakeNetSchool) + monkeypatch.setattr("app.bot.handlers.manage.diary_binding.NetSchoolClient", _FakeNetSchool) async def test_choosing_netschool_shows_the_region_list(session, school_class): @@ -4271,12 +4271,22 @@ def test_the_role_check_above_reaches_every_handler_that_has_one(): """ from app.bot.handlers import manage as manage_module - source = Path(manage_module.__file__).read_text(encoding="utf-8") - minimums = _minimum_role_of(source) + # A package now, one module per screen, each with a router of its own + # under `manage_router`: every module's source, and every router's + # handlers, so a screen split off tomorrow is read the day it is split. + minimums: dict[str, Role | None] = {} + for module in sorted(Path(manage_module.__file__).parent.glob("*.py")): + minimums.update(_minimum_role_of(module.read_text(encoding="utf-8"))) + + def routers(router): + yield router + for sub in router.sub_routers: + yield from routers(sub) registered = { handler.callback.__name__ - for observer in (manage_router.callback_query, manage_router.message) + for router in routers(manage_router) + for observer in (router.callback_query, router.message) for handler in observer.handlers } assert len(registered) > 50, "the router looks empty; this test would prove nothing" From 6bcdd327bbb9ad060db68323666da21ea94fdd76 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 17:43:38 +0300 Subject: [PATCH 27/43] Split the wire format into one module per area, behind the same import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `app/schemas.py` had grown to 1573 lines and 89 classes, so a change to one entity meant reading every other one (#208). It is now the package `app/schemas/`: fifteen modules by area — `bundle`, `join`, `homework`, `tasks`, `subjects`, `edit`, `cron`, `diary_session`, `diary`, `school_class`, `bells`, `timetable`, `access`, `reports`, `directory` — and `_text`, the cleaning every free-text field goes through, which they share rather than repeat, because two spellings of one cleaning are two subjects that look like one. Every class, alias, constant and helper moved verbatim, with the comments directly above it; nothing in a class body changed. The section banners became module docstrings: the diary's text went to `diary`, and the one about the management surface, which holds across five modules, to the package docstring. The package re-exports every public name, and `_clean_optional_text`, which `tests/test_hardening.py` reads from here, so no import anywhere in `app/`, `tests/` or `scripts/` had to change. What the package no longer carries are the names the old module only imported (`BaseModel`, `Field`, `re`, `Date` and the like) and its private helpers; nothing outside it read either. The contract did not move: the OpenAPI document is byte-identical before and after (sorted JSON, with the Telegram webhook mounted and without, and under two hash seeds), all 89 models are fully defined, and a built wheel carries the whole package — `packages.find` already includes `app*`, and `.vercelignore` excludes nothing under `app/`. Not covered: `bot/handlers/manage.py` and `api/manage.py`, the other two files #208 names, are not split here. The Android KDoc that points at `server/app/schemas.py`, and the tree in `docs/architecture.md`, still name the old file. Refs #208 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/schemas.py | 1573 --------------------------- server/app/schemas/__init__.py | 267 +++++ server/app/schemas/_text.py | 50 + server/app/schemas/access.py | 58 + server/app/schemas/bells.py | 106 ++ server/app/schemas/bundle.py | 163 +++ server/app/schemas/cron.py | 25 + server/app/schemas/diary.py | 262 +++++ server/app/schemas/diary_session.py | 248 +++++ server/app/schemas/directory.py | 91 ++ server/app/schemas/edit.py | 109 ++ server/app/schemas/homework.py | 65 ++ server/app/schemas/join.py | 110 ++ server/app/schemas/reports.py | 54 + server/app/schemas/school_class.py | 109 ++ server/app/schemas/subjects.py | 102 ++ server/app/schemas/tasks.py | 91 ++ server/app/schemas/timetable.py | 50 + 18 files changed, 1960 insertions(+), 1573 deletions(-) delete mode 100644 server/app/schemas.py create mode 100644 server/app/schemas/__init__.py create mode 100644 server/app/schemas/_text.py create mode 100644 server/app/schemas/access.py create mode 100644 server/app/schemas/bells.py create mode 100644 server/app/schemas/bundle.py create mode 100644 server/app/schemas/cron.py create mode 100644 server/app/schemas/diary.py create mode 100644 server/app/schemas/diary_session.py create mode 100644 server/app/schemas/directory.py create mode 100644 server/app/schemas/edit.py create mode 100644 server/app/schemas/homework.py create mode 100644 server/app/schemas/join.py create mode 100644 server/app/schemas/reports.py create mode 100644 server/app/schemas/school_class.py create mode 100644 server/app/schemas/subjects.py create mode 100644 server/app/schemas/tasks.py create mode 100644 server/app/schemas/timetable.py diff --git a/server/app/schemas.py b/server/app/schemas.py deleted file mode 100644 index dfee7f07..00000000 --- a/server/app/schemas.py +++ /dev/null @@ -1,1573 +0,0 @@ -"""Wire format shared with the Android client. - -Field names are the contract. Anything renamed here must be renamed in -``core/network`` on the Android side and bumped in ``API_VERSION``. -""" - -from __future__ import annotations - -import re -from datetime import date as Date -from datetime import datetime -from datetime import time as Time -from typing import TYPE_CHECKING, Literal - -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator - -from app.providers.diary.http import cookie_value_ok, header_value_ok - -if TYPE_CHECKING: - from app.providers.diary.registry import Binding - -API_VERSION = 1 - - -def _strip_control_chars(value: str) -> str: - """Drop anything unprintable, including NUL. - - ``device_name`` and ``code`` are client-supplied and land in a database - column. Postgres rejects NUL inside text outright, so a device that sent one - got a 500 out of what should be a clean request. - """ - return "".join(ch for ch in value if ch == " " or ch.isprintable()) - - -def _clean_optional_text(value: str | None) -> str | None: - """One line, single-spaced, or ``None``. - - Runs of whitespace are collapsed, not merely trimmed at the ends, because - the bot has always done exactly that - ``" ".join(text.split())`` on every - name it is typed - and a name is compared as text in three places that - cannot see each other: the uniqueness check that makes the subject - dictionary a dictionary, the rename that carries the timetable, the - homework and the substitutions along by name, and the widget's own matching. A - class where «Алгебра и начала» was added from the phone and «Алгебра и - начала» from the bot has two subjects that look like one, and a rename of - either moves none of the other's lessons. - - Every whitespace character becomes a space first, so a tab is a word break - rather than something ``_strip_control_chars`` silently deletes - it is - neither a space nor printable, so «а\tб» used to be stored as «аб». - """ - if value is None: - return None - spaced = "".join(" " if ch.isspace() else ch for ch in value) - return " ".join(_strip_control_chars(spaced).split()) or None - - -def _clean_notes(value: str | None) -> str | None: - """Notes keep their line breaks; everything else unprintable goes.""" - if value is None: - return None - cleaned = "".join(ch for ch in value if ch == "\n" or ch == " " or ch.isprintable()) - cleaned = cleaned.strip() - return cleaned or None - - -#: Mirrors ``JoinRequest.code``'s own ``min_length``; see ``_clean_code``. -_MIN_CODE_LENGTH = 4 - - -class JoinRequest(BaseModel): - code: str = Field(min_length=4, max_length=16) - device_name: str | None = Field(default=None, max_length=120) - - @field_validator("code") - @classmethod - def _clean_code(cls, value: str) -> str: - """Sanitise the code, and reject one that sanitises away to nothing. - - This used to share ``_sanitise`` with ``device_name`` and return - ``cleaned or None``. Pydantic does not re-check an after-validator's - return against the field's annotation, so a code of four spaces — which - passes ``min_length=4`` — arrived at the handler as ``None`` and the - ``.strip()`` there raised ``AttributeError``. That is a 500 out of a - request the schema exists to reject, on an unauthenticated endpoint. - """ - cleaned = _strip_control_chars(value).strip() - if len(cleaned) < _MIN_CODE_LENGTH: - raise ValueError("code must contain at least 4 usable characters") - return cleaned - - @field_validator("device_name") - @classmethod - def _clean_device_name(cls, value: str | None) -> str | None: - """Optional, so sanitising it away to nothing simply means absent.""" - if value is None: - return None - cleaned = _strip_control_chars(value).strip() - return cleaned or None - - -class DiaryBindingOut(BaseModel): - """Which diary a class reads, so a phone that joined it can sign in there - without searching for its school. - - Defined here rather than in the diary block below because - :class:`JoinResponse` carries it. Built only through ``of`` from - `registry.binding`, so a class bound to a region since dropped from the - allow-list, one that takes no password, or a «Сетевой город» binding with - no school all read as no binding at all — the phone is never pointed at a - diary this server would refuse. - """ - - provider: Literal["petersburg", "netschool"] - #: The allow-list key, which is the region catalog's key. ``None`` for - #: Petersburg, which is one city's server. - region: str | None = None - #: The upstream's own school id («scid»), which the phone signs in with. - school_id: int | None = None - school_name: str | None = None - - @classmethod - def of(cls, bound: Binding | None) -> DiaryBindingOut | None: - if bound is None: - return None - return cls( - provider=bound.provider.key, - region=bound.region, - school_id=bound.school_id, - school_name=bound.school_name, - ) - - -class JoinResponse(BaseModel): - token: str - class_id: int - class_name: str - school: str | None = None - timezone: str - #: The class's diary binding, or ``None`` when it has none this server can - #: reach. Additive, so an older phone ignores it and ``API_VERSION`` holds. - diary: DiaryBindingOut | None = None - - -class LessonOut(BaseModel): - index: int - subject: str - starts_at: Time - ends_at: Time - room: str | None = None - teacher: str | None = None - color: str | None = None - is_replaced: bool = False - is_cancelled: bool = False - note: str | None = None - - -class EventOut(BaseModel): - title: str - kind: str - starts_at: Time - ends_at: Time - location: str | None = None - covers_lesson: bool = False - - -class HomeworkOut(BaseModel): - subject: str - text: str - attachment_url: str | None = None - - -class HolidayOut(BaseModel): - """A named date, whether or not it stops the lessons. - - ``code`` is stable and ``title`` is Russian, the way every other string the - server puts on a screen is. A client that wants the name in its own - language matches the code and falls back to the title, so a date this - server learns before that client does still has something to draw. - """ - - code: str - title: str - #: True only for a statutory non-working day, and then the day has no - #: lessons. False for an observance — «День учителя» is a full Wednesday. - stops_lessons: bool - - -class DayOut(BaseModel): - date: Date - weekday: int - kind: str - lessons: list[LessonOut] = [] - events: list[EventOut] = [] - homework: list[HomeworkOut] = [] - note: str | None = None - #: What this date is called, if it is called anything. - holiday: HolidayOut | None = None - #: Why there are no lessons, when the timetable was not what decided it: - #: `out_of_year`, `between_terms` or `public_holiday`. Null on an ordinary - #: day, including an ordinary empty one — «nobody put lessons on a Sunday» - #: is not a reason, it is the absence of one. - #: - #: Added beside `kind` rather than folded into it: all three arrive as - #: `holiday` today, and a client that has never heard of this field keeps - #: drawing what it drew. What it buys the ones that have is four different - #: accents on a calendar instead of one. - off_reason: str | None = None - - -class TermOut(BaseModel): - """One quarter or half-year, as the class actually runs it.""" - - index: int - kind: Literal["quarter", "semester"] - starts_on: Date - ends_on: Date - - -class ClassOut(BaseModel): - id: int - name: str - # The year of school, 1..11, and the letter that distinguishes two classes - # of the same year. Null on a class created before they existed: its name - # is all there is, and «9» read out of «9А» would be a guess. - grade: int | None = None - letter: str | None = None - school: str | None = None - city: str | None = None - timezone: str - #: Which scheme the year is cut into, and the terms themselves — the app - #: renders «2 четверть» and shades the calendar from these rather than - #: recomputing dates a school is free to have moved. - term_kind: Literal["quarter", "semester"] | None = None - terms: list[TermOut] = Field(default_factory=list) - - -RoleName = Literal["viewer", "editor", "admin", "owner"] - - -class DeviceOut(BaseModel): - """What this device may do. Never carries the Telegram id it is linked to: - the app shows a name and a role, and the id is nobody's business.""" - - linked: bool = False - role: RoleName | None = None - can_edit: bool = False - - -class BundleOut(BaseModel): - """One response holds everything the widget needs to run offline for two weeks.""" - - api_version: int = API_VERSION - school_class: ClassOut - generated_at: str - days: list[DayOut] - next_school_day: DayOut | None = None - # Added in the same API version: absent for a client that predates it, and - # ``None`` is what such a client's mapper ignores. - device: DeviceOut | None = None - - -# -------------------------------------------------------------------------- -# Linking -# -------------------------------------------------------------------------- - - -class MeOut(BaseModel): - device_name: str | None = None - linked: bool - role: RoleName | None = None - can_edit: bool - # Only while unlinked. A linked device has no code, and a code that stayed - # on a linked row could be typed by somebody else and re-home the phone. - link_code: str | None = None - bot_deep_link: str | None = None - - -class UnlinkOut(BaseModel): - linked: bool - - -# -------------------------------------------------------------------------- -# Homework -# -------------------------------------------------------------------------- - - -class HomeworkItemOut(HomeworkOut): - """A homework row on its own, outside a day: the list and the ticks need - the id and the date that the bundle's per-day shape carries implicitly.""" - - id: int - due_date: Date - # This device's owner's tick. Always ``false`` for an unlinked device. - done: bool = False - - -class DoneIn(BaseModel): - done: bool - - -class DoneOut(BaseModel): - id: int - done: bool - - -class HomeworkIn(BaseModel): - due_date: Date - subject: str = Field(min_length=1, max_length=120) - text: str = Field(min_length=1, max_length=4000) - attachment_url: str | None = Field(default=None, max_length=500) - - @field_validator("subject") - @classmethod - def _clean_subject(cls, value: str) -> str: - cleaned = _strip_control_chars(value).strip() - if not cleaned: - raise ValueError("subject must not be blank") - return cleaned - - @field_validator("text") - @classmethod - def _clean_text(cls, value: str) -> str: - # Line breaks stay: «№ 12–15\nустно § 4» is how homework is written. - cleaned = _clean_notes(value) - if cleaned is None: - raise ValueError("text must not be blank") - return cleaned - - @field_validator("attachment_url") - @classmethod - def _clean_url(cls, value: str | None) -> str | None: - if value is None: - return None - cleaned = _strip_control_chars(value).strip() - return cleaned or None - - -# -------------------------------------------------------------------------- -# Subjects -# -------------------------------------------------------------------------- - - -class SubjectOut(BaseModel): - name: str - short_name: str | None = None - teacher: str | None = None - color: str | None = None - - -# -------------------------------------------------------------------------- -# Now -# -------------------------------------------------------------------------- - - -NowState = Literal["before_school", "lesson", "break", "after_school", "day_off", "no_data"] - - -class NowOut(BaseModel): - """The server's answer to "what is happening right now", in the class's zone. - - The widget normally computes this from the bundle itself; the endpoint is - for clients that would rather ask than carry the resolver, and it is what - the bundle's own maths is checked against. - """ - - date: Date - time: Time - state: NowState - current: LessonOut | None = None - next: LessonOut | None = None - # Seconds to the next boundary: the end of ``current`` during a lesson, - # the start of ``next`` before school and in a break. ``None`` when the - # school day is over or never started. - until_next_seconds: int | None = None - # The first day with lessons strictly after today. - next_school_day: Date | None = None - - -# -------------------------------------------------------------------------- -# Personal tasks -# -------------------------------------------------------------------------- - - -class TaskOut(BaseModel): - id: int - title: str - notes: str | None = None - subject_name: str | None = None - due_date: Date | None = None - due_time: Time | None = None - priority: int - done: bool - # UTC: an instant, not a time anybody wrote down. See `PersonalTask`. - done_at: datetime | None = None - homework_id: int | None = None - # Class wall time, unlike the three around it. - remind_at: datetime | None = None - # UTC, with `done_at`. - created_at: datetime | None = None - updated_at: datetime | None = None - - -class TaskIn(BaseModel): - title: str = Field(min_length=1, max_length=200) - notes: str | None = Field(default=None, max_length=2000) - due_date: Date | None = None - due_time: Time | None = None - priority: int = Field(default=1, ge=0, le=2) - subject_name: str | None = Field(default=None, max_length=120) - homework_id: int | None = None - remind_at: datetime | None = None - - @field_validator("title") - @classmethod - def _clean_title(cls, value: str) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("title must not be blank") - return cleaned - - _clean_subject = field_validator("subject_name")(_clean_optional_text) - _clean_notes = field_validator("notes")(_clean_notes) - - -class TaskPatch(BaseModel): - """Every field optional; only the ones sent are changed. ``null`` clears a - nullable field, which is why "absent" and "null" are told apart.""" - - title: str | None = Field(default=None, min_length=1, max_length=200) - notes: str | None = Field(default=None, max_length=2000) - due_date: Date | None = None - due_time: Time | None = None - priority: int | None = Field(default=None, ge=0, le=2) - subject_name: str | None = Field(default=None, max_length=120) - homework_id: int | None = None - remind_at: datetime | None = None - done: bool | None = None - - # An absent field is never validated, so these two run only on a value the - # client actually sent - which is how an explicit ``null`` is refused while - # "leave it alone" stays the default, exactly as ``ClassPatch`` does it. - # Both columns are NOT NULL, and without the refusal ``{"title": null}`` - # reached the UPDATE: an IntegrityError forty frames down, which the app - # sees as a 500 on a field it merely cleared. - @field_validator("title") - @classmethod - def _clean_title(cls, value: str | None) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("title must not be blank") - return cleaned - - @field_validator("priority") - @classmethod - def _priority_when_present(cls, value: int | None) -> int: - if value is None: - raise ValueError("priority must not be null") - return value - - _clean_subject = field_validator("subject_name")(_clean_optional_text) - _clean_notes = field_validator("notes")(_clean_notes) - - -# -------------------------------------------------------------------------- -# Calendar -# -------------------------------------------------------------------------- - - -class CalendarOut(BaseModel): - url: str - - -# -------------------------------------------------------------------------- -# Editing -# -------------------------------------------------------------------------- - - -OverrideActionName = Literal["replace", "cancel", "clear"] - - -class OverrideIn(BaseModel): - date: Date - index: int = Field(ge=1, le=20) - action: OverrideActionName - subject: str | None = Field(default=None, max_length=120) - room: str | None = Field(default=None, max_length=32) - teacher: str | None = Field(default=None, max_length=120) - note: str | None = Field(default=None, max_length=500) - - _clean_subject = field_validator("subject")(_clean_optional_text) - _clean_room = field_validator("room")(_clean_optional_text) - _clean_teacher = field_validator("teacher")(_clean_optional_text) - _clean_note = field_validator("note")(_clean_optional_text) - - @model_validator(mode="after") - def _replace_needs_something(self) -> OverrideIn: - # A replacement with nothing in it would be stored and then dropped by - # the resolver as a no-op; better to say so up front. - if self.action == "replace" and not (self.subject or self.room or self.teacher): - raise ValueError("replace needs a subject, a room or a teacher") - return self - - -class OverrideOut(BaseModel): - date: Date - index: int - action: OverrideActionName - subject: str | None = None - room: str | None = None - teacher: str | None = None - note: str | None = None - - -EventKindName = Literal["event", "canteen", "exam", "trip", "meeting"] - - -class EventIn(BaseModel): - date: Date - starts_at: Time - ends_at: Time - title: str = Field(min_length=1, max_length=200) - kind: EventKindName = "event" - location: str | None = Field(default=None, max_length=120) - # Defaults like the bot: only a «мероприятие» or a trip normally stands in - # for lessons; a canteen break sits in a break. - covers_lesson: bool | None = None - - @field_validator("title") - @classmethod - def _clean_title(cls, value: str) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("title must not be blank") - return cleaned - - _clean_location = field_validator("location")(_clean_optional_text) - - @model_validator(mode="after") - def _ends_after_start(self) -> EventIn: - if self.ends_at <= self.starts_at: - raise ValueError("ends_at must be after starts_at") - return self - - -class EventCreatedOut(BaseModel): - id: int - - -DayKindName = Literal["normal", "holiday", "shortened", "remote"] - - -class DayIn(BaseModel): - date: Date - kind: DayKindName - note: str | None = Field(default=None, max_length=500) - bell_schedule_id: int | None = None - - _clean_note = field_validator("note")(_clean_optional_text) - - -class DayOverrideOut(BaseModel): - date: Date - kind: DayKindName - note: str | None = None - bell_schedule_id: int | None = None - - -class DeletedOut(BaseModel): - id: int - deleted: bool = True - - -# -------------------------------------------------------------------------- -# Cron -# -------------------------------------------------------------------------- - - -class TickOut(BaseModel): - morning: int - evening: int - tasks: int - failed: int - fsm_purged: int - join_attempts_purged: int - diary_sessions_purged: int = 0 - device_tokens_purged: int = 0 - diary_links_purged: int = 0 - device_invites_purged: int = 0 - #: The keep-alive that holds a «Сетевой город» session open across its short - #: idle window: how many were pinged alive, how many the upstream had already - #: dropped, and true when the keep-alive itself raised (isolated so a diary - #: fault never fails the whole tick and reddens the clock). - diary_sessions_kept_alive: int = 0 - diary_sessions_lost: int = 0 - diary_keepalive_failed: bool = False - - -# --------------------------------------------------------------------------- -# The electronic diary -# -# The wire shapes of ``/api/v1/diary``. Every one is built from a provider -# model by its own ``of``, and that constructor is the seam: when the upstream -# changes, the provider's mapper absorbs it, these classes do not move, and the -# Android client never learns that anything happened. -# --------------------------------------------------------------------------- - - -class DiaryLoginIn(BaseModel): - """Credentials, used once and never stored. - - ``login`` rather than ``email`` because the upstream accepts more than one - kind of identifier and calling it an email would be a promise this project - cannot keep. - """ - - login: str = Field(min_length=3, max_length=200) - password: str = Field(min_length=1, max_length=200) - #: Which diary. Absent means Petersburg, so an older phone that sends only a - #: login and a password still signs in there. For «Сетевой город» the region - #: is a key into the allow-list and the school is the upstream's own id; - #: both are validated in the route before any upstream call. - provider: str | None = Field(default=None, max_length=32) - region: str | None = Field(default=None, max_length=32) - school_id: int | None = Field(default=None, ge=1, le=2_000_000_000) - - @field_validator("login") - @classmethod - def _clean_login(cls, value: str) -> str: - return _clean_login_value(value) - - -def _clean_login_value(value: str) -> str: - """A login as the upstream will see it: printable, trimmed, three or more. - - Shared by the password sign-in and the registration of a phone's session, - because both write it to the same column and «Вход выполнен» prints it - from there — and the phone cleans it character for character the same way - (`DiaryLogin.clean`), so a login pasted with an invisible character is not - a wrong password on one side only. It keys nothing: corrections are filed - under the child (`services/diary.child_scope`). - """ - cleaned = _strip_control_chars(value).strip() - if len(cleaned) < 3: - raise ValueError("login must contain at least 3 usable characters") - return cleaned - - -class DiaryLoginOut(BaseModel): - token: str - login: str - - - -class DiaryStudentOut(BaseModel): - id: int - first_name: str - last_name: str - middle_name: str | None = None - full_name: str - school: str | None = None - class_name: str | None = None - - @classmethod - def of(cls, student) -> DiaryStudentOut: - # Deliberately without ``education_id`` and ``group_id``: they are the - # upstream's handles, the server resolves them from the student id on - # every request, and a client that learned them would be a client that - # could be pointed at somebody else's child. - return cls( - id=student.id, - first_name=student.first_name, - last_name=student.last_name, - middle_name=student.middle_name, - full_name=student.full_name, - school=student.school, - class_name=student.class_name, - ) - - -#: Three dot-separated base64url parts, the last possibly empty: the shape of -#: the ``X-JWT-Token`` Petersburg issues. -_JWT = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*") - -#: An allow-list key's shape. Whether it is *in* the allow-list is the route's -#: question, asked before any upstream call. -_REGION_KEY = r"^[a-z0-9-]{2,32}$" - - -class PetersburgCredentialIn(BaseModel): - """The session Petersburg handed the phone: the ``X-JWT-Token`` cookie, or - ``data.token`` when the answer carried no cookie.""" - - model_config = ConfigDict(extra="forbid") - - token: str = Field(min_length=16, max_length=4096, repr=False) - - @field_validator("token") - @classmethod - def _a_jwt_that_can_be_a_cookie(cls, value: str) -> str: - # Sent back upstream as a cookie on every read, so it must be one - # cookie value and nothing more; `_raw` checks the same again. - if not _JWT.fullmatch(value) or not cookie_value_ok(value): - raise ValueError("token must be a JWT") - return value - - -class NetSchoolCookiesIn(BaseModel): - """The two session cookies «Сетевой город» sets, and no other — an unknown - name is refused rather than carried, since it would be sent on every read.""" - - model_config = ConfigDict(extra="forbid") - - NSSESSIONID: str = Field(min_length=1, max_length=128, repr=False) - ESRNSec: str | None = Field(default=None, min_length=1, max_length=2048, repr=False) - - @field_validator("NSSESSIONID", "ESRNSec") - @classmethod - def _one_cookie_value(cls, value: str | None) -> str | None: - # A `;` here would smuggle a second cookie onto every read. - if value is not None and not cookie_value_ok(value): - raise ValueError("not a cookie value") - return value - - -class NetSchoolCredentialIn(BaseModel): - """What the phone's «Сетевой город» sign-in ended holding.""" - - model_config = ConfigDict(extra="forbid") - - #: The bearer, sent in the ``at`` header, so it must be one header value. - at: str = Field(min_length=8, max_length=512, repr=False) - cookies: NetSchoolCookiesIn - #: The version the server's own sign-in keeps for the SecurityWarning - #: acknowledgement and the logout. - ver: str | None = Field(default=None, max_length=32, pattern=r"^[A-Za-z0-9._-]+$") - #: The login's ``timeOut``. Stored and read by nothing (the keep-alive has - #: a floor of its own), so any non-negative integer is taken: refusing a - #: whole session over the unit of a field nobody reads would be absurd. - time_out: int | None = Field(default=None, ge=0, le=2_147_483_647) - - @field_validator("at") - @classmethod - def _one_header_value(cls, value: str) -> str: - # A line break here would be a second header on every read. - if not header_value_ok(value): - raise ValueError("not a header value") - return value - - -class _SessionIn(BaseModel): - """What every registration carries besides the session itself. - - ``extra="forbid"`` is the rule this endpoint exists for, not tidiness: a - ``password`` key is a 422, so no client can send one here, by mistake or - otherwise. - """ - - model_config = ConfigDict(extra="forbid") - - #: What the person typed into the phone's own form. Nothing upstream - #: vouches for it, so it only names the session: a login copied from - #: another family reaches nothing of theirs (#165), because what a session - #: reaches is what its own diary lists. - login: str = Field(min_length=3, max_length=200) - - @field_validator("login") - @classmethod - def _clean_login(cls, value: str) -> str: - return _clean_login_value(value) - - -class PetersburgSessionIn(_SessionIn): - provider: Literal["petersburg"] - credential: PetersburgCredentialIn - - -class NetSchoolSessionIn(_SessionIn): - provider: Literal["netschool"] - #: An allow-list key; one outside it, or a region that takes no password, - #: is a 422 from the route before any upstream call. - region: str = Field(pattern=_REGION_KEY) - #: The upstream school id («scid») the phone signed in with. - school_id: int = Field(ge=1, le=2_000_000_000) - credential: NetSchoolCredentialIn - - -#: The registration body, told apart by ``provider``. -DiarySessionBody = PetersburgSessionIn | NetSchoolSessionIn - - -class DiarySessionOut(DiaryLoginOut): - """Our bearer for a session the phone opened, and what the phone needs to - keep reading it. Never the upstream credential: that stays here, sealed. - - ``token`` and ``login`` sit where ``DiaryLoginOut`` has them, so an app - decodes both answers the same way. - """ - - provider: Literal["petersburg", "netschool"] - region: str | None = None - school_id: int | None = None - #: What the diary calls the school, where it says (``None`` for Petersburg). - school_name: str | None = None - #: The zone the diary cuts its days at — the same rule the server's own - #: «today» uses for this session (`services/diary.zone_for`). - zone: str - #: The pupils the validating read already fetched, so the phone does not - #: ask again straight away. - students: list[DiaryStudentOut] = Field(default_factory=list) - - -class PetersburgCapabilitiesOut(BaseModel): - """Nothing to say yet about Petersburg beyond that it is served.""" - - -class NetSchoolCapabilitiesOut(BaseModel): - #: The allow-list keys this server signs in to with a password. - regions: list[str] = Field(default_factory=list) - - -class DiaryProvidersOut(BaseModel): - petersburg: PetersburgCapabilitiesOut = Field(default_factory=PetersburgCapabilitiesOut) - netschool: NetSchoolCapabilitiesOut = Field(default_factory=NetSchoolCapabilitiesOut) - - -class DiaryCapabilitiesOut(BaseModel): - """What this server's diary can do, asked before the phone takes a password. - - ``enabled`` is false without ``DIARY_SECRET``; ``registration`` says the - server takes a session the phone opened (a server from before this answers - 404 here instead). - """ - - enabled: bool - registration: bool = True - providers: DiaryProvidersOut = Field(default_factory=DiaryProvidersOut) - - -class DiaryPeriodOut(BaseModel): - id: int - name: str - starts_on: Date | None = None - ends_on: Date | None = None - is_current: bool = False - - @classmethod - def of(cls, period) -> DiaryPeriodOut: - return cls( - id=period.id, - name=period.name, - starts_on=period.starts_on, - ends_on=period.ends_on, - is_current=period.is_current, - ) - - -class DiarySubjectOut(BaseModel): - id: int | None = None - name: str - - @classmethod - def of(cls, subject) -> DiarySubjectOut: - return cls(id=subject.id, name=subject.name) - - -class DiaryTeacherOut(BaseModel): - id: int | None = None - name: str - position: str | None = None - subjects: list[str] = [] - - @classmethod - def of(cls, teacher) -> DiaryTeacherOut: - return cls( - id=teacher.id, - name=teacher.name, - position=teacher.position, - subjects=list(teacher.subjects), - ) - - -class DiaryMarkOut(BaseModel): - """One register entry. - - ``value`` is what belongs in the cell and ``kind`` says what it means, so a - client can colour an absence differently without knowing that upstream it - was type code 30000. - """ - - id: int | None = None - subject_id: int | None = None - subject: str - date: Date | None = None - value: str - kind: str - reason: str | None = None - comment: str | None = None - - @classmethod - def of(cls, mark) -> DiaryMarkOut: - return cls( - id=mark.id, - subject_id=mark.subject_id, - subject=mark.subject_name, - date=mark.date, - value=mark.value, - kind=mark.kind.value, - reason=mark.reason, - comment=mark.comment, - ) - - -class DiaryEditOut(BaseModel): - """One field a family has corrected, as the client needs to draw it. - - ``original`` is what the diary says **now**, not what it said when the - correction was written — the client shows it as «в дневнике: …», and the - question it answers is what is currently being covered up. - """ - - field: str - value: str - original: str | None = None - #: The diary has changed this field since the correction was made, so the - #: value being hidden is no longer the one the person decided to replace. - changed_upstream: bool = False - - @classmethod - def of(cls, edit) -> DiaryEditOut: - return cls( - field=edit.field, - value=edit.value, - original=edit.original, - changed_upstream=edit.changed_upstream, - ) - - -class DiaryLessonOut(BaseModel): - date: Date - number: int | None = None - subject: str - starts_at: Time | None = None - ends_at: Time | None = None - room: str | None = None - teacher: str | None = None - homework: str | None = None - topic: str | None = None - #: The key a correction for this lesson is filed under. Sent down so the - #: client echoes it back rather than building its own: two implementations - #: of a key that has to match exactly would agree until the first lesson - #: with no number, and then quietly stop. - target: str = "" - edits: list[DiaryEditOut] = Field(default_factory=list) - #: Another lesson the same day carries the same key, so no correction is - #: applied to either. See ``services/diary_overrides.lesson_target``. - ambiguous: bool = False - - @classmethod - def of(cls, overlaid) -> DiaryLessonOut: - lesson = overlaid.lesson - return cls( - date=lesson.date, - number=lesson.number, - subject=lesson.subject, - starts_at=lesson.starts_at, - ends_at=lesson.ends_at, - room=lesson.room, - teacher=lesson.teacher, - homework=lesson.homework, - topic=lesson.topic, - target=overlaid.target, - edits=[DiaryEditOut.of(edit) for edit in overlaid.edits], - ambiguous=overlaid.ambiguous, - ) - - -class DiaryHomeworkOut(BaseModel): - id: int | None = None - due_date: Date - subject: str - text: str - teacher: str | None = None - #: @see DiaryLessonOut.target - target: str = "" - edits: list[DiaryEditOut] = Field(default_factory=list) - #: Another item due the same day shares this key — two assignments in one - #: subject, neither carrying an upstream id — so no correction is applied to - #: either. @see DiaryLessonOut.ambiguous - ambiguous: bool = False - - @classmethod - def of(cls, overlaid) -> DiaryHomeworkOut: - item = overlaid.item - return cls( - id=item.id, - due_date=item.due_date, - subject=item.subject, - text=item.text, - teacher=item.teacher, - target=overlaid.target, - edits=[DiaryEditOut.of(edit) for edit in overlaid.edits], - ambiguous=overlaid.ambiguous, - ) - - -class DiaryResetIn(BaseModel): - """Which correction to take off. - - A body rather than a query string, and a POST rather than a DELETE, because - a target is free text: a subject named «Физика & астрономия» produces a key - with an ampersand in it, and a caller that encodes it a shade imperfectly - resets nothing while being told 204. The value that has to match byte for - byte does not travel in a URL. - """ - - target: str = Field(min_length=1, max_length=300) - field: str = Field(min_length=1, max_length=40) - - -class DiaryOverrideIn(BaseModel): - """A correction being written. The target came from a read; it is echoed.""" - - target: str = Field(min_length=1, max_length=300) - field: str = Field(min_length=1, max_length=40) - #: Empty is a real answer — the diary often carries a placeholder where a - #: family would rather see nothing — so it is stored rather than treated as - #: a reset. Resetting is ``POST .../overrides/reset``, which names the - #: target and field in a body; it used to be a ``DELETE`` with them in the - #: query string, and a target is a colon-joined string with a subject name - #: in it, which is the kind of thing a proxy log truncates and an ``&`` in - #: a subject silently cuts in half. - value: str = Field(max_length=4000) - #: What the person was looking at when they wrote the correction. - #: - #: Taken from the client rather than re-read upstream, and deliberately: the - #: question it exists to answer is "has the diary changed since the person - #: decided to replace this", and the answer is about what *they* saw, not - #: about what the upstream happened to say in the second this request - #: landed. The row is shared by everyone whose diary lists the child, so - #: the last writer's ``original`` is what everybody's ``changed_upstream`` - #: is measured against — and still there is no boundary here to defend: - #: whoever can write it sees the child in their own diary and could write - #: the value itself, and a wrong ``original`` only raises or lowers a flag - #: that is drawn beside the diary's own current answer. - original: str | None = Field(default=None, max_length=4000) - - -class DiaryOverrideOut(BaseModel): - """A stored correction, for the screen that lists and resets them.""" - - target: str - field: str - value: str - #: What the diary said **when this was written** — not what it says now. - #: - #: Spelled differently from :attr:`DiaryEditOut.original` on purpose. The - #: two are the same feature, travel to the same client and mean opposite - #: things: one is the value currently being covered up, this one is the - #: value the person decided to replace, however long ago. One name for both - #: is a client rendering «в дневнике: …» from whichever it happened to have. - original_when_written: str | None = None - updated_at: datetime - - @classmethod - def of(cls, row) -> DiaryOverrideOut: - return cls( - target=row.target, - field=row.field, - value=row.value, - original_when_written=row.original, - updated_at=row.updated_at, - ) - - -class DiaryAttendanceOut(BaseModel): - at: datetime - direction: str - - @classmethod - def of(cls, event) -> DiaryAttendanceOut: - return cls(at=event.at, direction=event.direction) - - -# --------------------------------------------------------------------------- -# Managing the class -# -# The phone's half of the bot's /class, /subjects, /bells, /devices, /log, -# /stats, /export and /import. Nothing here carries the caller's own role or -# class: both are derived server-side from the bearer token and the Telegram -# account it is linked to, so what the client believes about itself has never -# been part of this contract. -# -# Timestamps on this surface are class wall time, like every other clock the -# app is given - the audit log is read by a person sitting in the class's own -# zone, not by one sitting next to the server. -# --------------------------------------------------------------------------- - - -#: The bot's own spelling of a colour, so the two surfaces store one format. -_COLOUR_RE = re.compile(r"^#?([0-9a-fA-F]{6})$") - - -def _clean_colour(value: str | None) -> str | None: - """``#5b6abf`` / ``5B6ABF`` -> ``#5B6ABF``; a dash or blank clears it. - - One spelling in the database is what lets the app compare a lesson's colour - against a palette entry without normalising first, and it is what the - bot's colour picker already writes. - """ - if value is None: - return None - raw = value.strip() - if raw in {"", "-", "—"}: - return None - match = _COLOUR_RE.match(raw) - if match is None: - raise ValueError("colour must be six hex digits, as #5B6ABF") - return f"#{match.group(1).upper()}" - - -class ManagedClassOut(BaseModel): - """The class card the bot draws under «⚙️ Класс», as data. - - ``join_code`` is in here because the card shows it: this endpoint is - admin-only, and the code is what an admin reads out to the class. - """ - - id: int - name: str - school: str | None = None - city: str | None = None - timezone: str - # «МСК+2 (UTC+5) · Екатеринбург» - the same label the bot prints, so the - # app does not have to carry the table of Russian zones twice. - timezone_label: str - join_code: str - #: "open" | "invite" — whether that code is enough on its own. - join_mode: str = "open" - members: int - devices: int - pending_requests: int - bell_schedule_id: int | None = None - calendar_ready: bool = False - - -class TermSchemeIn(BaseModel): - """Switch the class between quarters and half-years.""" - - kind: Literal["quarter", "semester"] - - -class TermBoundsIn(BaseModel): - """Both edges of one term. Validated against the year in the service, not - here: «пересекается с периодом 2» is a rule about the other rows, and - pydantic can only see this one.""" - - starts_on: Date - ends_on: Date - - -class TermsOut(BaseModel): - kind: Literal["quarter", "semester"] - year: int - terms: list[TermOut] = Field(default_factory=list) - - -class SchoolOut(BaseModel): - """One row of the school directory, as the picker shows it.""" - - name: str - full_name: str - #: The OGRN, a Russian company registration number — thirteen digits, - #: assigned once and never reused. Returned so a - #: client can tell two «Гимназия № 3» apart without parsing the address. - ogrn: str | None = None - inn: str | None = None - address: str | None = None - city: str | None = None - region: str | None = None - #: False for a school the register has closed. Shown rather than hidden: - #: a class created in May may belong to one merged over the summer. - active: bool = True - - -class SchoolSearchOut(BaseModel): - """One page of results, and whether there is more behind it. - - ``truncated`` is not «есть ещё страницы» — those are ``pages``. It means - the directory's own ceiling of twenty was reached, so this is the first - twenty of an unknown number and the way forward is a longer query, not a - next page. A client that ignores it will show «найдено 20» for a search - matching three hundred schools. - """ - - items: list[SchoolOut] = Field(default_factory=list) - page: int - pages: int - total: int - truncated: bool = False - - -class ClassPatch(BaseModel): - """Only the fields present are changed; ``null`` clears a nullable one. - - ``name`` and ``timezone`` are not nullable: the name is what every message - calls this class and what the delete confirmation is typed against, and a - class with no zone would have no "today". - """ - - name: str | None = Field(default=None, min_length=1, max_length=64) - # 1..11. The bound is the school's, not the column's: a class numbered 0 or - # 12 would resolve its term scheme from a comparison that happens to be - # true rather than from a decision. - grade: int | None = Field(default=None, ge=1, le=11) - letter: str | None = Field(default=None, max_length=8) - school: str | None = Field(default=None, max_length=200) - city: str | None = Field(default=None, max_length=120) - timezone: str | None = Field(default=None, max_length=64) - #: Who vouches for a phone: the class code, or the bot. See ``JoinMode``. - #: A literal rather than the enum so an unknown value is a 422 with the - #: field named, not a 500 from deep inside SQLAlchemy. - join_mode: Literal["open", "invite"] | None = None - - # An absent field is never validated, so these two run only on a value the - # client actually sent - which is how an explicit ``null`` is refused while - # "leave it alone" stays the default. - @field_validator("name", "timezone") - @classmethod - def _required_when_present(cls, value: str | None) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("must not be blank") - return cleaned - - _clean_school = field_validator("school")(_clean_optional_text) - _clean_city = field_validator("city")(_clean_optional_text) - - -class ClassDeleteIn(BaseModel): - """The class's own name, typed back. - - The same confirmation the bot asks for, and for the same reason: a «вы - уверены?» button is pressed by the same thumb that pressed the one before - it, while a name has to be read off the screen first. - """ - - confirm_name: str = Field(min_length=1, max_length=64) - - -class ManagedSubjectOut(SubjectOut): - """A subject with its id. The read-only dictionary in ``GET /subjects`` is - keyed by name because that is what a lesson stores; management addresses a - row, which needs the id.""" - - id: int - - -class SubjectIn(BaseModel): - name: str = Field(min_length=1, max_length=120) - short_name: str | None = Field(default=None, max_length=16) - teacher: str | None = Field(default=None, max_length=120) - color: str | None = Field(default=None, max_length=9) - - @field_validator("name") - @classmethod - def _clean_name(cls, value: str) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("name must not be blank") - return cleaned - - _clean_short = field_validator("short_name")(_clean_optional_text) - _clean_teacher = field_validator("teacher")(_clean_optional_text) - _clean_color = field_validator("color")(_clean_colour) - - -class SubjectPatch(BaseModel): - """Only the fields present are changed; ``null`` clears a nullable one. - ``name`` is the rename, and it carries the timetable with it.""" - - name: str | None = Field(default=None, min_length=1, max_length=120) - short_name: str | None = Field(default=None, max_length=16) - teacher: str | None = Field(default=None, max_length=120) - color: str | None = Field(default=None, max_length=9) - - # Sent, so it is validated; absent, so it is not. A subject with no name - # would be a lesson that cannot be spelled. - @field_validator("name") - @classmethod - def _name_when_present(cls, value: str | None) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("name must not be blank") - return cleaned - - _clean_short = field_validator("short_name")(_clean_optional_text) - _clean_teacher = field_validator("teacher")(_clean_optional_text) - _clean_color = field_validator("color")(_clean_colour) - - -class SubjectSavedOut(BaseModel): - """``moved`` is how many timetable, homework and substitution rows a rename - carried with it - zero for every other kind of edit, and the number an - admin needs to believe the rename actually happened.""" - - subject: ManagedSubjectOut - moved: int = 0 - - -class BellPeriodIn(BaseModel): - index: int = Field(ge=1, le=20) - starts_at: Time - ends_at: Time - - @model_validator(mode="after") - def _ends_after_start(self) -> BellPeriodIn: - if self.ends_at <= self.starts_at: - raise ValueError("ends_at must be after starts_at") - return self - - -class BellPeriodOut(BaseModel): - index: int - starts_at: Time - ends_at: Time - - -class BellScheduleOut(BaseModel): - id: int - name: str - # The one the class runs on when no day says otherwise. - is_default: bool = False - periods: list[BellPeriodOut] = [] - #: Lessons this write stopped ringing, counted in rows rather than in - #: numbers — one number under two weekdays is two lessons nobody will see. - #: - #: Shrinking a schedule, or pointing the class at a shorter one, leaves - #: every row past the new last rung stored and drawn nowhere. The bot says - #: so in an alert the moment it happens; the API wrote the same count into - #: the audit log and answered the caller with a schedule that looked - #: entirely fine, so an admin editing bells from the phone lost six - #: lessons and was told nothing until they went looking for the log. Zero - #: on every read and on every write that silenced nothing, which is almost - #: all of them. - silenced_lessons: int = 0 - - -class BellPeriodsIn(BaseModel): - """At least one row, always. - - The stored schedule is the thing a class runs on, and an empty list is far - more likely to be a client bug than somebody meaning "no bells at all" - - which is what the bot's «пустой присылкой звонки не стереть» says too. - """ - - periods: list[BellPeriodIn] = Field(min_length=1, max_length=20) - - @model_validator(mode="after") - def _indexes_are_unique(self) -> BellPeriodsIn: - seen = {period.index for period in self.periods} - if len(seen) != len(self.periods): - raise ValueError("lesson numbers must not repeat") - return self - - -class BellScheduleIn(BaseModel): - name: str = Field(min_length=1, max_length=64) - # Optional here, unlike on the periods endpoint: a schedule may be created - # empty and filled in afterwards. - periods: list[BellPeriodIn] = Field(default=[], max_length=20) - - @field_validator("name") - @classmethod - def _clean_name(cls, value: str) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("name must not be blank") - return cleaned - - @model_validator(mode="after") - def _indexes_are_unique(self) -> BellScheduleIn: - seen = {period.index for period in self.periods} - if len(seen) != len(self.periods): - raise ValueError("lesson numbers must not repeat") - return self - - -class BellSchedulePatch(BaseModel): - name: str | None = Field(default=None, min_length=1, max_length=64) - # ``true`` makes this the class default. ``false`` is refused rather than - # silently leaving the class with none: something has to be the default. - is_default: bool | None = None - - @field_validator("name") - @classmethod - def _name_when_present(cls, value: str | None) -> str: - cleaned = _clean_optional_text(value) - if cleaned is None: - raise ValueError("name must not be blank") - return cleaned - - -class TimetableExportOut(BaseModel): - """The whole weekly template in the bot's paste format. - - Byte-for-byte what «📤 Экспорт» sends, so a text saved from the bot can be - imported by the app and the other way round. - """ - - text: str - lessons: int - - -class TimetableImportIn(BaseModel): - text: str = Field(min_length=1, max_length=20000) - # Whether to overwrite weekdays that already have lessons. Without it an - # import that would replace something answers with the conflicts instead. - replace: bool = False - - -class ImportConflictOut(BaseModel): - """One weekday the paste would overwrite: what is there now, what would - replace it. Weekday is 1=Monday .. 7=Sunday, as everywhere else.""" - - weekday: int - existing: int - incoming: int - - -class TimetableImportOut(BaseModel): - """``applied: false`` means nothing was written - either the paste held no - day the parser recognised, or it collided and ``replace`` was not set.""" - - applied: bool - days: list[int] = [] - lessons: int = 0 - bells: int = 0 - conflicts: list[ImportConflictOut] = [] - # Lines the parser could not read. Echoed back so an admin can fix the two - # that were typos rather than re-reading the whole paste. - rejected: list[str] = [] - - -class ManagedDeviceOut(BaseModel): - """One phone on the class's list. - - ``owner`` is a display name, never the Telegram id: an admin needs to know - whose phone this is, and that is the whole of what they need. - """ - - id: int - device_name: str | None = None - linked: bool = False - owner: str | None = None - role: RoleName | None = None - revoked: bool = False - created_at: datetime | None = None - last_seen_at: datetime | None = None - linked_at: datetime | None = None - - -class AuditEntryOut(BaseModel): - id: int - # Machine tag: homework.add, subject.rename, timetable.import, ... - action: str - summary: str - who: str | None = None - at: datetime | None = None - - -class AuditPageOut(BaseModel): - """``has_more`` rather than a total: the log is append-only and unbounded, - and a count of it would be a full scan on every page turn.""" - - entries: list[AuditEntryOut] = [] - limit: int - offset: int - has_more: bool = False - - -class SubjectHoursOut(BaseModel): - """Lessons a week. A subject that alternates weeks counts a half, which is - how a school's own paperwork writes «часов в неделю».""" - - name: str - hours: float - - -class StatsOut(BaseModel): - today: Date - lessons_per_week: float - subjects_count: int - subjects: list[SubjectHoursOut] = [] - homework_open: int - homework_total: int - members_by_role: dict[RoleName, int] = {} - devices_active: int - overrides_upcoming: int - events_upcoming: int - - -class AccessRequestOut(BaseModel): - id: int - who: str - requested_role: RoleName - message: str | None = None - created_at: datetime | None = None - - -class RequestDecisionIn(BaseModel): - """The role to grant. Absent means the one that was asked for, which is - what pressing «Выдать» in the bot does. Ignored when declining.""" - - role: RoleName | None = None - - -class RequestDecisionOut(BaseModel): - id: int - status: Literal["approved", "declined"] - # The role actually granted, or ``null`` for a declined request. - role: RoleName | None = None - who: str - - -# --------------------------------------------------------------------------- -# The school directory, anonymous: which regions a school may be in -# --------------------------------------------------------------------------- - - -class SchoolRegionOut(BaseModel): - """One region the search found schools in.""" - - #: The region catalog's key («tatarstan»), the one the phone's bundled copy - #: of the same catalog knows. ``null`` when the directory named a region - #: the catalog cannot place — then ``label`` says what it called it. - region: str | None = None - #: The two-digit subject code: the catalog's for a placed region, the - #: directory's own for one it could not place. - code: str | None = None - #: The directory's own name for the region («г Байконур»), and only for - #: an unplaced one: a placed region is named from the catalog, in the - #: reader's language. - label: str | None = None - #: Hits in this region among the twenty the directory returns at most. - schools: int - #: Up to three towns, best-ranked first. - cities: list[str] = Field(default_factory=list) - #: Up to three school names as a person writes them. - examples: list[str] = Field(default_factory=list) - - -class SchoolRegionsOut(BaseModel): - """What ``GET /api/v1/directory/school-regions`` answers. - - Picking the region from the list always works; this only saves the - scrolling. So every failure of it is a 503 that says «выберите регион из - списка», and an answer that places nothing is an empty list rather than - an error. - """ - - #: As searched: whitespace collapsed, cut to 150 characters. - query: str - #: Best-ranked region first, at most ten. - regions: list[SchoolRegionOut] = Field(default_factory=list) - #: The directory's own ceiling of twenty was reached, so these are the - #: regions of the first twenty matches, not of all of them. - truncated: bool = False - #: The name is too common to place — «школа № 5» is in every region. - #: Answered with no upstream call when the name is only a kind of school - #: and a small number; after one when twenty matches span four regions or - #: more. The phone says so and shows the list. - generic: bool = False diff --git a/server/app/schemas/__init__.py b/server/app/schemas/__init__.py new file mode 100644 index 00000000..2a89717c --- /dev/null +++ b/server/app/schemas/__init__.py @@ -0,0 +1,267 @@ +"""Wire format shared with the Android client. + +Field names are the contract. Anything renamed here must be renamed in +``core/network`` on the Android side and bumped in ``API_VERSION``. + +One module per area, because in one file a change to one entity meant reading +all the others (#208). Every public name is re-exported from here, so +``from app.schemas import X`` is still the one way in, and no caller had to +learn where a class went: + +- ``bundle`` — what the widget reads: the bundle, its days, lessons, events + and terms, ``/now`` and the calendar feed; ``API_VERSION`` and ``RoleName`` +- ``join`` — getting a phone into a class and linking it to an account +- ``homework`` and ``tasks`` — the class's homework and a person's own tasks +- ``subjects`` — the subject dictionary, read by every phone, managed by an + admin +- ``edit`` — substitutions, events and marked days, written from the phone +- ``cron`` — what one tick of the clock did +- ``diary_session`` and ``diary`` — signing in to the electronic diary, and + what it reads back with the corrections laid over it +- ``school_class``, ``bells``, ``timetable``, ``access`` and ``reports`` — + the management surface, below +- ``directory`` — the school directory +- ``_text`` — the cleaning every free-text field goes through + +Managing the class +------------------ + +The phone's half of the bot's /class, /subjects, /bells, /devices, /log, +/stats, /export and /import. Nothing there carries the caller's own role or +class: both are derived server-side from the bearer token and the Telegram +account it is linked to, so what the client believes about itself has never +been part of this contract. + +Timestamps on that surface are class wall time, like every other clock the +app is given - the audit log is read by a person sitting in the class's own +zone, not by one sitting next to the server. +""" + +from __future__ import annotations + +# Private, and re-exported only because tests/test_hardening.py reads it from +# here; the redundant alias is what marks it as meant. +from app.schemas._text import _clean_optional_text as _clean_optional_text +from app.schemas.access import ( + AccessRequestOut, + ManagedDeviceOut, + RequestDecisionIn, + RequestDecisionOut, +) +from app.schemas.bells import ( + BellPeriodIn, + BellPeriodOut, + BellPeriodsIn, + BellScheduleIn, + BellScheduleOut, + BellSchedulePatch, +) +from app.schemas.bundle import ( + API_VERSION, + BundleOut, + CalendarOut, + ClassOut, + DayOut, + DeviceOut, + EventOut, + HolidayOut, + HomeworkOut, + LessonOut, + NowOut, + NowState, + RoleName, + TermOut, +) +from app.schemas.cron import ( + TickOut, +) +from app.schemas.diary import ( + DiaryAttendanceOut, + DiaryEditOut, + DiaryHomeworkOut, + DiaryLessonOut, + DiaryMarkOut, + DiaryOverrideIn, + DiaryOverrideOut, + DiaryPeriodOut, + DiaryResetIn, + DiarySubjectOut, + DiaryTeacherOut, +) +from app.schemas.diary_session import ( + DiaryCapabilitiesOut, + DiaryLoginIn, + DiaryLoginOut, + DiaryProvidersOut, + DiarySessionBody, + DiarySessionOut, + DiaryStudentOut, + NetSchoolCapabilitiesOut, + NetSchoolCookiesIn, + NetSchoolCredentialIn, + NetSchoolSessionIn, + PetersburgCapabilitiesOut, + PetersburgCredentialIn, + PetersburgSessionIn, +) +from app.schemas.directory import ( + SchoolOut, + SchoolRegionOut, + SchoolRegionsOut, + SchoolSearchOut, +) +from app.schemas.edit import ( + DayIn, + DayKindName, + DayOverrideOut, + DeletedOut, + EventCreatedOut, + EventIn, + EventKindName, + OverrideActionName, + OverrideIn, + OverrideOut, +) +from app.schemas.homework import ( + DoneIn, + DoneOut, + HomeworkIn, + HomeworkItemOut, +) +from app.schemas.join import ( + DiaryBindingOut, + JoinRequest, + JoinResponse, + MeOut, + UnlinkOut, +) +from app.schemas.reports import ( + AuditEntryOut, + AuditPageOut, + StatsOut, + SubjectHoursOut, +) +from app.schemas.school_class import ( + ClassDeleteIn, + ClassPatch, + ManagedClassOut, + TermBoundsIn, + TermSchemeIn, + TermsOut, +) +from app.schemas.subjects import ( + ManagedSubjectOut, + SubjectIn, + SubjectOut, + SubjectPatch, + SubjectSavedOut, +) +from app.schemas.tasks import ( + TaskIn, + TaskOut, + TaskPatch, +) +from app.schemas.timetable import ( + ImportConflictOut, + TimetableExportOut, + TimetableImportIn, + TimetableImportOut, +) + +__all__ = [ + "API_VERSION", + "AccessRequestOut", + "AuditEntryOut", + "AuditPageOut", + "BellPeriodIn", + "BellPeriodOut", + "BellPeriodsIn", + "BellScheduleIn", + "BellScheduleOut", + "BellSchedulePatch", + "BundleOut", + "CalendarOut", + "ClassDeleteIn", + "ClassOut", + "ClassPatch", + "DayIn", + "DayKindName", + "DayOut", + "DayOverrideOut", + "DeletedOut", + "DeviceOut", + "DiaryAttendanceOut", + "DiaryBindingOut", + "DiaryCapabilitiesOut", + "DiaryEditOut", + "DiaryHomeworkOut", + "DiaryLessonOut", + "DiaryLoginIn", + "DiaryLoginOut", + "DiaryMarkOut", + "DiaryOverrideIn", + "DiaryOverrideOut", + "DiaryPeriodOut", + "DiaryProvidersOut", + "DiaryResetIn", + "DiarySessionBody", + "DiarySessionOut", + "DiaryStudentOut", + "DiarySubjectOut", + "DiaryTeacherOut", + "DoneIn", + "DoneOut", + "EventCreatedOut", + "EventIn", + "EventKindName", + "EventOut", + "HolidayOut", + "HomeworkIn", + "HomeworkItemOut", + "HomeworkOut", + "ImportConflictOut", + "JoinRequest", + "JoinResponse", + "LessonOut", + "ManagedClassOut", + "ManagedDeviceOut", + "ManagedSubjectOut", + "MeOut", + "NetSchoolCapabilitiesOut", + "NetSchoolCookiesIn", + "NetSchoolCredentialIn", + "NetSchoolSessionIn", + "NowOut", + "NowState", + "OverrideActionName", + "OverrideIn", + "OverrideOut", + "PetersburgCapabilitiesOut", + "PetersburgCredentialIn", + "PetersburgSessionIn", + "RequestDecisionIn", + "RequestDecisionOut", + "RoleName", + "SchoolOut", + "SchoolRegionOut", + "SchoolRegionsOut", + "SchoolSearchOut", + "StatsOut", + "SubjectHoursOut", + "SubjectIn", + "SubjectOut", + "SubjectPatch", + "SubjectSavedOut", + "TaskIn", + "TaskOut", + "TaskPatch", + "TermBoundsIn", + "TermOut", + "TermSchemeIn", + "TermsOut", + "TickOut", + "TimetableExportOut", + "TimetableImportIn", + "TimetableImportOut", + "UnlinkOut", +] diff --git a/server/app/schemas/_text.py b/server/app/schemas/_text.py new file mode 100644 index 00000000..90750efb --- /dev/null +++ b/server/app/schemas/_text.py @@ -0,0 +1,50 @@ +"""The cleaning every free-text field of the wire format goes through. + +Shared by the modules beside this one rather than repeated in each, because a +name is compared as text in places that cannot see each other: two spellings of +one cleaning are two subjects that look like one. +""" + +from __future__ import annotations + + +def _strip_control_chars(value: str) -> str: + """Drop anything unprintable, including NUL. + + ``device_name`` and ``code`` are client-supplied and land in a database + column. Postgres rejects NUL inside text outright, so a device that sent one + got a 500 out of what should be a clean request. + """ + return "".join(ch for ch in value if ch == " " or ch.isprintable()) + + +def _clean_optional_text(value: str | None) -> str | None: + """One line, single-spaced, or ``None``. + + Runs of whitespace are collapsed, not merely trimmed at the ends, because + the bot has always done exactly that - ``" ".join(text.split())`` on every + name it is typed - and a name is compared as text in three places that + cannot see each other: the uniqueness check that makes the subject + dictionary a dictionary, the rename that carries the timetable, the + homework and the substitutions along by name, and the widget's own matching. A + class where «Алгебра и начала» was added from the phone and «Алгебра и + начала» from the bot has two subjects that look like one, and a rename of + either moves none of the other's lessons. + + Every whitespace character becomes a space first, so a tab is a word break + rather than something ``_strip_control_chars`` silently deletes - it is + neither a space nor printable, so «а\tб» used to be stored as «аб». + """ + if value is None: + return None + spaced = "".join(" " if ch.isspace() else ch for ch in value) + return " ".join(_strip_control_chars(spaced).split()) or None + + +def _clean_notes(value: str | None) -> str | None: + """Notes keep their line breaks; everything else unprintable goes.""" + if value is None: + return None + cleaned = "".join(ch for ch in value if ch == "\n" or ch == " " or ch.isprintable()) + cleaned = cleaned.strip() + return cleaned or None diff --git a/server/app/schemas/access.py b/server/app/schemas/access.py new file mode 100644 index 00000000..03cf6afd --- /dev/null +++ b/server/app/schemas/access.py @@ -0,0 +1,58 @@ +"""Who may do what: the phones on the class's list, and a member asking for more. + +An access request is «Хочу редактировать» — a member asking the admins for a +higher role — not a request to join; joining is ``join``. + +Part of the management surface; what holds across it is in the package +docstring. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Literal + +from pydantic import BaseModel + +from app.schemas.bundle import RoleName + + +class ManagedDeviceOut(BaseModel): + """One phone on the class's list. + + ``owner`` is a display name, never the Telegram id: an admin needs to know + whose phone this is, and that is the whole of what they need. + """ + + id: int + device_name: str | None = None + linked: bool = False + owner: str | None = None + role: RoleName | None = None + revoked: bool = False + created_at: datetime | None = None + last_seen_at: datetime | None = None + linked_at: datetime | None = None + + +class AccessRequestOut(BaseModel): + id: int + who: str + requested_role: RoleName + message: str | None = None + created_at: datetime | None = None + + +class RequestDecisionIn(BaseModel): + """The role to grant. Absent means the one that was asked for, which is + what pressing «Выдать» in the bot does. Ignored when declining.""" + + role: RoleName | None = None + + +class RequestDecisionOut(BaseModel): + id: int + status: Literal["approved", "declined"] + # The role actually granted, or ``null`` for a declined request. + role: RoleName | None = None + who: str diff --git a/server/app/schemas/bells.py b/server/app/schemas/bells.py new file mode 100644 index 00000000..db664b3b --- /dev/null +++ b/server/app/schemas/bells.py @@ -0,0 +1,106 @@ +"""Managing the bell schedules a class runs on. + +Part of the management surface; what holds across it is in the package +docstring. +""" + +from __future__ import annotations + +from datetime import time as Time + +from pydantic import BaseModel, Field, field_validator, model_validator + +from app.schemas._text import _clean_optional_text + + +class BellPeriodIn(BaseModel): + index: int = Field(ge=1, le=20) + starts_at: Time + ends_at: Time + + @model_validator(mode="after") + def _ends_after_start(self) -> BellPeriodIn: + if self.ends_at <= self.starts_at: + raise ValueError("ends_at must be after starts_at") + return self + + +class BellPeriodOut(BaseModel): + index: int + starts_at: Time + ends_at: Time + + +class BellScheduleOut(BaseModel): + id: int + name: str + # The one the class runs on when no day says otherwise. + is_default: bool = False + periods: list[BellPeriodOut] = [] + #: Lessons this write stopped ringing, counted in rows rather than in + #: numbers — one number under two weekdays is two lessons nobody will see. + #: + #: Shrinking a schedule, or pointing the class at a shorter one, leaves + #: every row past the new last rung stored and drawn nowhere. The bot says + #: so in an alert the moment it happens; the API wrote the same count into + #: the audit log and answered the caller with a schedule that looked + #: entirely fine, so an admin editing bells from the phone lost six + #: lessons and was told nothing until they went looking for the log. Zero + #: on every read and on every write that silenced nothing, which is almost + #: all of them. + silenced_lessons: int = 0 + + +class BellPeriodsIn(BaseModel): + """At least one row, always. + + The stored schedule is the thing a class runs on, and an empty list is far + more likely to be a client bug than somebody meaning "no bells at all" - + which is what the bot's «пустой присылкой звонки не стереть» says too. + """ + + periods: list[BellPeriodIn] = Field(min_length=1, max_length=20) + + @model_validator(mode="after") + def _indexes_are_unique(self) -> BellPeriodsIn: + seen = {period.index for period in self.periods} + if len(seen) != len(self.periods): + raise ValueError("lesson numbers must not repeat") + return self + + +class BellScheduleIn(BaseModel): + name: str = Field(min_length=1, max_length=64) + # Optional here, unlike on the periods endpoint: a schedule may be created + # empty and filled in afterwards. + periods: list[BellPeriodIn] = Field(default=[], max_length=20) + + @field_validator("name") + @classmethod + def _clean_name(cls, value: str) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("name must not be blank") + return cleaned + + @model_validator(mode="after") + def _indexes_are_unique(self) -> BellScheduleIn: + seen = {period.index for period in self.periods} + if len(seen) != len(self.periods): + raise ValueError("lesson numbers must not repeat") + return self + + +class BellSchedulePatch(BaseModel): + name: str | None = Field(default=None, min_length=1, max_length=64) + # ``true`` makes this the class default. ``false`` is refused rather than + # silently leaving the class with none: something has to be the default. + is_default: bool | None = None + + @field_validator("name") + @classmethod + def _name_when_present(cls, value: str | None) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("name must not be blank") + return cleaned diff --git a/server/app/schemas/bundle.py b/server/app/schemas/bundle.py new file mode 100644 index 00000000..604db6bb --- /dev/null +++ b/server/app/schemas/bundle.py @@ -0,0 +1,163 @@ +"""What the widget reads: the bundle, the days in it, and ``/now``. + +``API_VERSION`` lives here because the bundle is what carries it. ``RoleName`` +lives here because ``DeviceOut`` is where a role first reaches the client; the +management modules take it from here rather than spelling the four roles again. +The calendar feed's answer is here too — it is another way to read these days. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import time as Time +from typing import Literal + +from pydantic import BaseModel, Field + +API_VERSION = 1 + + +class LessonOut(BaseModel): + index: int + subject: str + starts_at: Time + ends_at: Time + room: str | None = None + teacher: str | None = None + color: str | None = None + is_replaced: bool = False + is_cancelled: bool = False + note: str | None = None + + +class EventOut(BaseModel): + title: str + kind: str + starts_at: Time + ends_at: Time + location: str | None = None + covers_lesson: bool = False + + +class HomeworkOut(BaseModel): + subject: str + text: str + attachment_url: str | None = None + + +class HolidayOut(BaseModel): + """A named date, whether or not it stops the lessons. + + ``code`` is stable and ``title`` is Russian, the way every other string the + server puts on a screen is. A client that wants the name in its own + language matches the code and falls back to the title, so a date this + server learns before that client does still has something to draw. + """ + + code: str + title: str + #: True only for a statutory non-working day, and then the day has no + #: lessons. False for an observance — «День учителя» is a full Wednesday. + stops_lessons: bool + + +class DayOut(BaseModel): + date: Date + weekday: int + kind: str + lessons: list[LessonOut] = [] + events: list[EventOut] = [] + homework: list[HomeworkOut] = [] + note: str | None = None + #: What this date is called, if it is called anything. + holiday: HolidayOut | None = None + #: Why there are no lessons, when the timetable was not what decided it: + #: `out_of_year`, `between_terms` or `public_holiday`. Null on an ordinary + #: day, including an ordinary empty one — «nobody put lessons on a Sunday» + #: is not a reason, it is the absence of one. + #: + #: Added beside `kind` rather than folded into it: all three arrive as + #: `holiday` today, and a client that has never heard of this field keeps + #: drawing what it drew. What it buys the ones that have is four different + #: accents on a calendar instead of one. + off_reason: str | None = None + + +class TermOut(BaseModel): + """One quarter or half-year, as the class actually runs it.""" + + index: int + kind: Literal["quarter", "semester"] + starts_on: Date + ends_on: Date + + +class ClassOut(BaseModel): + id: int + name: str + # The year of school, 1..11, and the letter that distinguishes two classes + # of the same year. Null on a class created before they existed: its name + # is all there is, and «9» read out of «9А» would be a guess. + grade: int | None = None + letter: str | None = None + school: str | None = None + city: str | None = None + timezone: str + #: Which scheme the year is cut into, and the terms themselves — the app + #: renders «2 четверть» and shades the calendar from these rather than + #: recomputing dates a school is free to have moved. + term_kind: Literal["quarter", "semester"] | None = None + terms: list[TermOut] = Field(default_factory=list) + + +RoleName = Literal["viewer", "editor", "admin", "owner"] + + +class DeviceOut(BaseModel): + """What this device may do. Never carries the Telegram id it is linked to: + the app shows a name and a role, and the id is nobody's business.""" + + linked: bool = False + role: RoleName | None = None + can_edit: bool = False + + +class BundleOut(BaseModel): + """One response holds everything the widget needs to run offline for two weeks.""" + + api_version: int = API_VERSION + school_class: ClassOut + generated_at: str + days: list[DayOut] + next_school_day: DayOut | None = None + # Added in the same API version: absent for a client that predates it, and + # ``None`` is what such a client's mapper ignores. + device: DeviceOut | None = None + + +NowState = Literal["before_school", "lesson", "break", "after_school", "day_off", "no_data"] + + +class NowOut(BaseModel): + """The server's answer to "what is happening right now", in the class's zone. + + The widget normally computes this from the bundle itself; the endpoint is + for clients that would rather ask than carry the resolver, and it is what + the bundle's own maths is checked against. + """ + + date: Date + time: Time + state: NowState + current: LessonOut | None = None + next: LessonOut | None = None + # Seconds to the next boundary: the end of ``current`` during a lesson, + # the start of ``next`` before school and in a break. ``None`` when the + # school day is over or never started. + until_next_seconds: int | None = None + # The first day with lessons strictly after today. + next_school_day: Date | None = None + + +class CalendarOut(BaseModel): + url: str diff --git a/server/app/schemas/cron.py b/server/app/schemas/cron.py new file mode 100644 index 00000000..4ac9a806 --- /dev/null +++ b/server/app/schemas/cron.py @@ -0,0 +1,25 @@ +"""What one call of ``/api/v1/cron/tick`` did — the clock the server does not have.""" + +from __future__ import annotations + +from pydantic import BaseModel + + +class TickOut(BaseModel): + morning: int + evening: int + tasks: int + failed: int + fsm_purged: int + join_attempts_purged: int + diary_sessions_purged: int = 0 + device_tokens_purged: int = 0 + diary_links_purged: int = 0 + device_invites_purged: int = 0 + #: The keep-alive that holds a «Сетевой город» session open across its short + #: idle window: how many were pinged alive, how many the upstream had already + #: dropped, and true when the keep-alive itself raised (isolated so a diary + #: fault never fails the whole tick and reddens the clock). + diary_sessions_kept_alive: int = 0 + diary_sessions_lost: int = 0 + diary_keepalive_failed: bool = False diff --git a/server/app/schemas/diary.py b/server/app/schemas/diary.py new file mode 100644 index 00000000..fb876e34 --- /dev/null +++ b/server/app/schemas/diary.py @@ -0,0 +1,262 @@ +"""The electronic diary: what it reads back, and the corrections over it. + +The wire shapes of ``/api/v1/diary``. Every one is built from a provider +model by its own ``of``, and that constructor is the seam: when the upstream +changes, the provider's mapper absorbs it, these classes do not move, and the +Android client never learns that anything happened. + +Signing in, and the session the phone registers, are in ``diary_session``. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import datetime +from datetime import time as Time + +from pydantic import BaseModel, Field + + +class DiaryPeriodOut(BaseModel): + id: int + name: str + starts_on: Date | None = None + ends_on: Date | None = None + is_current: bool = False + + @classmethod + def of(cls, period) -> DiaryPeriodOut: + return cls( + id=period.id, + name=period.name, + starts_on=period.starts_on, + ends_on=period.ends_on, + is_current=period.is_current, + ) + + +class DiarySubjectOut(BaseModel): + id: int | None = None + name: str + + @classmethod + def of(cls, subject) -> DiarySubjectOut: + return cls(id=subject.id, name=subject.name) + + +class DiaryTeacherOut(BaseModel): + id: int | None = None + name: str + position: str | None = None + subjects: list[str] = [] + + @classmethod + def of(cls, teacher) -> DiaryTeacherOut: + return cls( + id=teacher.id, + name=teacher.name, + position=teacher.position, + subjects=list(teacher.subjects), + ) + + +class DiaryMarkOut(BaseModel): + """One register entry. + + ``value`` is what belongs in the cell and ``kind`` says what it means, so a + client can colour an absence differently without knowing that upstream it + was type code 30000. + """ + + id: int | None = None + subject_id: int | None = None + subject: str + date: Date | None = None + value: str + kind: str + reason: str | None = None + comment: str | None = None + + @classmethod + def of(cls, mark) -> DiaryMarkOut: + return cls( + id=mark.id, + subject_id=mark.subject_id, + subject=mark.subject_name, + date=mark.date, + value=mark.value, + kind=mark.kind.value, + reason=mark.reason, + comment=mark.comment, + ) + + +class DiaryEditOut(BaseModel): + """One field a family has corrected, as the client needs to draw it. + + ``original`` is what the diary says **now**, not what it said when the + correction was written — the client shows it as «в дневнике: …», and the + question it answers is what is currently being covered up. + """ + + field: str + value: str + original: str | None = None + #: The diary has changed this field since the correction was made, so the + #: value being hidden is no longer the one the person decided to replace. + changed_upstream: bool = False + + @classmethod + def of(cls, edit) -> DiaryEditOut: + return cls( + field=edit.field, + value=edit.value, + original=edit.original, + changed_upstream=edit.changed_upstream, + ) + + +class DiaryLessonOut(BaseModel): + date: Date + number: int | None = None + subject: str + starts_at: Time | None = None + ends_at: Time | None = None + room: str | None = None + teacher: str | None = None + homework: str | None = None + topic: str | None = None + #: The key a correction for this lesson is filed under. Sent down so the + #: client echoes it back rather than building its own: two implementations + #: of a key that has to match exactly would agree until the first lesson + #: with no number, and then quietly stop. + target: str = "" + edits: list[DiaryEditOut] = Field(default_factory=list) + #: Another lesson the same day carries the same key, so no correction is + #: applied to either. See ``services/diary_overrides.lesson_target``. + ambiguous: bool = False + + @classmethod + def of(cls, overlaid) -> DiaryLessonOut: + lesson = overlaid.lesson + return cls( + date=lesson.date, + number=lesson.number, + subject=lesson.subject, + starts_at=lesson.starts_at, + ends_at=lesson.ends_at, + room=lesson.room, + teacher=lesson.teacher, + homework=lesson.homework, + topic=lesson.topic, + target=overlaid.target, + edits=[DiaryEditOut.of(edit) for edit in overlaid.edits], + ambiguous=overlaid.ambiguous, + ) + + +class DiaryHomeworkOut(BaseModel): + id: int | None = None + due_date: Date + subject: str + text: str + teacher: str | None = None + #: @see DiaryLessonOut.target + target: str = "" + edits: list[DiaryEditOut] = Field(default_factory=list) + #: Another item due the same day shares this key — two assignments in one + #: subject, neither carrying an upstream id — so no correction is applied to + #: either. @see DiaryLessonOut.ambiguous + ambiguous: bool = False + + @classmethod + def of(cls, overlaid) -> DiaryHomeworkOut: + item = overlaid.item + return cls( + id=item.id, + due_date=item.due_date, + subject=item.subject, + text=item.text, + teacher=item.teacher, + target=overlaid.target, + edits=[DiaryEditOut.of(edit) for edit in overlaid.edits], + ambiguous=overlaid.ambiguous, + ) + + +class DiaryResetIn(BaseModel): + """Which correction to take off. + + A body rather than a query string, and a POST rather than a DELETE, because + a target is free text: a subject named «Физика & астрономия» produces a key + with an ampersand in it, and a caller that encodes it a shade imperfectly + resets nothing while being told 204. The value that has to match byte for + byte does not travel in a URL. + """ + + target: str = Field(min_length=1, max_length=300) + field: str = Field(min_length=1, max_length=40) + + +class DiaryOverrideIn(BaseModel): + """A correction being written. The target came from a read; it is echoed.""" + + target: str = Field(min_length=1, max_length=300) + field: str = Field(min_length=1, max_length=40) + #: Empty is a real answer — the diary often carries a placeholder where a + #: family would rather see nothing — so it is stored rather than treated as + #: a reset. Resetting is ``POST .../overrides/reset``, which names the + #: target and field in a body; it used to be a ``DELETE`` with them in the + #: query string, and a target is a colon-joined string with a subject name + #: in it, which is the kind of thing a proxy log truncates and an ``&`` in + #: a subject silently cuts in half. + value: str = Field(max_length=4000) + #: What the person was looking at when they wrote the correction. + #: + #: Taken from the client rather than re-read upstream, and deliberately: the + #: question it exists to answer is "has the diary changed since the person + #: decided to replace this", and the answer is about what *they* saw, not + #: about what the upstream happened to say in the second this request + #: landed. The row is shared by everyone whose diary lists the child, so + #: the last writer's ``original`` is what everybody's ``changed_upstream`` + #: is measured against — and still there is no boundary here to defend: + #: whoever can write it sees the child in their own diary and could write + #: the value itself, and a wrong ``original`` only raises or lowers a flag + #: that is drawn beside the diary's own current answer. + original: str | None = Field(default=None, max_length=4000) + + +class DiaryOverrideOut(BaseModel): + """A stored correction, for the screen that lists and resets them.""" + + target: str + field: str + value: str + #: What the diary said **when this was written** — not what it says now. + #: + #: Spelled differently from :attr:`DiaryEditOut.original` on purpose. The + #: two are the same feature, travel to the same client and mean opposite + #: things: one is the value currently being covered up, this one is the + #: value the person decided to replace, however long ago. One name for both + #: is a client rendering «в дневнике: …» from whichever it happened to have. + original_when_written: str | None = None + updated_at: datetime + + @classmethod + def of(cls, row) -> DiaryOverrideOut: + return cls( + target=row.target, + field=row.field, + value=row.value, + original_when_written=row.original, + updated_at=row.updated_at, + ) + + +class DiaryAttendanceOut(BaseModel): + at: datetime + direction: str + + @classmethod + def of(cls, event) -> DiaryAttendanceOut: + return cls(at=event.at, direction=event.direction) diff --git a/server/app/schemas/diary_session.py b/server/app/schemas/diary_session.py new file mode 100644 index 00000000..f3fcfda5 --- /dev/null +++ b/server/app/schemas/diary_session.py @@ -0,0 +1,248 @@ +"""Signing in to the electronic diary, and what this server's diary can do. + +A password sign-in (``DiaryLoginIn``) and a session the phone opened with the +diary itself (``DiarySessionBody``) both end in our own bearer. What is read +through that bearer, and the corrections laid over it, are in ``diary``; what +that module says about ``of`` holds for ``DiaryStudentOut`` here too. +""" + +from __future__ import annotations + +import re +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from app.providers.diary.http import cookie_value_ok, header_value_ok +from app.schemas._text import _strip_control_chars + + +class DiaryLoginIn(BaseModel): + """Credentials, used once and never stored. + + ``login`` rather than ``email`` because the upstream accepts more than one + kind of identifier and calling it an email would be a promise this project + cannot keep. + """ + + login: str = Field(min_length=3, max_length=200) + password: str = Field(min_length=1, max_length=200) + #: Which diary. Absent means Petersburg, so an older phone that sends only a + #: login and a password still signs in there. For «Сетевой город» the region + #: is a key into the allow-list and the school is the upstream's own id; + #: both are validated in the route before any upstream call. + provider: str | None = Field(default=None, max_length=32) + region: str | None = Field(default=None, max_length=32) + school_id: int | None = Field(default=None, ge=1, le=2_000_000_000) + + @field_validator("login") + @classmethod + def _clean_login(cls, value: str) -> str: + return _clean_login_value(value) + + +def _clean_login_value(value: str) -> str: + """A login as the upstream will see it: printable, trimmed, three or more. + + Shared by the password sign-in and the registration of a phone's session, + because both write it to the same column and «Вход выполнен» prints it + from there — and the phone cleans it character for character the same way + (`DiaryLogin.clean`), so a login pasted with an invisible character is not + a wrong password on one side only. It keys nothing: corrections are filed + under the child (`services/diary.child_scope`). + """ + cleaned = _strip_control_chars(value).strip() + if len(cleaned) < 3: + raise ValueError("login must contain at least 3 usable characters") + return cleaned + + +class DiaryLoginOut(BaseModel): + token: str + login: str + + +class DiaryStudentOut(BaseModel): + id: int + first_name: str + last_name: str + middle_name: str | None = None + full_name: str + school: str | None = None + class_name: str | None = None + + @classmethod + def of(cls, student) -> DiaryStudentOut: + # Deliberately without ``education_id`` and ``group_id``: they are the + # upstream's handles, the server resolves them from the student id on + # every request, and a client that learned them would be a client that + # could be pointed at somebody else's child. + return cls( + id=student.id, + first_name=student.first_name, + last_name=student.last_name, + middle_name=student.middle_name, + full_name=student.full_name, + school=student.school, + class_name=student.class_name, + ) + + +#: Three dot-separated base64url parts, the last possibly empty: the shape of +#: the ``X-JWT-Token`` Petersburg issues. +_JWT = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*") + + +#: An allow-list key's shape. Whether it is *in* the allow-list is the route's +#: question, asked before any upstream call. +_REGION_KEY = r"^[a-z0-9-]{2,32}$" + + +class PetersburgCredentialIn(BaseModel): + """The session Petersburg handed the phone: the ``X-JWT-Token`` cookie, or + ``data.token`` when the answer carried no cookie.""" + + model_config = ConfigDict(extra="forbid") + + token: str = Field(min_length=16, max_length=4096, repr=False) + + @field_validator("token") + @classmethod + def _a_jwt_that_can_be_a_cookie(cls, value: str) -> str: + # Sent back upstream as a cookie on every read, so it must be one + # cookie value and nothing more; `_raw` checks the same again. + if not _JWT.fullmatch(value) or not cookie_value_ok(value): + raise ValueError("token must be a JWT") + return value + + +class NetSchoolCookiesIn(BaseModel): + """The two session cookies «Сетевой город» sets, and no other — an unknown + name is refused rather than carried, since it would be sent on every read.""" + + model_config = ConfigDict(extra="forbid") + + NSSESSIONID: str = Field(min_length=1, max_length=128, repr=False) + ESRNSec: str | None = Field(default=None, min_length=1, max_length=2048, repr=False) + + @field_validator("NSSESSIONID", "ESRNSec") + @classmethod + def _one_cookie_value(cls, value: str | None) -> str | None: + # A `;` here would smuggle a second cookie onto every read. + if value is not None and not cookie_value_ok(value): + raise ValueError("not a cookie value") + return value + + +class NetSchoolCredentialIn(BaseModel): + """What the phone's «Сетевой город» sign-in ended holding.""" + + model_config = ConfigDict(extra="forbid") + + #: The bearer, sent in the ``at`` header, so it must be one header value. + at: str = Field(min_length=8, max_length=512, repr=False) + cookies: NetSchoolCookiesIn + #: The version the server's own sign-in keeps for the SecurityWarning + #: acknowledgement and the logout. + ver: str | None = Field(default=None, max_length=32, pattern=r"^[A-Za-z0-9._-]+$") + #: The login's ``timeOut``. Stored and read by nothing (the keep-alive has + #: a floor of its own), so any non-negative integer is taken: refusing a + #: whole session over the unit of a field nobody reads would be absurd. + time_out: int | None = Field(default=None, ge=0, le=2_147_483_647) + + @field_validator("at") + @classmethod + def _one_header_value(cls, value: str) -> str: + # A line break here would be a second header on every read. + if not header_value_ok(value): + raise ValueError("not a header value") + return value + + +class _SessionIn(BaseModel): + """What every registration carries besides the session itself. + + ``extra="forbid"`` is the rule this endpoint exists for, not tidiness: a + ``password`` key is a 422, so no client can send one here, by mistake or + otherwise. + """ + + model_config = ConfigDict(extra="forbid") + + #: What the person typed into the phone's own form. Nothing upstream + #: vouches for it, so it only names the session: a login copied from + #: another family reaches nothing of theirs (#165), because what a session + #: reaches is what its own diary lists. + login: str = Field(min_length=3, max_length=200) + + @field_validator("login") + @classmethod + def _clean_login(cls, value: str) -> str: + return _clean_login_value(value) + + +class PetersburgSessionIn(_SessionIn): + provider: Literal["petersburg"] + credential: PetersburgCredentialIn + + +class NetSchoolSessionIn(_SessionIn): + provider: Literal["netschool"] + #: An allow-list key; one outside it, or a region that takes no password, + #: is a 422 from the route before any upstream call. + region: str = Field(pattern=_REGION_KEY) + #: The upstream school id («scid») the phone signed in with. + school_id: int = Field(ge=1, le=2_000_000_000) + credential: NetSchoolCredentialIn + + +#: The registration body, told apart by ``provider``. +DiarySessionBody = PetersburgSessionIn | NetSchoolSessionIn + + +class DiarySessionOut(DiaryLoginOut): + """Our bearer for a session the phone opened, and what the phone needs to + keep reading it. Never the upstream credential: that stays here, sealed. + + ``token`` and ``login`` sit where ``DiaryLoginOut`` has them, so an app + decodes both answers the same way. + """ + + provider: Literal["petersburg", "netschool"] + region: str | None = None + school_id: int | None = None + #: What the diary calls the school, where it says (``None`` for Petersburg). + school_name: str | None = None + #: The zone the diary cuts its days at — the same rule the server's own + #: «today» uses for this session (`services/diary.zone_for`). + zone: str + #: The pupils the validating read already fetched, so the phone does not + #: ask again straight away. + students: list[DiaryStudentOut] = Field(default_factory=list) + + +class PetersburgCapabilitiesOut(BaseModel): + """Nothing to say yet about Petersburg beyond that it is served.""" + + +class NetSchoolCapabilitiesOut(BaseModel): + #: The allow-list keys this server signs in to with a password. + regions: list[str] = Field(default_factory=list) + + +class DiaryProvidersOut(BaseModel): + petersburg: PetersburgCapabilitiesOut = Field(default_factory=PetersburgCapabilitiesOut) + netschool: NetSchoolCapabilitiesOut = Field(default_factory=NetSchoolCapabilitiesOut) + + +class DiaryCapabilitiesOut(BaseModel): + """What this server's diary can do, asked before the phone takes a password. + + ``enabled`` is false without ``DIARY_SECRET``; ``registration`` says the + server takes a session the phone opened (a server from before this answers + 404 here instead). + """ + + enabled: bool + registration: bool = True + providers: DiaryProvidersOut = Field(default_factory=DiaryProvidersOut) diff --git a/server/app/schemas/directory.py b/server/app/schemas/directory.py new file mode 100644 index 00000000..6b626ce0 --- /dev/null +++ b/server/app/schemas/directory.py @@ -0,0 +1,91 @@ +"""The school directory: a school found by name, and the regions it may be in. + +``SchoolOut`` and ``SchoolSearchOut`` answer an admin's search for the class's +school (``GET /api/v1/manage/schools``); ``SchoolRegionOut`` and +``SchoolRegionsOut`` answer the anonymous question of which regions a school +may be in. +""" + +from __future__ import annotations + +from pydantic import BaseModel, Field + + +class SchoolOut(BaseModel): + """One row of the school directory, as the picker shows it.""" + + name: str + full_name: str + #: The OGRN, a Russian company registration number — thirteen digits, + #: assigned once and never reused. Returned so a + #: client can tell two «Гимназия № 3» apart without parsing the address. + ogrn: str | None = None + inn: str | None = None + address: str | None = None + city: str | None = None + region: str | None = None + #: False for a school the register has closed. Shown rather than hidden: + #: a class created in May may belong to one merged over the summer. + active: bool = True + + +class SchoolSearchOut(BaseModel): + """One page of results, and whether there is more behind it. + + ``truncated`` is not «есть ещё страницы» — those are ``pages``. It means + the directory's own ceiling of twenty was reached, so this is the first + twenty of an unknown number and the way forward is a longer query, not a + next page. A client that ignores it will show «найдено 20» for a search + matching three hundred schools. + """ + + items: list[SchoolOut] = Field(default_factory=list) + page: int + pages: int + total: int + truncated: bool = False + + +class SchoolRegionOut(BaseModel): + """One region the search found schools in.""" + + #: The region catalog's key («tatarstan»), the one the phone's bundled copy + #: of the same catalog knows. ``null`` when the directory named a region + #: the catalog cannot place — then ``label`` says what it called it. + region: str | None = None + #: The two-digit subject code: the catalog's for a placed region, the + #: directory's own for one it could not place. + code: str | None = None + #: The directory's own name for the region («г Байконур»), and only for + #: an unplaced one: a placed region is named from the catalog, in the + #: reader's language. + label: str | None = None + #: Hits in this region among the twenty the directory returns at most. + schools: int + #: Up to three towns, best-ranked first. + cities: list[str] = Field(default_factory=list) + #: Up to three school names as a person writes them. + examples: list[str] = Field(default_factory=list) + + +class SchoolRegionsOut(BaseModel): + """What ``GET /api/v1/directory/school-regions`` answers. + + Picking the region from the list always works; this only saves the + scrolling. So every failure of it is a 503 that says «выберите регион из + списка», and an answer that places nothing is an empty list rather than + an error. + """ + + #: As searched: whitespace collapsed, cut to 150 characters. + query: str + #: Best-ranked region first, at most ten. + regions: list[SchoolRegionOut] = Field(default_factory=list) + #: The directory's own ceiling of twenty was reached, so these are the + #: regions of the first twenty matches, not of all of them. + truncated: bool = False + #: The name is too common to place — «школа № 5» is in every region. + #: Answered with no upstream call when the name is only a kind of school + #: and a small number; after one when twenty matches span four regions or + #: more. The phone says so and shows the list. + generic: bool = False diff --git a/server/app/schemas/edit.py b/server/app/schemas/edit.py new file mode 100644 index 00000000..5d982689 --- /dev/null +++ b/server/app/schemas/edit.py @@ -0,0 +1,109 @@ +"""Editing the class from the phone: substitutions, events and marked days. + +``DeletedOut`` is here and not in a module of its own; the management +endpoints answer a delete with it too. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import time as Time +from typing import Literal + +from pydantic import BaseModel, Field, field_validator, model_validator + +from app.schemas._text import _clean_optional_text + +OverrideActionName = Literal["replace", "cancel", "clear"] + + +class OverrideIn(BaseModel): + date: Date + index: int = Field(ge=1, le=20) + action: OverrideActionName + subject: str | None = Field(default=None, max_length=120) + room: str | None = Field(default=None, max_length=32) + teacher: str | None = Field(default=None, max_length=120) + note: str | None = Field(default=None, max_length=500) + + _clean_subject = field_validator("subject")(_clean_optional_text) + _clean_room = field_validator("room")(_clean_optional_text) + _clean_teacher = field_validator("teacher")(_clean_optional_text) + _clean_note = field_validator("note")(_clean_optional_text) + + @model_validator(mode="after") + def _replace_needs_something(self) -> OverrideIn: + # A replacement with nothing in it would be stored and then dropped by + # the resolver as a no-op; better to say so up front. + if self.action == "replace" and not (self.subject or self.room or self.teacher): + raise ValueError("replace needs a subject, a room or a teacher") + return self + + +class OverrideOut(BaseModel): + date: Date + index: int + action: OverrideActionName + subject: str | None = None + room: str | None = None + teacher: str | None = None + note: str | None = None + + +EventKindName = Literal["event", "canteen", "exam", "trip", "meeting"] + + +class EventIn(BaseModel): + date: Date + starts_at: Time + ends_at: Time + title: str = Field(min_length=1, max_length=200) + kind: EventKindName = "event" + location: str | None = Field(default=None, max_length=120) + # Defaults like the bot: only a «мероприятие» or a trip normally stands in + # for lessons; a canteen break sits in a break. + covers_lesson: bool | None = None + + @field_validator("title") + @classmethod + def _clean_title(cls, value: str) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("title must not be blank") + return cleaned + + _clean_location = field_validator("location")(_clean_optional_text) + + @model_validator(mode="after") + def _ends_after_start(self) -> EventIn: + if self.ends_at <= self.starts_at: + raise ValueError("ends_at must be after starts_at") + return self + + +class EventCreatedOut(BaseModel): + id: int + + +DayKindName = Literal["normal", "holiday", "shortened", "remote"] + + +class DayIn(BaseModel): + date: Date + kind: DayKindName + note: str | None = Field(default=None, max_length=500) + bell_schedule_id: int | None = None + + _clean_note = field_validator("note")(_clean_optional_text) + + +class DayOverrideOut(BaseModel): + date: Date + kind: DayKindName + note: str | None = None + bell_schedule_id: int | None = None + + +class DeletedOut(BaseModel): + id: int + deleted: bool = True diff --git a/server/app/schemas/homework.py b/server/app/schemas/homework.py new file mode 100644 index 00000000..27befacb --- /dev/null +++ b/server/app/schemas/homework.py @@ -0,0 +1,65 @@ +"""Homework on its own, outside a day: the list, the ticks, and a row written. + +The per-day shape the bundle carries, ``HomeworkOut``, is in ``bundle``; +``HomeworkItemOut`` is that shape with the id and the date added. +""" + +from __future__ import annotations + +from datetime import date as Date + +from pydantic import BaseModel, Field, field_validator + +from app.schemas._text import _clean_notes, _strip_control_chars +from app.schemas.bundle import HomeworkOut + + +class HomeworkItemOut(HomeworkOut): + """A homework row on its own, outside a day: the list and the ticks need + the id and the date that the bundle's per-day shape carries implicitly.""" + + id: int + due_date: Date + # This device's owner's tick. Always ``false`` for an unlinked device. + done: bool = False + + +class DoneIn(BaseModel): + done: bool + + +class DoneOut(BaseModel): + id: int + done: bool + + +class HomeworkIn(BaseModel): + due_date: Date + subject: str = Field(min_length=1, max_length=120) + text: str = Field(min_length=1, max_length=4000) + attachment_url: str | None = Field(default=None, max_length=500) + + @field_validator("subject") + @classmethod + def _clean_subject(cls, value: str) -> str: + cleaned = _strip_control_chars(value).strip() + if not cleaned: + raise ValueError("subject must not be blank") + return cleaned + + @field_validator("text") + @classmethod + def _clean_text(cls, value: str) -> str: + # Line breaks stay: «№ 12–15\nустно § 4» is how homework is written. + cleaned = _clean_notes(value) + if cleaned is None: + raise ValueError("text must not be blank") + return cleaned + + @field_validator("attachment_url") + @classmethod + def _clean_url(cls, value: str | None) -> str | None: + if value is None: + return None + cleaned = _strip_control_chars(value).strip() + return cleaned or None diff --git a/server/app/schemas/join.py b/server/app/schemas/join.py new file mode 100644 index 00000000..4700291f --- /dev/null +++ b/server/app/schemas/join.py @@ -0,0 +1,110 @@ +"""Getting a phone into a class, and linking it to an account. + +``POST /join`` takes the class code or a personal connect code in one field; +``/me`` and ``/me/unlink`` are what the phone asks afterwards. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from pydantic import BaseModel, Field, field_validator + +from app.schemas._text import _strip_control_chars +from app.schemas.bundle import RoleName + +if TYPE_CHECKING: + from app.providers.diary.registry import Binding + + +#: Mirrors ``JoinRequest.code``'s own ``min_length``; see ``_clean_code``. +_MIN_CODE_LENGTH = 4 + + +class JoinRequest(BaseModel): + code: str = Field(min_length=4, max_length=16) + device_name: str | None = Field(default=None, max_length=120) + + @field_validator("code") + @classmethod + def _clean_code(cls, value: str) -> str: + """Sanitise the code, and reject one that sanitises away to nothing. + + This used to share ``_sanitise`` with ``device_name`` and return + ``cleaned or None``. Pydantic does not re-check an after-validator's + return against the field's annotation, so a code of four spaces — which + passes ``min_length=4`` — arrived at the handler as ``None`` and the + ``.strip()`` there raised ``AttributeError``. That is a 500 out of a + request the schema exists to reject, on an unauthenticated endpoint. + """ + cleaned = _strip_control_chars(value).strip() + if len(cleaned) < _MIN_CODE_LENGTH: + raise ValueError("code must contain at least 4 usable characters") + return cleaned + + @field_validator("device_name") + @classmethod + def _clean_device_name(cls, value: str | None) -> str | None: + """Optional, so sanitising it away to nothing simply means absent.""" + if value is None: + return None + cleaned = _strip_control_chars(value).strip() + return cleaned or None + + +class DiaryBindingOut(BaseModel): + """Which diary a class reads, so a phone that joined it can sign in there + without searching for its school. + + Defined here rather than in the diary block below because + :class:`JoinResponse` carries it. Built only through ``of`` from + `registry.binding`, so a class bound to a region since dropped from the + allow-list, one that takes no password, or a «Сетевой город» binding with + no school all read as no binding at all — the phone is never pointed at a + diary this server would refuse. + """ + + provider: Literal["petersburg", "netschool"] + #: The allow-list key, which is the region catalog's key. ``None`` for + #: Petersburg, which is one city's server. + region: str | None = None + #: The upstream's own school id («scid»), which the phone signs in with. + school_id: int | None = None + school_name: str | None = None + + @classmethod + def of(cls, bound: Binding | None) -> DiaryBindingOut | None: + if bound is None: + return None + return cls( + provider=bound.provider.key, + region=bound.region, + school_id=bound.school_id, + school_name=bound.school_name, + ) + + +class JoinResponse(BaseModel): + token: str + class_id: int + class_name: str + school: str | None = None + timezone: str + #: The class's diary binding, or ``None`` when it has none this server can + #: reach. Additive, so an older phone ignores it and ``API_VERSION`` holds. + diary: DiaryBindingOut | None = None + + +class MeOut(BaseModel): + device_name: str | None = None + linked: bool + role: RoleName | None = None + can_edit: bool + # Only while unlinked. A linked device has no code, and a code that stayed + # on a linked row could be typed by somebody else and re-home the phone. + link_code: str | None = None + bot_deep_link: str | None = None + + +class UnlinkOut(BaseModel): + linked: bool diff --git a/server/app/schemas/reports.py b/server/app/schemas/reports.py new file mode 100644 index 00000000..f55828e2 --- /dev/null +++ b/server/app/schemas/reports.py @@ -0,0 +1,54 @@ +"""What an admin reads about the class rather than changes: the log and the stats. + +Part of the management surface; what holds across it is in the package +docstring. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import datetime + +from pydantic import BaseModel + +from app.schemas.bundle import RoleName + + +class AuditEntryOut(BaseModel): + id: int + # Machine tag: homework.add, subject.rename, timetable.import, ... + action: str + summary: str + who: str | None = None + at: datetime | None = None + + +class AuditPageOut(BaseModel): + """``has_more`` rather than a total: the log is append-only and unbounded, + and a count of it would be a full scan on every page turn.""" + + entries: list[AuditEntryOut] = [] + limit: int + offset: int + has_more: bool = False + + +class SubjectHoursOut(BaseModel): + """Lessons a week. A subject that alternates weeks counts a half, which is + how a school's own paperwork writes «часов в неделю».""" + + name: str + hours: float + + +class StatsOut(BaseModel): + today: Date + lessons_per_week: float + subjects_count: int + subjects: list[SubjectHoursOut] = [] + homework_open: int + homework_total: int + members_by_role: dict[RoleName, int] = {} + devices_active: int + overrides_upcoming: int + events_upcoming: int diff --git a/server/app/schemas/school_class.py b/server/app/schemas/school_class.py new file mode 100644 index 00000000..1995adae --- /dev/null +++ b/server/app/schemas/school_class.py @@ -0,0 +1,109 @@ +"""Managing the class itself: the «⚙️ Класс» card and its edits, its terms, its deletion. + +Part of the management surface; what holds across it is in the package +docstring. +""" + +from __future__ import annotations + +from datetime import date as Date +from typing import Literal + +from pydantic import BaseModel, Field, field_validator + +from app.schemas._text import _clean_optional_text +from app.schemas.bundle import TermOut + + +class ManagedClassOut(BaseModel): + """The class card the bot draws under «⚙️ Класс», as data. + + ``join_code`` is in here because the card shows it: this endpoint is + admin-only, and the code is what an admin reads out to the class. + """ + + id: int + name: str + school: str | None = None + city: str | None = None + timezone: str + # «МСК+2 (UTC+5) · Екатеринбург» - the same label the bot prints, so the + # app does not have to carry the table of Russian zones twice. + timezone_label: str + join_code: str + #: "open" | "invite" — whether that code is enough on its own. + join_mode: str = "open" + members: int + devices: int + pending_requests: int + bell_schedule_id: int | None = None + calendar_ready: bool = False + + +class TermSchemeIn(BaseModel): + """Switch the class between quarters and half-years.""" + + kind: Literal["quarter", "semester"] + + +class TermBoundsIn(BaseModel): + """Both edges of one term. Validated against the year in the service, not + here: «пересекается с периодом 2» is a rule about the other rows, and + pydantic can only see this one.""" + + starts_on: Date + ends_on: Date + + +class TermsOut(BaseModel): + kind: Literal["quarter", "semester"] + year: int + terms: list[TermOut] = Field(default_factory=list) + + +class ClassPatch(BaseModel): + """Only the fields present are changed; ``null`` clears a nullable one. + + ``name`` and ``timezone`` are not nullable: the name is what every message + calls this class and what the delete confirmation is typed against, and a + class with no zone would have no "today". + """ + + name: str | None = Field(default=None, min_length=1, max_length=64) + # 1..11. The bound is the school's, not the column's: a class numbered 0 or + # 12 would resolve its term scheme from a comparison that happens to be + # true rather than from a decision. + grade: int | None = Field(default=None, ge=1, le=11) + letter: str | None = Field(default=None, max_length=8) + school: str | None = Field(default=None, max_length=200) + city: str | None = Field(default=None, max_length=120) + timezone: str | None = Field(default=None, max_length=64) + #: Who vouches for a phone: the class code, or the bot. See ``JoinMode``. + #: A literal rather than the enum so an unknown value is a 422 with the + #: field named, not a 500 from deep inside SQLAlchemy. + join_mode: Literal["open", "invite"] | None = None + + # An absent field is never validated, so these two run only on a value the + # client actually sent - which is how an explicit ``null`` is refused while + # "leave it alone" stays the default. + @field_validator("name", "timezone") + @classmethod + def _required_when_present(cls, value: str | None) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("must not be blank") + return cleaned + + _clean_school = field_validator("school")(_clean_optional_text) + _clean_city = field_validator("city")(_clean_optional_text) + + +class ClassDeleteIn(BaseModel): + """The class's own name, typed back. + + The same confirmation the bot asks for, and for the same reason: a «вы + уверены?» button is pressed by the same thumb that pressed the one before + it, while a name has to be read off the screen first. + """ + + confirm_name: str = Field(min_length=1, max_length=64) diff --git a/server/app/schemas/subjects.py b/server/app/schemas/subjects.py new file mode 100644 index 00000000..fc8db885 --- /dev/null +++ b/server/app/schemas/subjects.py @@ -0,0 +1,102 @@ +"""The subject dictionary: read by every phone, managed by an admin. + +The colour cleaning lives here because a subject is the only row a colour is +written to; a lesson's colour is its subject's. +""" + +from __future__ import annotations + +import re + +from pydantic import BaseModel, Field, field_validator + +from app.schemas._text import _clean_optional_text + + +class SubjectOut(BaseModel): + name: str + short_name: str | None = None + teacher: str | None = None + color: str | None = None + + +#: The bot's own spelling of a colour, so the two surfaces store one format. +_COLOUR_RE = re.compile(r"^#?([0-9a-fA-F]{6})$") + + +def _clean_colour(value: str | None) -> str | None: + """``#5b6abf`` / ``5B6ABF`` -> ``#5B6ABF``; a dash or blank clears it. + + One spelling in the database is what lets the app compare a lesson's colour + against a palette entry without normalising first, and it is what the + bot's colour picker already writes. + """ + if value is None: + return None + raw = value.strip() + if raw in {"", "-", "—"}: + return None + match = _COLOUR_RE.match(raw) + if match is None: + raise ValueError("colour must be six hex digits, as #5B6ABF") + return f"#{match.group(1).upper()}" + + +class ManagedSubjectOut(SubjectOut): + """A subject with its id. The read-only dictionary in ``GET /subjects`` is + keyed by name because that is what a lesson stores; management addresses a + row, which needs the id.""" + + id: int + + +class SubjectIn(BaseModel): + name: str = Field(min_length=1, max_length=120) + short_name: str | None = Field(default=None, max_length=16) + teacher: str | None = Field(default=None, max_length=120) + color: str | None = Field(default=None, max_length=9) + + @field_validator("name") + @classmethod + def _clean_name(cls, value: str) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("name must not be blank") + return cleaned + + _clean_short = field_validator("short_name")(_clean_optional_text) + _clean_teacher = field_validator("teacher")(_clean_optional_text) + _clean_color = field_validator("color")(_clean_colour) + + +class SubjectPatch(BaseModel): + """Only the fields present are changed; ``null`` clears a nullable one. + ``name`` is the rename, and it carries the timetable with it.""" + + name: str | None = Field(default=None, min_length=1, max_length=120) + short_name: str | None = Field(default=None, max_length=16) + teacher: str | None = Field(default=None, max_length=120) + color: str | None = Field(default=None, max_length=9) + + # Sent, so it is validated; absent, so it is not. A subject with no name + # would be a lesson that cannot be spelled. + @field_validator("name") + @classmethod + def _name_when_present(cls, value: str | None) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("name must not be blank") + return cleaned + + _clean_short = field_validator("short_name")(_clean_optional_text) + _clean_teacher = field_validator("teacher")(_clean_optional_text) + _clean_color = field_validator("color")(_clean_colour) + + +class SubjectSavedOut(BaseModel): + """``moved`` is how many timetable, homework and substitution rows a rename + carried with it - zero for every other kind of edit, and the number an + admin needs to believe the rename actually happened.""" + + subject: ManagedSubjectOut + moved: int = 0 diff --git a/server/app/schemas/tasks.py b/server/app/schemas/tasks.py new file mode 100644 index 00000000..674cc714 --- /dev/null +++ b/server/app/schemas/tasks.py @@ -0,0 +1,91 @@ +"""A person's own tasks, which nobody else in the class sees.""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import datetime +from datetime import time as Time + +from pydantic import BaseModel, Field, field_validator + +from app.schemas._text import _clean_notes, _clean_optional_text + + +class TaskOut(BaseModel): + id: int + title: str + notes: str | None = None + subject_name: str | None = None + due_date: Date | None = None + due_time: Time | None = None + priority: int + done: bool + # UTC: an instant, not a time anybody wrote down. See `PersonalTask`. + done_at: datetime | None = None + homework_id: int | None = None + # Class wall time, unlike the three around it. + remind_at: datetime | None = None + # UTC, with `done_at`. + created_at: datetime | None = None + updated_at: datetime | None = None + + +class TaskIn(BaseModel): + title: str = Field(min_length=1, max_length=200) + notes: str | None = Field(default=None, max_length=2000) + due_date: Date | None = None + due_time: Time | None = None + priority: int = Field(default=1, ge=0, le=2) + subject_name: str | None = Field(default=None, max_length=120) + homework_id: int | None = None + remind_at: datetime | None = None + + @field_validator("title") + @classmethod + def _clean_title(cls, value: str) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("title must not be blank") + return cleaned + + _clean_subject = field_validator("subject_name")(_clean_optional_text) + _clean_notes = field_validator("notes")(_clean_notes) + + +class TaskPatch(BaseModel): + """Every field optional; only the ones sent are changed. ``null`` clears a + nullable field, which is why "absent" and "null" are told apart.""" + + title: str | None = Field(default=None, min_length=1, max_length=200) + notes: str | None = Field(default=None, max_length=2000) + due_date: Date | None = None + due_time: Time | None = None + priority: int | None = Field(default=None, ge=0, le=2) + subject_name: str | None = Field(default=None, max_length=120) + homework_id: int | None = None + remind_at: datetime | None = None + done: bool | None = None + + # An absent field is never validated, so these two run only on a value the + # client actually sent - which is how an explicit ``null`` is refused while + # "leave it alone" stays the default, exactly as ``ClassPatch`` does it. + # Both columns are NOT NULL, and without the refusal ``{"title": null}`` + # reached the UPDATE: an IntegrityError forty frames down, which the app + # sees as a 500 on a field it merely cleared. + @field_validator("title") + @classmethod + def _clean_title(cls, value: str | None) -> str: + cleaned = _clean_optional_text(value) + if cleaned is None: + raise ValueError("title must not be blank") + return cleaned + + @field_validator("priority") + @classmethod + def _priority_when_present(cls, value: int | None) -> int: + if value is None: + raise ValueError("priority must not be null") + return value + + _clean_subject = field_validator("subject_name")(_clean_optional_text) + _clean_notes = field_validator("notes")(_clean_notes) diff --git a/server/app/schemas/timetable.py b/server/app/schemas/timetable.py new file mode 100644 index 00000000..8eb7e122 --- /dev/null +++ b/server/app/schemas/timetable.py @@ -0,0 +1,50 @@ +"""The weekly template as text, out and back in: «📤 Экспорт» and «📥 Импорт». + +Part of the management surface; what holds across it is in the package +docstring. +""" + +from __future__ import annotations + +from pydantic import BaseModel, Field + + +class TimetableExportOut(BaseModel): + """The whole weekly template in the bot's paste format. + + Byte-for-byte what «📤 Экспорт» sends, so a text saved from the bot can be + imported by the app and the other way round. + """ + + text: str + lessons: int + + +class TimetableImportIn(BaseModel): + text: str = Field(min_length=1, max_length=20000) + # Whether to overwrite weekdays that already have lessons. Without it an + # import that would replace something answers with the conflicts instead. + replace: bool = False + + +class ImportConflictOut(BaseModel): + """One weekday the paste would overwrite: what is there now, what would + replace it. Weekday is 1=Monday .. 7=Sunday, as everywhere else.""" + + weekday: int + existing: int + incoming: int + + +class TimetableImportOut(BaseModel): + """``applied: false`` means nothing was written - either the paste held no + day the parser recognised, or it collided and ``replace`` was not set.""" + + applied: bool + days: list[int] = [] + lessons: int = 0 + bells: int = 0 + conflicts: list[ImportConflictOut] = [] + # Lines the parser could not read. Echoed back so an admin can fix the two + # that were typos rather than re-reading the whole paste. + rejected: list[str] = [] From 73b1e932caeb015e142bd4b214f20cfc9644e8fa Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 17:43:43 +0300 Subject: [PATCH 28/43] Keep the services below the bot, with the role ladder and the shared wording moved beneath both MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four services imported from the bot's own package: services/access and services/linking took the role ladder from app.bot.roles (can_grant, get_role), services/reminders took the day card, the message budget and the calendar names from app.bot.render, and services/timetable_io the weekday names. The services are the layer the API shares with the bot, so every endpoint that grants access, links a phone, imports or exports a timetable, or ticks the cron reached the bot's UI package through them, and the next rule written beside those imports had nowhere neutral to live. What moved, unchanged apart from comments: - all of app/bot/roles.py to app/services/roles.py: is_env_owner, get_membership, get_role, require_role, list_memberships, default_class_for, can_grant, claim_phone_invites. Nothing in it touches aiogram. - from app/bot/render.py to a new app/wording.py, which imports only models and schedule: MONTHS_GENITIVE, MONTHS_NOMINATIVE, WEEKDAYS, WEEKDAYS_SHORT, EVENT_ICONS, DAY_KIND_LABELS, plural, MESSAGE_LIMIT, more_line, clamp, cut, human_date, relative_day_name, DAY_HOMEWORK_TEXT_MAX, render_day, and the private _OFF_REASON_LINES and _no_lessons_because that render_day draws with. app.bot.roles and app.bot.render import every public name back, so the handlers, the middleware and the endpoints that import from there get the very same objects and none of them changed; no test patched a moved name at its old address. The services import from app.services.roles and app.wording. tests/test_service_layering.py reads every module under app/ and follows the imports from each app.services module through the rest of app/, so a service that reaches the bot through a neutral module fails as well, with the chain named. It sees function-local, TYPE_CHECKING, relative and import_module spellings, and holds its own matcher against them. Seen red with HEAD's services/access.py put back («app.services.access -> app.bot.roles»), green after. It also checks the bot modules hand out the same objects as their new homes. tests/test_plural_calls.py now scans all of app/ rather than app/bot/, because plural and render_day moved out of the bot and the digests that call them are in services/. Not covered: the rule is enforced for services/ only. api/edit.py and api/manage.py still import human_date and WEEKDAYS from app.bot.render, and four api modules build the Bot through a function-local import of app.bot.bot; both are outside this issue and in files another agent owns. The layer rule is not yet written into docs/architecture.md (#204). Closes #205 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/bot/render.py | 293 +++----------------------- server/app/bot/roles.py | 202 +++--------------- server/app/services/__init__.py | 8 + server/app/services/access.py | 2 +- server/app/services/linking.py | 2 +- server/app/services/reminders.py | 10 +- server/app/services/roles.py | 189 +++++++++++++++++ server/app/services/timetable_io.py | 2 +- server/app/wording.py | 286 +++++++++++++++++++++++++ server/tests/test_plural_calls.py | 18 +- server/tests/test_service_layering.py | 200 ++++++++++++++++++ 11 files changed, 758 insertions(+), 454 deletions(-) create mode 100644 server/app/services/roles.py create mode 100644 server/app/wording.py create mode 100644 server/tests/test_service_layering.py diff --git a/server/app/bot/render.py b/server/app/bot/render.py index c4b4e6a5..1fdad9ef 100644 --- a/server/app/bot/render.py +++ b/server/app/bot/render.py @@ -2,6 +2,14 @@ Kept apart from the handlers so the wording can be changed without touching any control flow. + +The calendar names, the message budget, ``plural`` and the day card are not +here: the digests in ``services/reminders`` and the paste grammar in +``services/timetable_io`` need them too, and a service may not import the bot +(#205), so they live in :mod:`app.wording`. Every one of them is imported back +below, so ``from app.bot.render import …`` in a handler or an endpoint reads the +same object it always did. The ones nothing here draws with are imported as +``X as X``, which is how the linter tells a re-export from an unused import. """ from __future__ import annotations @@ -12,257 +20,25 @@ from datetime import time as Time from html import escape -from app.models import DayKind, EventKind, PersonalTask, ReminderSettings, Role, WeekParity -from app.schedule import DayOffReason, ResolvedDay, ResolvedLesson, week_parity - -MONTHS_GENITIVE = [ - "января", - "февраля", - "марта", - "апреля", - "мая", - "июня", - "июля", - "августа", - "сентября", - "октября", - "ноября", - "декабря", -] - -#: Nominative, for a heading that names the month rather than a date in it: -#: «Сентябрь 2026», not «сентября». -MONTHS_NOMINATIVE = [ - "Январь", - "Февраль", - "Март", - "Апрель", - "Май", - "Июнь", - "Июль", - "Август", - "Сентябрь", - "Октябрь", - "Ноябрь", - "Декабрь", -] - -WEEKDAYS = [ - "понедельник", - "вторник", - "среда", - "четверг", - "пятница", - "суббота", - "воскресенье", -] - -EVENT_ICONS = { - EventKind.EVENT: "🎉", - EventKind.CANTEEN: "🍽", - EventKind.EXAM: "📋", - EventKind.TRIP: "🚌", - EventKind.MEETING: "👥", -} - -DAY_KIND_LABELS = { - DayKind.HOLIDAY: "🏖 Каникулы / выходной", - DayKind.SHORTENED: "⏱ Сокращённые уроки", - DayKind.REMOTE: "💻 Дистанционное обучение", - DayKind.SELF_STUDY: "📖 Самоподготовка", - DayKind.DAY_OFF: "🌿 Отгул", -} - - -# -------------------------------------------------------------------------- -# Message budgets -# -------------------------------------------------------------------------- -# -# A message Telegram will not deliver is a screen that says nothing: the -# ceiling is 4096 characters after entity parsing, and the whole message is -# refused rather than clipped. Every renderer below that grows with the data -# has to carry a budget, and these are the three tools for it. -# -# They used to live in ``manage_render``, which is downstream of this module, -# so the four management pages had them and nothing else could. That is how -# the day view, the access list, the task list and the diary's four renderers -# each ended up without one: the fix was written twice and reached neither -# ``render_day`` here nor anything in ``diary_render``. - -#: What one message may grow to. -#: -#: Telegram's ceiling is «1-4096 characters **after entities parsing**», which -#: is the Bot API's own wording for `sendMessage`'s `text`: it counts what it -#: parses, so `<b>` costs nothing and `&` counts as the one «&» it becomes. -#: An earlier version of this comment said the margin was there because -#: Telegram counts the tags. It does not, and that mistake cost a day — it is -#: what `_export_parts` in `handlers/manage` was built to defend against, and -#: that turned six messages into thirty-four and walked into the flood limit. -#: -#: Everything here measures the raw string, tags and entities included, so it -#: is *conservative*: a page cut at 3900 raw is comfortably under 4096 parsed. -#: That is deliberate and cheaper than parsing twice to find out — but it means -#: a number in this file is a budget and never a measurement of what Telegram -#: will count. The margin itself is for a navigation hint a handler may append. -#: -#: There is one way the raw count reads *lower* than Telegram's, and it is the -#: reason this number must not be tidied up towards 4096: Telegram counts UTF-16 -#: code units, and every emoji outside the BMP — «📝», «📥», «🗓», most of the -#: ones these cards are built from — is two of them where Python sees one. The -#: tags a raw count includes and a parsed count does not are worth far more -#: than that in every page measured so far, so the slack has never been spent; -#: nothing measures it, and at 4096 the first page to prove otherwise would not -#: be clipped, it would be refused. -MESSAGE_LIMIT = 3900 - - -def more_line(total: int, shown: int) -> list[str]: - hidden = total - shown - return [f"… и ещё {hidden}"] if hidden > 0 else [] - - -def clamp(lines: list[str], limit: int = MESSAGE_LIMIT) -> str: - """Join lines, dropping the tail that would not fit and saying how many. - - Cutting from the end rather than shortening every line: the rows are - ordered by what matters most (the nearest date, the newest change), so the - ones that survive are the ones worth reading. - """ - kept: list[str] = [] - used = 0 - for position, line in enumerate(lines): - cost = len(line) + 1 - if used + cost > limit: - rest = len(lines) - position - kept.append("… и ещё " + plural(rest, "строка", "строки", "строк")) - break - kept.append(line) - used += cost - return "\n".join(kept) - - -def cut(text: str, limit: int) -> str: - """One long free-text value, shortened for a list where it is one row. - - Called on the raw value and never on the escaped one: cutting after - escaping can leave «&am», which is a message Telegram refuses of its own. - """ - text = " ".join(text.split()) - return text if len(text) <= limit else text[: limit - 1].rstrip() + "…" - - -def human_date(day: Date, today: Date | None = None) -> str: - """«сегодня, 9 сентября (вторник)» — the form people actually read.""" - label = f"{day.day} {MONTHS_GENITIVE[day.month - 1]} ({WEEKDAYS[day.weekday()]})" - if today is None: - return label - delta = (day - today).days - if delta == 0: - return f"сегодня, {label}" - if delta == 1: - return f"завтра, {label}" - if delta == -1: - return f"вчера, {label}" - return label - - -def relative_day_name(day: Date, today: Date) -> str: - """«на завтра» / «на понедельник» / «на 15 сентября».""" - delta = (day - today).days - if delta == 1: - return "на завтра" - if 2 <= delta <= 7: - return f"на {WEEKDAYS[day.weekday()]}" - return f"на {day.day} {MONTHS_GENITIVE[day.month - 1]}" - - -#: An assignment in the day view, before it is shortened. -#: -#: Generous on purpose, and not the digest's 400: this is one day, and the -#: point of opening it is to read the assignment rather than to be told there is -#: one. The cut exists for the other end — ``schemas`` accepts 4000 characters -#: for an assignment and the column is uncapped, so a single pasted essay used to -#: take the whole day over Telegram's ceiling, on «сегодня», on «завтра», on -#: the ‹ › pager, in the calendar card and in the morning digest at once, and -#: `/today` is a plain answer with no callback to apologise on. -DAY_HOMEWORK_TEXT_MAX = 1000 - - -#: Why a day is empty, in the words the reader can act on. -#: -#: «Уроков нет» is true of all four and useless for three: somebody looking at -#: a blank Tuesday in November wants to know whether it is the holidays, a -#: public holiday, or a day the timetable simply has nothing on — and those -#: are three different things to do next. -_OFF_REASON_LINES: dict[DayOffReason, str] = { - DayOffReason.OUT_OF_YEAR: "Учебный год окончен — уроков нет.", - DayOffReason.BETWEEN_TERMS: "Каникулы между периодами — уроков нет.", - DayOffReason.PUBLIC_HOLIDAY: "Праздничный день — уроков нет.", -} - - -def _no_lessons_because(day: ResolvedDay) -> str: - return _OFF_REASON_LINES.get(day.off_reason, "Уроков нет.") if day.off_reason else "Уроков нет." - - -def render_day(day: ResolvedDay, today: Date) -> str: - lines = [f"<b>{escape(human_date(day.date, today)).capitalize()}</b>"] - - kind_label = DAY_KIND_LABELS.get(day.kind) - if kind_label: - lines.append(kind_label) - if day.holiday: - # Escaped like everything else that is not this file's own text. These - # titles are ours rather than typed by anybody, but the rule is about - # where a string is written rather than about who wrote it — «женщин и - # девочек» is fine today and the next name added may not be. - lines.append(f"🎉 {escape(day.holiday.title)}") - if day.note: - lines.append(f"<i>{escape(day.note)}</i>") - - if not day.lessons: - lines.append("") - lines.append(_no_lessons_because(day)) - else: - lines.append("") - for lesson in day.lessons: - time_range = f"{lesson.starts_at:%H:%M}–{lesson.ends_at:%H:%M}" - subject = escape(lesson.subject) - if lesson.is_cancelled: - row = f"{lesson.index}. <s>{subject}</s> — отменён" - else: - marks = " 🔁" if lesson.is_replaced else "" - row = f"{lesson.index}. <b>{subject}</b>{marks}" - extras = [] - if lesson.room and not lesson.is_cancelled: - extras.append(f"каб. {escape(lesson.room)}") - if lesson.teacher and not lesson.is_cancelled: - extras.append(escape(lesson.teacher)) - suffix = f" · {' · '.join(extras)}" if extras else "" - lines.append(f"<code>{time_range}</code> {row}{suffix}") - if lesson.note: - lines.append(f" <i>{escape(lesson.note)}</i>") - - if day.events: - lines.append("") - lines.append("<b>События</b>") - for event in day.events: - icon = EVENT_ICONS.get(event.kind, "•") - where = f" · {escape(event.location)}" if event.location else "" - lines.append( - f"{icon} <code>{event.starts_at:%H:%M}–{event.ends_at:%H:%M}</code> " - f"{escape(event.title)}{where}" - ) - - if day.homework: - lines.append("") - lines.append("<b>Домашнее задание</b>") - for item in day.homework: - text = escape(cut(item.text, DAY_HOMEWORK_TEXT_MAX)) - lines.append(f"📝 <b>{escape(item.subject)}</b>: {text}") - - return clamp(lines) - +from app.models import PersonalTask, ReminderSettings, Role, WeekParity +from app.schedule import ResolvedDay, ResolvedLesson, week_parity +from app.wording import DAY_HOMEWORK_TEXT_MAX as DAY_HOMEWORK_TEXT_MAX +from app.wording import ( + DAY_KIND_LABELS, + EVENT_ICONS, + MONTHS_GENITIVE, + WEEKDAYS_SHORT, + clamp, + cut, + human_date, + more_line, + plural, +) +from app.wording import MESSAGE_LIMIT as MESSAGE_LIMIT +from app.wording import MONTHS_NOMINATIVE as MONTHS_NOMINATIVE +from app.wording import WEEKDAYS as WEEKDAYS +from app.wording import relative_day_name as relative_day_name +from app.wording import render_day as render_day #: Members listed on «👥 Доступ», and the number the role picker builds its #: buttons from. @@ -335,11 +111,9 @@ def render_role_help(role: Role) -> str: # -------------------------------------------------------------------------- -# Plurals and small formatting helpers +# Small formatting helpers # -------------------------------------------------------------------------- -WEEKDAYS_SHORT = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"] - PRIORITY_ICONS = {2: "🔴", 1: "🟡", 0: "⚪"} #: Longest message the week view may grow to before it starts dropping @@ -353,17 +127,6 @@ def render_role_help(role: Role) -> str: INVISIBLE = "⁣" -def plural(count: int, one: str, few: str, many: str) -> str: - """«1 урок», «2 урока», «5 уроков» — Russian has three plural forms, not two.""" - tail = count % 100 - if 11 <= tail <= 19: - form = many - else: - tail %= 10 - form = one if tail == 1 else few if 2 <= tail <= 4 else many - return f"{count} {form}" - - def silenced_lessons(silenced: list[tuple[int, int]]) -> str: """What to tell an admin whose new bells left lessons ringing nowhere. diff --git a/server/app/bot/roles.py b/server/app/bot/roles.py index 29d15c9a..48a155b8 100644 --- a/server/app/bot/roles.py +++ b/server/app/bot/roles.py @@ -1,180 +1,32 @@ -"""Who is allowed to do what. +"""Who is allowed to do what — asked here, decided in :mod:`app.services.roles`. -Role ladder (weakest first): VIEWER -> EDITOR -> ADMIN -> OWNER. - -* VIEWER — reads the schedule and homework in the bot. -* EDITOR — writes homework, substitutions and events. This is the role you hand to a - classmate whose phone number you add. -* ADMIN — everything an editor can do, plus the weekly timetable, bells and - granting/revoking EDITOR and VIEWER. -* OWNER — everything, plus granting ADMIN and rotating the join code. - OWNER is granted only by ``OWNER_IDS`` in the environment, so it can - never be escalated into from inside the bot. +The role ladder moved to ``services/`` because the services the API shares +with the bot ask it too — ``services/linking`` for what a linked phone may +write, ``services/access`` for what a request may be granted — and a service +may not import the bot (#205). The handlers and the middleware have always +asked here, so every name is imported back and is the very same function. """ from __future__ import annotations -from datetime import UTC, datetime - -from sqlalchemy import select -from sqlalchemy import update as sa_update -from sqlalchemy.ext.asyncio import AsyncSession - -from app.config import get_settings -from app.db import rows_affected -from app.models import BotUser, PhoneInvite, Role, SchoolClass -from app.security import normalise_phone - - -def is_env_owner(telegram_id: int) -> bool: - return telegram_id in get_settings().owner_id_list - - -async def get_membership( - session: AsyncSession, telegram_id: int, class_id: int -) -> BotUser | None: - return await session.scalar( - select(BotUser).where(BotUser.telegram_id == telegram_id, BotUser.class_id == class_id) - ) - - -async def get_role(session: AsyncSession, telegram_id: int, class_id: int) -> Role | None: - """Effective role, with the environment owner list taking precedence.""" - if is_env_owner(telegram_id): - return Role.OWNER - membership = await get_membership(session, telegram_id, class_id) - return membership.role if membership else None - - -async def require_role( - session: AsyncSession, telegram_id: int, class_id: int, minimum: Role -) -> bool: - role = await get_role(session, telegram_id, class_id) - return role is not None and role.at_least(minimum) - - -async def list_memberships(session: AsyncSession, telegram_id: int) -> list[BotUser]: - """Every class this account is in, oldest membership first. - - The order is stated rather than left to the database because three things - read it as if it were: the class the middleware falls back to, the one - ``default_class_for`` picks, and the order of the «🔀 Сменить класс» - buttons. An unordered ``SELECT`` is free to hand back a different order - after any write, so a parent with two children could aim at the second - button and open the other child — and the fallback class could differ - between two taps. SQLite happens to return insertion order, which is why - the tests never saw it; Postgres makes no such promise. - """ - return list( - await session.scalars( - select(BotUser).where(BotUser.telegram_id == telegram_id).order_by(BotUser.id) - ) - ) - - -async def default_class_for(session: AsyncSession, telegram_id: int) -> SchoolClass | None: - """The class a user lands in when they open the bot. - - Environment owners see the first class even before they are members of it, - which is what makes bootstrapping a fresh install possible. - """ - memberships = await list_memberships(session, telegram_id) - if memberships: - return await session.get(SchoolClass, memberships[0].class_id) - if is_env_owner(telegram_id): - return await session.scalar(select(SchoolClass).order_by(SchoolClass.id).limit(1)) - return None - - -def can_grant(actor: Role, target: Role) -> bool: - """Nobody may grant a role at or above their own, and OWNER is env-only. - - Without this rule an admin could promote a friend to admin and then be - demoted by them; the strict inequality removes that whole class of problem. - """ - if target is Role.OWNER: - return False - if not actor.at_least(Role.ADMIN): - return False - return actor.rank > target.rank - - -async def claim_phone_invites( - session: AsyncSession, - telegram_id: int, - phone: str, - username: str | None, - full_name: str | None, -) -> list[tuple[SchoolClass, Role]]: - """Apply every pending invite matching ``phone``. - - Called when a user shares their contact with the bot. Telegram guarantees the - number really belongs to that account, which is what makes an invite-by-phone - safe to auto-apply. - - @return (class, effective role) per invite claimed — the role the account - holds in that class afterwards, which is not always the invite's. - """ - normalised = normalise_phone(phone) - if not normalised: - return [] - - invites = list( - await session.scalars( - select(PhoneInvite).where( - PhoneInvite.phone == normalised, PhoneInvite.used_by.is_(None) - ) - ) - ) - - now = datetime.now(UTC).replace(tzinfo=None) - granted: list[tuple[SchoolClass, Role]] = [] - for invite in invites: - school_class = await session.get(SchoolClass, invite.class_id) - if school_class is None: - continue - - # Spent before anything is granted, by one conditional UPDATE, exactly - # as `device_invites.burn` spends a phone's code: the read above is not - # a claim. A webhook Telegram believes went unanswered is delivered - # again, and the two deliveries both read this invite unused; assigning - # `used_by` and committing let both through. The same account was then - # answered «Доступ выдан» twice, or the slower delivery died on the - # membership's unique key, and a second account on the number got a - # membership of its own from an invite worth one. Here the later - # statement waits on the earlier's lock, re-checks the row after it, - # and matches nothing, so that delivery grants nothing. - spent = await session.execute( - sa_update(PhoneInvite) - .where(PhoneInvite.id == invite.id, PhoneInvite.used_by.is_(None)) - .values(used_by=telegram_id, used_at=now) - ) - if rows_affected(spent) != 1: - continue - - membership = await get_membership(session, telegram_id, invite.class_id) - if membership is None: - membership = BotUser( - telegram_id=telegram_id, - class_id=invite.class_id, - role=invite.role, - granted_by=invite.invited_by, - ) - session.add(membership) - elif invite.role.rank > membership.role.rank: - membership.role = invite.role - - membership.phone = normalised - membership.username = username - membership.full_name = full_name - - # The role they now hold, not the one the invite named. The rule above - # keeps the higher of the two, so an invite below somebody's existing - # role changes nothing — but the caller draws the main menu from what - # is returned here, and an admin was told «роль: Наблюдатель» and given - # an observer's keyboard, with «🧩 Расписание», «👥 Доступ» and - # «⚙️ Класс» simply absent. - granted.append((school_class, membership.role)) - - await session.commit() - return granted +from app.services.roles import ( + can_grant, + claim_phone_invites, + default_class_for, + get_membership, + get_role, + is_env_owner, + list_memberships, + require_role, +) + +__all__ = [ + "can_grant", + "claim_phone_invites", + "default_class_for", + "get_membership", + "get_role", + "is_env_owner", + "list_memberships", + "require_role", +] diff --git a/server/app/services/__init__.py b/server/app/services/__init__.py index b791f480..ce68e1f3 100644 --- a/server/app/services/__init__.py +++ b/server/app/services/__init__.py @@ -8,6 +8,14 @@ API can use the rest of the package without paying aiogram's import time on a cold start. +Nor does any module here import ``app.bot``, at any level and by any path: +the bot is one of the two shells standing on this package, not something +under it. Four services once reached into ``bot/roles`` and ``bot/render`` +for the role ladder, the day card and the calendar names; those now live in +``services/roles`` and ``app/wording.py``, the bot imports them back, and +``tests/test_service_layering.py`` follows every import from here through the +rest of ``app/`` to keep it that way (#205). + The split exists because a linked phone and the bot write the same facts. A homework tick from the app and a tick from an inline button must land in the same table with the same rules, and the only way to guarantee that is for diff --git a/server/app/services/access.py b/server/app/services/access.py index 36a4c639..64bf210a 100644 --- a/server/app/services/access.py +++ b/server/app/services/access.py @@ -25,9 +25,9 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from app.bot.roles import can_grant from app.models import AccessRequest, BotUser, Role, SchoolClass from app.services import audit +from app.services.roles import can_grant class GrantRefused(Exception): diff --git a/server/app/services/linking.py b/server/app/services/linking.py index be9d7915..647f4a7f 100644 --- a/server/app/services/linking.py +++ b/server/app/services/linking.py @@ -16,9 +16,9 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession -from app.bot.roles import get_role from app.models import DeviceToken, Role from app.security import new_join_code +from app.services.roles import get_role #: Six characters, not the eight of a join code. A link code is single-use, #: only ever matched against devices that are not yet linked, and a correct diff --git a/server/app/services/reminders.py b/server/app/services/reminders.py index cbc24f9d..b1780c1e 100644 --- a/server/app/services/reminders.py +++ b/server/app/services/reminders.py @@ -32,7 +32,11 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession -from app.bot.render import ( +from app.db import rows_affected +from app.models import Homework, PersonalTask, ReminderSettings, SchoolClass +from app.schedule import ResolvedDay, ScheduleResolver +from app.services.tasks import homework_ticks +from app.wording import ( MONTHS_GENITIVE, clamp, cut, @@ -40,10 +44,6 @@ relative_day_name, render_day, ) -from app.db import rows_affected -from app.models import Homework, PersonalTask, ReminderSettings, SchoolClass -from app.schedule import ResolvedDay, ScheduleResolver -from app.services.tasks import homework_ticks log = logging.getLogger(__name__) diff --git a/server/app/services/roles.py b/server/app/services/roles.py new file mode 100644 index 00000000..bfeeaedb --- /dev/null +++ b/server/app/services/roles.py @@ -0,0 +1,189 @@ +"""Who is allowed to do what. + +Role ladder (weakest first): VIEWER -> EDITOR -> ADMIN -> OWNER. + +* VIEWER — reads the schedule and homework in the bot. +* EDITOR — writes homework, substitutions and events. This is the role you hand to a + classmate whose phone number you add. +* ADMIN — everything an editor can do, plus the weekly timetable, bells and + granting/revoking EDITOR and VIEWER. +* OWNER — everything, plus granting ADMIN and rotating the join code. + OWNER is granted only by ``OWNER_IDS`` in the environment, so it can + never be escalated into from inside the bot. + +The ladder is asked by both shells, not only by the bot it was written for: a +linked phone writes with its account's role, which ``services/linking`` reads +through :func:`get_role`, and ``services/access`` grants from a request only +what :func:`can_grant` allows. It lived in ``app.bot.roles`` and those two +services imported it from there, which put the bot's package under the layer +the API stands on (#205). Nothing here touches aiogram, and it lives here now; +``app.bot.roles`` imports every name back, so the handlers and the middleware +ask where they always did and get the same functions. +""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import select +from sqlalchemy import update as sa_update +from sqlalchemy.ext.asyncio import AsyncSession + +from app.config import get_settings +from app.db import rows_affected +from app.models import BotUser, PhoneInvite, Role, SchoolClass +from app.security import normalise_phone + + +def is_env_owner(telegram_id: int) -> bool: + return telegram_id in get_settings().owner_id_list + + +async def get_membership( + session: AsyncSession, telegram_id: int, class_id: int +) -> BotUser | None: + return await session.scalar( + select(BotUser).where(BotUser.telegram_id == telegram_id, BotUser.class_id == class_id) + ) + + +async def get_role(session: AsyncSession, telegram_id: int, class_id: int) -> Role | None: + """Effective role, with the environment owner list taking precedence.""" + if is_env_owner(telegram_id): + return Role.OWNER + membership = await get_membership(session, telegram_id, class_id) + return membership.role if membership else None + + +async def require_role( + session: AsyncSession, telegram_id: int, class_id: int, minimum: Role +) -> bool: + role = await get_role(session, telegram_id, class_id) + return role is not None and role.at_least(minimum) + + +async def list_memberships(session: AsyncSession, telegram_id: int) -> list[BotUser]: + """Every class this account is in, oldest membership first. + + The order is stated rather than left to the database because three things + read it as if it were: the class the middleware falls back to, the one + ``default_class_for`` picks, and the order of the «🔀 Сменить класс» + buttons. An unordered ``SELECT`` is free to hand back a different order + after any write, so a parent with two children could aim at the second + button and open the other child — and the fallback class could differ + between two taps. SQLite happens to return insertion order, which is why + the tests never saw it; Postgres makes no such promise. + """ + return list( + await session.scalars( + select(BotUser).where(BotUser.telegram_id == telegram_id).order_by(BotUser.id) + ) + ) + + +async def default_class_for(session: AsyncSession, telegram_id: int) -> SchoolClass | None: + """The class a user lands in when they open the bot. + + Environment owners see the first class even before they are members of it, + which is what makes bootstrapping a fresh install possible. + """ + memberships = await list_memberships(session, telegram_id) + if memberships: + return await session.get(SchoolClass, memberships[0].class_id) + if is_env_owner(telegram_id): + return await session.scalar(select(SchoolClass).order_by(SchoolClass.id).limit(1)) + return None + + +def can_grant(actor: Role, target: Role) -> bool: + """Nobody may grant a role at or above their own, and OWNER is env-only. + + Without this rule an admin could promote a friend to admin and then be + demoted by them; the strict inequality removes that whole class of problem. + """ + if target is Role.OWNER: + return False + if not actor.at_least(Role.ADMIN): + return False + return actor.rank > target.rank + + +async def claim_phone_invites( + session: AsyncSession, + telegram_id: int, + phone: str, + username: str | None, + full_name: str | None, +) -> list[tuple[SchoolClass, Role]]: + """Apply every pending invite matching ``phone``. + + Called when a user shares their contact with the bot. Telegram guarantees the + number really belongs to that account, which is what makes an invite-by-phone + safe to auto-apply. + + @return (class, effective role) per invite claimed — the role the account + holds in that class afterwards, which is not always the invite's. + """ + normalised = normalise_phone(phone) + if not normalised: + return [] + + invites = list( + await session.scalars( + select(PhoneInvite).where( + PhoneInvite.phone == normalised, PhoneInvite.used_by.is_(None) + ) + ) + ) + + now = datetime.now(UTC).replace(tzinfo=None) + granted: list[tuple[SchoolClass, Role]] = [] + for invite in invites: + school_class = await session.get(SchoolClass, invite.class_id) + if school_class is None: + continue + + # Spent before anything is granted, by one conditional UPDATE, exactly + # as `device_invites.burn` spends a phone's code: the read above is not + # a claim. A webhook Telegram believes went unanswered is delivered + # again, and the two deliveries both read this invite unused; assigning + # `used_by` and committing let both through. The same account was then + # answered «Доступ выдан» twice, or the slower delivery died on the + # membership's unique key, and a second account on the number got a + # membership of its own from an invite worth one. Here the later + # statement waits on the earlier's lock, re-checks the row after it, + # and matches nothing, so that delivery grants nothing. + spent = await session.execute( + sa_update(PhoneInvite) + .where(PhoneInvite.id == invite.id, PhoneInvite.used_by.is_(None)) + .values(used_by=telegram_id, used_at=now) + ) + if rows_affected(spent) != 1: + continue + + membership = await get_membership(session, telegram_id, invite.class_id) + if membership is None: + membership = BotUser( + telegram_id=telegram_id, + class_id=invite.class_id, + role=invite.role, + granted_by=invite.invited_by, + ) + session.add(membership) + elif invite.role.rank > membership.role.rank: + membership.role = invite.role + + membership.phone = normalised + membership.username = username + membership.full_name = full_name + + # The role they now hold, not the one the invite named. The rule above + # keeps the higher of the two, so an invite below somebody's existing + # role changes nothing — but the caller draws the main menu from what + # is returned here, and an admin was told «роль: Наблюдатель» and given + # an observer's keyboard, with «🧩 Расписание», «👥 Доступ» and + # «⚙️ Класс» simply absent. + granted.append((school_class, membership.role)) + + await session.commit() + return granted diff --git a/server/app/services/timetable_io.py b/server/app/services/timetable_io.py index 838a3512..5ac5b599 100644 --- a/server/app/services/timetable_io.py +++ b/server/app/services/timetable_io.py @@ -22,8 +22,8 @@ import re from datetime import time as Time -from app.bot.render import WEEKDAYS from app.models import BellPeriod, TimetableEntry, WeekParity +from app.wording import WEEKDAYS #: One parsed lesson line: (index, subject, room, teacher, parity). LessonRow = tuple[int, str, str | None, str | None, WeekParity] diff --git a/server/app/wording.py b/server/app/wording.py new file mode 100644 index 00000000..eb91d2e0 --- /dev/null +++ b/server/app/wording.py @@ -0,0 +1,286 @@ +"""The Russian the bot and the services both put into a message. + +Calendar names, the message budget, a date said aloud and the day card. The +bot draws all of them, and so does something that is not the bot: the +morning digest in ``services/reminders`` is the day card under «☀️ Доброе +утро!», the evening one and the task reminders date their rows in the same +words and keep to the same budget, and the paste grammar in +``services/timetable_io`` writes the same weekday names. + +They lived in ``app.bot.render``, and those services imported them from +there — so the layer the API shares with the bot reached up into the bot's +own package, and every endpoint that imports or exports a timetable did too +(#205). A service may not import ``app.bot``; this module sits below both, +beside ``schedule``, and imports nothing but ``models`` and ``schedule``. +``app.bot.render`` imports every public name here back, so a +``from app.bot.render import …`` anywhere reads the same objects it always did. +""" + +from __future__ import annotations + +from datetime import date as Date +from html import escape + +from app.models import DayKind, EventKind +from app.schedule import DayOffReason, ResolvedDay + +MONTHS_GENITIVE = [ + "января", + "февраля", + "марта", + "апреля", + "мая", + "июня", + "июля", + "августа", + "сентября", + "октября", + "ноября", + "декабря", +] + +#: Nominative, for a heading that names the month rather than a date in it: +#: «Сентябрь 2026», not «сентября». +MONTHS_NOMINATIVE = [ + "Январь", + "Февраль", + "Март", + "Апрель", + "Май", + "Июнь", + "Июль", + "Август", + "Сентябрь", + "Октябрь", + "Ноябрь", + "Декабрь", +] + +WEEKDAYS = [ + "понедельник", + "вторник", + "среда", + "четверг", + "пятница", + "суббота", + "воскресенье", +] + +WEEKDAYS_SHORT = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"] + +EVENT_ICONS = { + EventKind.EVENT: "🎉", + EventKind.CANTEEN: "🍽", + EventKind.EXAM: "📋", + EventKind.TRIP: "🚌", + EventKind.MEETING: "👥", +} + +DAY_KIND_LABELS = { + DayKind.HOLIDAY: "🏖 Каникулы / выходной", + DayKind.SHORTENED: "⏱ Сокращённые уроки", + DayKind.REMOTE: "💻 Дистанционное обучение", + DayKind.SELF_STUDY: "📖 Самоподготовка", + DayKind.DAY_OFF: "🌿 Отгул", +} + + +def plural(count: int, one: str, few: str, many: str) -> str: + """«1 урок», «2 урока», «5 уроков» — Russian has three plural forms, not two.""" + tail = count % 100 + if 11 <= tail <= 19: + form = many + else: + tail %= 10 + form = one if tail == 1 else few if 2 <= tail <= 4 else many + return f"{count} {form}" + + +# -------------------------------------------------------------------------- +# Message budgets +# -------------------------------------------------------------------------- +# +# A message Telegram will not deliver is a screen that says nothing: the +# ceiling is 4096 characters after entity parsing, and the whole message is +# refused rather than clipped. Every renderer that grows with the data has to +# carry a budget, and these are the three tools for it. +# +# They used to live in ``manage_render``, which is downstream of +# ``app.bot.render``, so the four management pages had them and nothing else +# could. That is how the day view, the access list, the task list and the +# diary's four renderers each ended up without one: the fix was written twice +# and reached neither ``render_day`` nor anything in ``diary_render``. + +#: What one message may grow to. +#: +#: Telegram's ceiling is «1-4096 characters **after entities parsing**», which +#: is the Bot API's own wording for `sendMessage`'s `text`: it counts what it +#: parses, so `<b>` costs nothing and `&` counts as the one «&» it becomes. +#: An earlier version of this comment said the margin was there because +#: Telegram counts the tags. It does not, and that mistake cost a day — it is +#: what `_export_parts` in `handlers/manage` was built to defend against, and +#: that turned six messages into thirty-four and walked into the flood limit. +#: +#: Everything here measures the raw string, tags and entities included, so it +#: is *conservative*: a page cut at 3900 raw is comfortably under 4096 parsed. +#: That is deliberate and cheaper than parsing twice to find out — but it means +#: a number in this file is a budget and never a measurement of what Telegram +#: will count. The margin itself is for a navigation hint a handler may append. +#: +#: There is one way the raw count reads *lower* than Telegram's, and it is the +#: reason this number must not be tidied up towards 4096: Telegram counts UTF-16 +#: code units, and every emoji outside the BMP — «📝», «📥», «🗓», most of the +#: ones these cards are built from — is two of them where Python sees one. The +#: tags a raw count includes and a parsed count does not are worth far more +#: than that in every page measured so far, so the slack has never been spent; +#: nothing measures it, and at 4096 the first page to prove otherwise would not +#: be clipped, it would be refused. +MESSAGE_LIMIT = 3900 + + +def more_line(total: int, shown: int) -> list[str]: + hidden = total - shown + return [f"… и ещё {hidden}"] if hidden > 0 else [] + + +def clamp(lines: list[str], limit: int = MESSAGE_LIMIT) -> str: + """Join lines, dropping the tail that would not fit and saying how many. + + Cutting from the end rather than shortening every line: the rows are + ordered by what matters most (the nearest date, the newest change), so the + ones that survive are the ones worth reading. + """ + kept: list[str] = [] + used = 0 + for position, line in enumerate(lines): + cost = len(line) + 1 + if used + cost > limit: + rest = len(lines) - position + kept.append("… и ещё " + plural(rest, "строка", "строки", "строк")) + break + kept.append(line) + used += cost + return "\n".join(kept) + + +def cut(text: str, limit: int) -> str: + """One long free-text value, shortened for a list where it is one row. + + Called on the raw value and never on the escaped one: cutting after + escaping can leave «&am», which is a message Telegram refuses of its own. + """ + text = " ".join(text.split()) + return text if len(text) <= limit else text[: limit - 1].rstrip() + "…" + + +def human_date(day: Date, today: Date | None = None) -> str: + """«сегодня, 9 сентября (вторник)» — the form people actually read.""" + label = f"{day.day} {MONTHS_GENITIVE[day.month - 1]} ({WEEKDAYS[day.weekday()]})" + if today is None: + return label + delta = (day - today).days + if delta == 0: + return f"сегодня, {label}" + if delta == 1: + return f"завтра, {label}" + if delta == -1: + return f"вчера, {label}" + return label + + +def relative_day_name(day: Date, today: Date) -> str: + """«на завтра» / «на понедельник» / «на 15 сентября».""" + delta = (day - today).days + if delta == 1: + return "на завтра" + if 2 <= delta <= 7: + return f"на {WEEKDAYS[day.weekday()]}" + return f"на {day.day} {MONTHS_GENITIVE[day.month - 1]}" + + +#: An assignment in the day view, before it is shortened. +#: +#: Generous on purpose, and not the digest's 400: this is one day, and the +#: point of opening it is to read the assignment rather than to be told there is +#: one. The cut exists for the other end — ``schemas`` accepts 4000 characters +#: for an assignment and the column is uncapped, so a single pasted essay used to +#: take the whole day over Telegram's ceiling, on «сегодня», on «завтра», on +#: the ‹ › pager, in the calendar card and in the morning digest at once, and +#: `/today` is a plain answer with no callback to apologise on. +DAY_HOMEWORK_TEXT_MAX = 1000 + + +#: Why a day is empty, in the words the reader can act on. +#: +#: «Уроков нет» is true of all four and useless for three: somebody looking at +#: a blank Tuesday in November wants to know whether it is the holidays, a +#: public holiday, or a day the timetable simply has nothing on — and those +#: are three different things to do next. +_OFF_REASON_LINES: dict[DayOffReason, str] = { + DayOffReason.OUT_OF_YEAR: "Учебный год окончен — уроков нет.", + DayOffReason.BETWEEN_TERMS: "Каникулы между периодами — уроков нет.", + DayOffReason.PUBLIC_HOLIDAY: "Праздничный день — уроков нет.", +} + + +def _no_lessons_because(day: ResolvedDay) -> str: + return _OFF_REASON_LINES.get(day.off_reason, "Уроков нет.") if day.off_reason else "Уроков нет." + + +def render_day(day: ResolvedDay, today: Date) -> str: + lines = [f"<b>{escape(human_date(day.date, today)).capitalize()}</b>"] + + kind_label = DAY_KIND_LABELS.get(day.kind) + if kind_label: + lines.append(kind_label) + if day.holiday: + # Escaped like everything else that is not this file's own text. These + # titles are ours rather than typed by anybody, but the rule is about + # where a string is written rather than about who wrote it — «женщин и + # девочек» is fine today and the next name added may not be. + lines.append(f"🎉 {escape(day.holiday.title)}") + if day.note: + lines.append(f"<i>{escape(day.note)}</i>") + + if not day.lessons: + lines.append("") + lines.append(_no_lessons_because(day)) + else: + lines.append("") + for lesson in day.lessons: + time_range = f"{lesson.starts_at:%H:%M}–{lesson.ends_at:%H:%M}" + subject = escape(lesson.subject) + if lesson.is_cancelled: + row = f"{lesson.index}. <s>{subject}</s> — отменён" + else: + marks = " 🔁" if lesson.is_replaced else "" + row = f"{lesson.index}. <b>{subject}</b>{marks}" + extras = [] + if lesson.room and not lesson.is_cancelled: + extras.append(f"каб. {escape(lesson.room)}") + if lesson.teacher and not lesson.is_cancelled: + extras.append(escape(lesson.teacher)) + suffix = f" · {' · '.join(extras)}" if extras else "" + lines.append(f"<code>{time_range}</code> {row}{suffix}") + if lesson.note: + lines.append(f" <i>{escape(lesson.note)}</i>") + + if day.events: + lines.append("") + lines.append("<b>События</b>") + for event in day.events: + icon = EVENT_ICONS.get(event.kind, "•") + where = f" · {escape(event.location)}" if event.location else "" + lines.append( + f"{icon} <code>{event.starts_at:%H:%M}–{event.ends_at:%H:%M}</code> " + f"{escape(event.title)}{where}" + ) + + if day.homework: + lines.append("") + lines.append("<b>Домашнее задание</b>") + for item in day.homework: + text = escape(cut(item.text, DAY_HOMEWORK_TEXT_MAX)) + lines.append(f"📝 <b>{escape(item.subject)}</b>: {text}") + + return clamp(lines) diff --git a/server/tests/test_plural_calls.py b/server/tests/test_plural_calls.py index b13e63f8..01df8bc0 100644 --- a/server/tests/test_plural_calls.py +++ b/server/tests/test_plural_calls.py @@ -7,10 +7,16 @@ the test over one of them was green throughout. This reads the source rather than the output because the output cannot be -enumerated. Every renderer under ``app/bot/`` would have to be called with a -count in each of the three Russian forms to find the next one, and the next one -will be in a branch nobody thought to build a fixture for. The slip has exactly -one shape in the source, and one shape is what a parser can be certain about. +enumerated. Every renderer in ``app/`` would have to be called with a count in +each of the three Russian forms to find the next one, and the next one will be +in a branch nobody thought to build a fixture for. The slip has exactly one +shape in the source, and one shape is what a parser can be certain about. + +All of ``app/`` rather than ``app/bot/``, which is what this read while every +renderer lived there. ``plural`` and the day card moved to ``app/wording.py`` +so the digests could share them without importing the bot (#205), and the +digests themselves are in ``app/services/`` — a scan of the bot alone would +have gone on passing over both. """ from __future__ import annotations @@ -18,11 +24,11 @@ import ast from pathlib import Path -BOT = Path(__file__).resolve().parents[1] / "app" / "bot" +APP = Path(__file__).resolve().parents[1] / "app" def _modules() -> list[Path]: - return sorted(BOT.rglob("*.py")) + return sorted(APP.rglob("*.py")) def _number_before(node: ast.JoinedStr, call: ast.FormattedValue) -> str | None: diff --git a/server/tests/test_service_layering.py b/server/tests/test_service_layering.py new file mode 100644 index 00000000..ff84370b --- /dev/null +++ b/server/tests/test_service_layering.py @@ -0,0 +1,200 @@ +"""Nothing under ``app/services/`` reaches ``app.bot``, by any path. + +``services/`` is the layer both shells stand on: the bot's handlers and the +``/api/v1`` endpoints call the same functions so that a rule is written once. +Four services imported from the bot's own package — the role ladder from +``bot/roles``, the day card, the message budget and the calendar names from +``bot/render`` — so the API reached the bot through the layer it shares with +it, and the next rule written beside those imports would have had nowhere +neutral to live (#205). The pieces moved to ``app.services.roles`` and +``app.wording``, and this holds the direction. + +It reads the source rather than ``sys.modules``, for the reason +``test_test_imports`` gives: what matters is every spelling of the import, +including the ones inside a function body that no test happens to call. And it +follows the imports **through** the rest of ``app/``, because a service that +imports a neutral module which imports the bot has the same dependency with +one more step in it; the failure names the whole chain. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +APP = Path(__file__).resolve().parents[1] / "app" +FORBIDDEN = "app.bot" + + +def _is_forbidden(dotted: str) -> bool: + return dotted == FORBIDDEN or dotted.startswith(FORBIDDEN + ".") + + +def _imported_names(tree: ast.AST, module: str, is_package: bool) -> set[str]: + """Every dotted name ``tree`` imports, relative spellings made absolute. + + ``ast.walk`` rather than the module body, so an import inside a function, + under ``if TYPE_CHECKING:`` or in a ``try`` is seen like any other. For + ``from X import Y`` both ``X`` and ``X.Y`` are returned, because ``Y`` may + be a module (``from app.bot import roles``) and only the caller knows + which names are modules. A literal handed to ``import_module`` counts too. + """ + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + found.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + if node.level: + base = module.split(".") if is_package else module.split(".")[:-1] + base = base[: len(base) - (node.level - 1)] + source = ".".join(base + ([node.module] if node.module else [])) + else: + source = node.module or "" + found.add(source) + found.update(f"{source}.{alias.name}" for alias in node.names) + elif isinstance(node, ast.Call): + name = getattr(node.func, "attr", None) or getattr(node.func, "id", None) + if name in ("import_module", "__import__") and node.args: + first = node.args[0] + if isinstance(first, ast.Constant) and isinstance(first.value, str): + found.add(first.value) + return found + + +def _modules() -> dict[str, Path]: + modules: dict[str, Path] = {} + for path in APP.rglob("*.py"): + parts = list(path.relative_to(APP.parent).with_suffix("").parts) + if parts[-1] == "__init__": + parts = parts[:-1] + modules[".".join(parts)] = path + return modules + + +def _module_of(dotted: str, modules: dict[str, Path]) -> str | None: + """The module of ``app/`` a dotted name lives in, or ``None`` outside it.""" + while dotted and dotted not in modules: + dotted = dotted.rpartition(".")[0] + return dotted or None + + +def _chains_into_the_bot() -> list[str]: + modules = _modules() + edges: dict[str, set[str]] = {} + for name, path in modules.items(): + tree = ast.parse(path.read_text(encoding="utf-8"), str(path)) + imported = _imported_names(tree, name, path.name == "__init__.py") + edges[name] = { + target + for target in (_module_of(dotted, modules) for dotted in imported) + if target is not None and target != name + } + + chains: list[str] = [] + for start in sorted(name for name in modules if name.startswith("app.services")): + came_from: dict[str, str | None] = {start: None} + queue = [start] + while queue: + current = queue.pop(0) + for target in sorted(edges[current]): + if target in came_from: + continue + came_from[target] = current + if _is_forbidden(target): + chain = [target] + while (step := came_from[chain[-1]]) is not None: + chain.append(step) + chains.append(" -> ".join(reversed(chain))) + continue + queue.append(target) + return chains + + +def test_no_service_reaches_the_bot(): + chains = _chains_into_the_bot() + assert chains == [], ( + "A service may not import from `app.bot`, directly or through another " + "module: the API stands on `services/`, and the bot is one of the two " + "shells above it. Move what the service needs down — a rule into " + "`app/services/`, wording into `app/wording.py` — and import it back " + "into the bot module it came from.\n" + "\n".join(chains) + ) + + +def test_the_check_recognises_every_spelling_of_the_slip(): + """Held here rather than trusted, as ``test_test_imports`` holds its own. + + One dependency, many spellings; a matcher that saw only the first would + report the tree clean with the other seven in it. + """ + for source in ( + "from app.bot.roles import can_grant", + "from app.bot import roles", + "from app import bot", + "import app.bot.render", + "import app.bot.render as render", + "from ..bot.roles import get_role", + "from ..bot import render", + "def later():\n from app.bot.render import WEEKDAYS\n", + "if TYPE_CHECKING:\n from app.bot.roles import get_role\n", + "importlib.import_module('app.bot.render')", + ): + names = _imported_names(ast.parse(source), "app.services.example", False) + assert any(_is_forbidden(name) for name in names), source + + # And it is quiet about what a service legitimately imports, including a + # package whose name merely starts with the same three letters. + for source in ( + "from app.services import audit", + "from app.services.roles import get_role", + "from app.wording import WEEKDAYS", + "from app.models import Role", + "from . import audit", + "from app.botany import leaves", + "import aiogram", + ): + names = _imported_names(ast.parse(source), "app.services.example", False) + assert not any(_is_forbidden(name) for name in names), source + + +def test_the_moved_names_are_still_the_bot_modules_own(): + """``app.bot.roles`` and ``app.bot.render`` hand out the very same objects. + + The handlers, the middleware and two endpoints still import from there. + Imported back rather than copied, because a copy is a second definition + free to drift from the first — the thing ``services/`` exists to prevent. + """ + from app import wording + from app.bot import render, roles + from app.services import roles as service_roles + + for name in ( + "can_grant", + "claim_phone_invites", + "default_class_for", + "get_membership", + "get_role", + "is_env_owner", + "list_memberships", + "require_role", + ): + assert getattr(roles, name) is getattr(service_roles, name), name + + for name in ( + "DAY_HOMEWORK_TEXT_MAX", + "DAY_KIND_LABELS", + "EVENT_ICONS", + "MESSAGE_LIMIT", + "MONTHS_GENITIVE", + "MONTHS_NOMINATIVE", + "WEEKDAYS", + "WEEKDAYS_SHORT", + "clamp", + "cut", + "human_date", + "more_line", + "plural", + "relative_day_name", + "render_day", + ): + assert getattr(render, name) is getattr(wording, name), name From 1db2c858c029fabfc46da4388d1a64e0079aa66d Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 17:08:31 +0300 Subject: [PATCH 29/43] Deploy the exact versions CI tested, from a lock of the function's whole dependency tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit requirements.txt carried the same `>=` floors as pyproject.toml, so every Vercel build installed whatever was newest that day, and a checkout set up a week earlier tested something else again: SQLAlchemy 2.1 reached production and CI that way, unannounced (#164). It is now a lock. requirements.in holds the deployed share of pyproject.toml's runtime dependencies, character for character, and `uv pip compile requirements.in --python-version 3.12 --python-platform linux --output-file requirements.txt` resolves it to 34 exact pins, transitive ones included, for CPython 3.12 on Linux; the command is the lock's header. uv rather than pip-compile because it resolves for a Python and a platform other than the one it runs on. The pins are what resolves today, the newest release of each; nothing was chosen or held back. CI's server job installs the lock and the package in one resolve, so the suite runs on the deployed versions, and a lock that no longer satisfies a floor fails the install. The lock is part of the pip cache key, and requirements.in is on the server job's path filter. test_requirements_mirror.py now holds the three files level: the input is pyproject's deployed share (both directions and the same specifiers, as before); every lock line is one `==` pin; every input requirement is pinned at a version its floor and the httpx ceiling allow; the lock marks exactly the input's packages as `-r requirements.in`, so an input edited without a regeneration is caught; the header names the command, Linux and .python-version's Python; and the lock is closed and minimal on Linux/3.12 by the installed packages' own metadata — skipped, with the command to fix it, in a local environment not installed from the lock, and a failure instead under CI. Each was run red against a mutated file. The two httpx-bound tests in test_diary_client.py read the lock's input rather than the lock, which pins one version and has no ceiling to find. Dependabot's root entry moves from pip to uv: the uv updater regenerates a uv-compiled file with uv and keeps `--python-version` from the header, where the pip updater would rerun it with pip-compile. Its default strategy raises the input's floor with the pin, so a bump of a direct dependency still needs the floor raised in pyproject.toml by hand, as before; the github-pr skill says so, and the mirror test names the package. Not covered: the dev tools, uvicorn, aiosqlite and alembic are not locked and still float in CI — a ruff or mypy release can still turn CI red with no change here. The Docker image installs pyproject.toml's floors, unpinned. Verified on Windows with Python 3.13 only: a fresh venv from the lock plus `-e ".[dev]"`, and the lock reproduced byte for byte from its header; nothing here ran on 3.12 or on Linux, and the dependabot entry has not run. Closes #192 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/agents/deploy-ops.md | 4 +- .claude/skills/gates/SKILL.md | 4 +- .claude/skills/github-pr/SKILL.md | 18 +- .github/CODEOWNERS | 1 + .github/dependabot.yml | 23 +- .github/workflows/ci.yml | 20 +- CLAUDE.md | 5 +- docs/build.md | 7 + docs/deploy.md | 3 +- requirements.in | 48 +++++ requirements.txt | 123 +++++++++-- server/tests/test_diary_client.py | 14 +- server/tests/test_requirements_mirror.py | 264 ++++++++++++++++++++--- 13 files changed, 451 insertions(+), 83 deletions(-) create mode 100644 requirements.in diff --git a/.claude/agents/deploy-ops.md b/.claude/agents/deploy-ops.md index 7f28d492..b9e3eeff 100644 --- a/.claude/agents/deploy-ops.md +++ b/.claude/agents/deploy-ops.md @@ -11,7 +11,9 @@ You diagnose production. Read `docs/deploy.md` first; it is current. One process holds the FastAPI app and the aiogram dispatcher. `api/` at the repository root is a thin Vercel entry point that re-exports `server/app/main.py`. `requirements.txt` at the root exists only because Vercel's Python builder does not read `pyproject.toml` from a -subdirectory — **and it must stay level with it.** +subdirectory. It is a lock compiled by `uv pip compile` from `requirements.in` (#192), and +**`requirements.in` must stay level with `pyproject.toml`**; regenerate the lock with the +command in its header rather than editing a pin. Locally the bot long-polls from the `app/main.py` lifespan; on serverless it is a webhook. `RUN_BOT=false` starts the API alone. diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index ddca164b..a33d8413 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -9,7 +9,9 @@ description: Run the checks this project actually gates on, in the right order, ## Server, from `server/` -Setup once: `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` +Setup once: `python3 -m venv .venv && .venv/bin/pip install -r ../requirements.txt -e ".[dev]"` +— the lock Vercel installs, then the package, which is exactly CI's install (#192). Without +the `-r` you test on whatever is newest today, which production does not run. 1. `ruff check app tests scripts migrations` — exactly what CI lints. `ruff check .` from `server/` covers the same tree. diff --git a/.claude/skills/github-pr/SKILL.md b/.claude/skills/github-pr/SKILL.md index f7260b9f..8263cc3c 100644 --- a/.claude/skills/github-pr/SKILL.md +++ b/.claude/skills/github-pr/SKILL.md @@ -179,13 +179,17 @@ like any other pull request. ### What a bump needs before it is merged, either way -- **`requirements.txt` and `server/pyproject.toml` hold the same floors, and dependabot - edits only the first.** CI installs pyproject and Vercel installs requirements, so a floor - raised in one file alone means tests against one version and a deployment on another. - `test_requirements_mirror.py` fails and names the packages; raise both. -- **Install what the bump declares before running the suite.** A floor of `>=2.0.54` proves - nothing while the environment still holds 2.0.53 — upgrade first, then `pytest`, or the - green is about the old version. +- **`requirements.in` and `server/pyproject.toml` hold the same floors, and dependabot + edits only the first.** `requirements.txt` is the lock compiled from `requirements.in` + (#192), and the `uv` entry moves them together: a bump of a package the input names raises + its floor there and its pin in the lock. `pyproject.toml` is not in that directory, so + `test_requirements_mirror.py` fails and names the package; raise the floor in + `pyproject.toml` to match, and touch nothing in the lock — it is regenerated, never + edited. A bump of a transitive package changes the lock alone and needs nothing. +- **Install what the bump declares before running the suite.** For a lock bump that is + `pip install -r ../requirements.txt -e ".[dev]"` from `server/`, which is what CI runs; a + floor of `>=2.0.54` proves nothing while the environment still holds 2.0.53, and the green + is then about the old version. - **Both halves of the gates** (`gates` skill). For an AGP or Gradle bump `assembleRelease` is the one that matters: R8 and resource shrinking run inside the build being moved. - **A bump that turns a test red is held, understood, and only then taken.** compose-bom diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 94f9eac6..cf5bc587 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -27,6 +27,7 @@ /.github/ @lumenpearson /vercel.json @lumenpearson /requirements.txt @lumenpearson +/requirements.in @lumenpearson # The documents people read. /docs/ @lumenpearson diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d541cb6a..837ebf94 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,10 +1,11 @@ version: 2 -# Three ecosystems and no npm: there is no Node in this repository at all. +# Four ecosystems and no npm: there is no Node in this repository at all. # # gradle -> android/ (settings.gradle.kts and gradle/libs.versions.toml) # pip -> server/ (pyproject.toml, the full set including dev) -# pip -> / (requirements.txt, which is what Vercel installs) +# uv -> / (requirements.in and its lock, requirements.txt, +# which is what Vercel installs) # actions -> / (.github/workflows) # # The Android versions in libs.versions.toml are not invented: they are carried @@ -82,11 +83,19 @@ updates: - asyncpg - aiosqlite - # The same set, a second file: Vercel installs from the root requirements.txt, - # because its Python builder does not read pyproject.toml from a subdirectory. - # A drift between the two files is the difference between what the tests cover - # and what runs in production, so both have to be updated. - - package-ecosystem: pip + # The lock Vercel installs: requirements.txt, compiled by `uv pip compile` + # from requirements.in (#192). `uv` rather than `pip`, because the uv updater + # is the one that regenerates a uv-compiled file with uv, and it re-reads + # `--python-version` from the lock's header; the pip updater would rerun it + # with pip-compile. It does not re-read `--python-platform`, and does not + # need to: it runs on Linux, the platform the header names. + # + # A bump of a package requirements.in names also raises its floor there, + # and pyproject.toml is not in this directory — test_requirements_mirror + # fails and names it, and the floor is raised in pyproject.toml by hand + # (the github-pr skill, "Dependabot's pull requests"). A bump of anything + # else touches the lock alone. + - package-ecosystem: uv directory: / schedule: interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6dcf6eb8..6e7936b4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,8 +103,10 @@ jobs: # test_env_example), `docs/diaries/regions.md` is the region # catalog's input and `docs/diaries.md` its table # (test_region_catalog), `docs/diaries/netschool.md` is quoted by - # test_netschool_mapper. - server/*|api/*|requirements.txt|docs/deploy.md|docs/build.md|docs/diaries.md|docs/diaries/*|.github/workflows/*) server=true ;; + # test_netschool_mapper. `requirements.in` is the input of the + # lock `requirements.txt`, and test_requirements_mirror holds the + # two level with pyproject.toml. + server/*|api/*|requirements.txt|requirements.in|docs/deploy.md|docs/build.md|docs/diaries.md|docs/diaries/*|.github/workflows/*) server=true ;; esac done <<< "$files" @@ -126,9 +128,19 @@ jobs: with: python-version: "3.12" cache: pip - cache-dependency-path: server/pyproject.toml + cache-dependency-path: | + requirements.txt + server/pyproject.toml + # The lock and the package in one resolve (#192). The lock is what + # Vercel installs, so the suite runs on the versions production gets + # rather than on whatever was newest the morning CI ran — which is how + # SQLAlchemy 2.1 reached the tests and the deployment unannounced + # (#164). pyproject.toml adds on top what the function does without: + # uvicorn, aiosqlite, alembic and the dev tools, which are not locked + # and still float. A lock that no longer satisfies one of its floors + # fails here, at the install, rather than in production. - name: Install - run: pip install -e ".[dev]" + run: pip install -r ../requirements.txt -e ".[dev]" - name: Lint run: ruff check app tests scripts migrations # `-n auto`, because this step was the whole run. It was twelve and a diff --git a/CLAUDE.md b/CLAUDE.md index c2ddd6b5..18b07914 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,7 +35,10 @@ cookie, no build step. Do not grow it into a second admin surface: anything the express belongs in the bot. `requirements.txt` at the root exists only because Vercel's Python builder does not read -`pyproject.toml` from a subdirectory — and it must stay level with it. +`pyproject.toml` from a subdirectory. It is a lock (#192) — every package the function can +import, at one exact version, for CPython 3.12 on Linux — compiled by `uv pip compile` from +`requirements.in`, which must stay level with `pyproject.toml`. The lock's header is the +command; never edit a pin by hand. CI installs the lock too, so the tests run on what deploys. ## Commands diff --git a/docs/build.md b/docs/build.md index 62ade838..a9a52b1b 100644 --- a/docs/build.md +++ b/docs/build.md @@ -19,6 +19,13 @@ python3 -m venv .venv && .venv/bin/pip install -e ".[dev]" cp .env.example .env ``` +That installs the newest release of everything `pyproject.toml` allows. CI and the +deployment do not: both install the root `requirements.txt`, a lock of the versions +production runs (#192), and CI adds the package on top — +`pip install -r ../requirements.txt -e ".[dev]"`. Do the same when a test passes here and +fails there, or the other way round; `test_requirements_mirror.py` skips one check, and says +so, in an environment that is not the lock's. + ### Four steps, and you can stop after any of them Each is worth doing before the next: everything in a later one depends on the earlier ones diff --git a/docs/deploy.md b/docs/deploy.md index 1efe9b77..34baa241 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -584,7 +584,8 @@ Any VPS with 1 GB of memory will do. One class's load is a few hundred requests | --- | --- | | `api/index.py` | the entry point; a thin re-export of `app.main:app`, so that serverless and `uvicorn` run the same code | | `vercel.json` | the region, the install command and the function's `maxDuration`. **There is no rewrite in it and there must not be:** with `"/(.*)" → "/api/index"` Vercel routes by the *rewritten* path, so FastAPI received a literal `/api/index`, and the health check, the client API and the Telegram webhook all answered 404 at once. Removed in PR #5 (`e99d8ca`); this line described something that was not in the file for a year — whoever puts it back will reproduce the same outage | -| `requirements.txt` | Vercel does not read `pyproject.toml` from a subdirectory; this holds `asyncpg` only, no `aiosqlite` | +| `requirements.txt` | what Vercel installs, because its builder does not read `pyproject.toml` from a subdirectory. A lock, not a list (#192): every package the function can import, transitive ones included, at one exact version, resolved for CPython 3.12 on Linux. Not written by hand — its header is the `uv pip compile` command that regenerates it. CI installs the same file together with the package, so the suite runs on the versions production gets; while it held floors, each deploy installed whatever was newest that day | +| `requirements.in` | the lock's input: `server/pyproject.toml`'s runtime dependencies, character for character, less what the function does without — `asyncpg` only, no `aiosqlite`, and no `uvicorn`, `alembic` or `tzdata`. Edit it with `pyproject.toml`, then regenerate the lock; `test_requirements_mirror.py` holds the three level | | `.vercelignore` | keeps `android/`, the tests and the documentation out of the bundle | ## Which to choose diff --git a/requirements.in b/requirements.in new file mode 100644 index 00000000..cd90c41b --- /dev/null +++ b/requirements.in @@ -0,0 +1,48 @@ +# What the Vercel function needs, and nothing else: the input of the lock. +# +# Vercel installs requirements.txt from the repository root (vercel.json's +# installCommand), because its Python builder does not read pyproject.toml +# from a subdirectory. That file is not written by hand. It is this list +# resolved to one exact version of every package, transitive ones included, +# for CPython 3.12 on Linux: .python-version's Python and CI's, on the +# platform the function runs on. While it held these floors instead, every +# deploy installed whatever was newest that day: SQLAlchemy 2.1 reached +# production and CI unannounced, and a checkout set up the week before went +# on testing 2.0 (#164, #192). +# +# After editing this file, regenerate the lock from the repository root with +# the command written in its header (`pip install uv` if you have no uv). uv +# rather than pip-compile, because it resolves for a Python and a platform +# other than the one it runs on, and pip-compile answers for the interpreter +# that runs it — on the owner's Windows machine, neither Linux nor 3.12. +# Without `--upgrade` it keeps every pin the edit does not force to move; +# `--upgrade-package NAME` moves one package, `--upgrade` moves them all. +# Keep the two names as they are: dependabot pairs the lock with its input by +# swapping .in for .txt, not by reading the header, whose order it cannot +# parse. +# +# CI installs the lock and the package in one resolve, so the suite runs on +# the versions the deployment gets, and a lock that no longer satisfies a +# floor fails CI's install rather than the deployment. +# +# The requirements are server/pyproject.toml's, character for character, and +# server/tests/test_requirements_mirror.py holds both that and the lock. +# +# asyncpg only: the serverless database is Postgres, and aiosqlite would be +# dead weight in the function bundle. +fastapi>=0.141.1 +aiogram>=3.31.0 +sqlalchemy[asyncio]>=2.0.54 +asyncpg>=0.31.0 +pydantic>=2.13.5 +pydantic-settings>=2.15.0 +# The DI container in server/app/di.py. Pure Python, and 26 ms on top of +# fastapi and sqlalchemy on a cold start — measured, because this bundle pays +# for every import on every one of them. +dishka>=1.10.1 +# Level with server/pyproject.toml, ceiling included: every diary call passes +# per-request cookies, which httpx 0.28 warns it is removing, and a release +# that removed them would send every diary call without a session rather than +# fail. What to check before raising it is written out in pyproject.toml. +httpx>=0.28.1,<0.29 +cryptography>=50.0.1 diff --git a/requirements.txt b/requirements.txt index 0781a021..1097b635 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,22 +1,101 @@ -# Vercel installs from the repository root. The server's own dependency set -# lives in server/pyproject.toml; this file mirrors it because Vercel's Python -# builder does not read pyproject from a subdirectory. -# -# asyncpg only: the serverless database is Postgres, and aiosqlite would be -# dead weight in the function bundle. -fastapi>=0.141.1 -aiogram>=3.31.0 -sqlalchemy[asyncio]>=2.0.54 -asyncpg>=0.31.0 -pydantic>=2.13.5 -pydantic-settings>=2.15.0 -# The DI container in server/app/di.py. Pure Python, and 26 ms on top of -# fastapi and sqlalchemy on a cold start — measured, because this bundle pays -# for every import on every one of them. -dishka>=1.10.1 -# Level with server/pyproject.toml, ceiling included: every diary call passes -# per-request cookies, which httpx 0.28 warns it is removing, and a release -# that removed them would send every diary call without a session rather than -# fail. What to check before raising it is written out in pyproject.toml. -httpx>=0.28.1,<0.29 -cryptography>=50.0.1 +# This file was autogenerated by uv via the following command: +# uv pip compile requirements.in --python-version 3.12 --python-platform linux --output-file requirements.txt +aiofiles==25.1.0 + # via aiogram +aiogram==3.31.0 + # via -r requirements.in +aiohappyeyeballs==2.7.1 + # via aiohttp +aiohttp==3.14.3 + # via aiogram +aiosignal==1.4.0 + # via aiohttp +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.15.1 + # via + # httpx + # starlette +asyncpg==0.31.0 + # via -r requirements.in +attrs==26.1.0 + # via aiohttp +certifi==2026.7.22 + # via + # aiogram + # httpcore + # httpx +cffi==2.1.1 + # via cryptography +cryptography==50.0.1 + # via -r requirements.in +dishka==1.10.1 + # via -r requirements.in +fastapi==0.141.1 + # via -r requirements.in +frozenlist==1.8.0 + # via + # aiohttp + # aiosignal +greenlet==3.5.6 + # via sqlalchemy +h11==0.16.0 + # via httpcore +httpcore==1.0.9 + # via httpx +httpx==0.28.1 + # via -r requirements.in +idna==3.20 + # via + # anyio + # httpx + # yarl +magic-filter==1.0.12 + # via aiogram +multidict==6.9.1 + # via + # aiohttp + # yarl +propcache==0.5.4 + # via + # aiohttp + # yarl +pycparser==3.0 + # via cffi +pydantic==2.13.5 + # via + # -r requirements.in + # aiogram + # fastapi + # pydantic-settings +pydantic-core==2.46.5 + # via pydantic +pydantic-settings==2.15.0 + # via -r requirements.in +python-dotenv==1.2.3 + # via pydantic-settings +sqlalchemy==2.1.1 + # via -r requirements.in +starlette==1.7.0 + # via fastapi +typing-extensions==4.16.0 + # via + # aiogram + # aiohttp + # aiosignal + # anyio + # fastapi + # pydantic + # pydantic-core + # sqlalchemy + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic + # pydantic-settings +yarl==1.25.1 + # via aiohttp diff --git a/server/tests/test_diary_client.py b/server/tests/test_diary_client.py index b7b15373..52bf24bd 100644 --- a/server/tests/test_diary_client.py +++ b/server/tests/test_diary_client.py @@ -121,9 +121,11 @@ async def shared(): "path", [ pathlib.Path(__file__).resolve().parents[1] / "pyproject.toml", - pathlib.Path(__file__).resolve().parents[2] / "requirements.txt", + # The lock's input, not the lock: the lock pins one version, and this + # bound is what every regeneration of it obeys. + pathlib.Path(__file__).resolve().parents[2] / "requirements.in", ], - ids=["pyproject", "requirements"], + ids=["pyproject", "requirements-in"], ) def test_httpx_is_bounded_above_because_this_client_depends_on_a_deprecation(path): """Every diary call is ``request(..., cookies=...)``, which httpx 0.28 @@ -143,13 +145,13 @@ def test_httpx_is_bounded_above_because_this_client_depends_on_a_deprecation(pat def test_the_two_places_httpx_is_pinned_say_the_same_thing(): - """``requirements.txt`` exists only because Vercel's builder cannot read a + """``requirements.in`` exists only because Vercel's builder cannot read a pyproject in a subdirectory, so it is a copy — and a copy that drifts is - worse than no copy, because the deployed set is the one nobody runs tests - against.""" + worse than no copy, because the lock Vercel installs is compiled from it, + not from the file the tests declare.""" here = pathlib.Path(__file__).resolve() assert _httpx_specifier((here.parents[1] / "pyproject.toml").read_text()) == _httpx_specifier( - (here.parents[2] / "requirements.txt").read_text() + (here.parents[2] / "requirements.in").read_text(encoding="utf-8") ) diff --git a/server/tests/test_requirements_mirror.py b/server/tests/test_requirements_mirror.py index 76c527e5..26250bc6 100644 --- a/server/tests/test_requirements_mirror.py +++ b/server/tests/test_requirements_mirror.py @@ -1,12 +1,18 @@ -"""The two dependency lists that have to say the same thing. +"""What Vercel installs, and what keeps it the set the tests ran on. ``requirements.txt`` at the repository root exists for one reason: Vercel's -Python builder does not read a ``pyproject.toml`` from a subdirectory. So the -deployed set is installed from the copy, and every test in this suite runs -against the original — which makes drift between them the one kind of -dependency bug nothing else here can see. A floor raised in ``pyproject.toml`` -because a handler started calling a new API installs fine in CI and ships a -function that imports the old one. +Python builder does not read a ``pyproject.toml`` from a subdirectory. It used +to be a copy of the floors, so every deploy installed whatever was newest that +day and nothing tested that set (#192). It is a lock now: ``requirements.in`` +beside it is the deployed share of ``server/pyproject.toml``'s dependencies, +and ``requirements.txt`` is that list resolved by ``uv pip compile`` to one +exact version of every package the function can import. CI installs the lock +together with the package, so the suite runs on exactly those versions. + +Three files, and three ways for them to come apart: a floor raised in +``pyproject.toml`` because a handler started calling a new API, and not in the +lock's input; an input edited and the lock not regenerated; a pin edited by +hand that leaves the deploy to choose a package for itself. The httpx ceiling has its own pair of tests in ``test_diary_client.py``, because *that* bound is about a deprecation rather than about the mirror. @@ -14,13 +20,22 @@ from __future__ import annotations +import os import pathlib import re import tomllib +from importlib import metadata + +import pytest +from packaging.requirements import Requirement +from packaging.utils import NormalizedName, canonicalize_name +from packaging.version import Version ROOT = pathlib.Path(__file__).resolve().parents[2] PYPROJECT = ROOT / "server" / "pyproject.toml" -REQUIREMENTS = ROOT / "requirements.txt" +LOCK_INPUT = ROOT / "requirements.in" +LOCK = ROOT / "requirements.txt" +PYTHON_VERSION = ROOT / ".python-version" #: Deliberately not in the function bundle, each for a reason written down #: where it is left out. ``uvicorn`` is the local server and Vercel brings its @@ -30,28 +45,66 @@ #: platform without its own, and Vercel runs Linux (#170). DEPLOYED_WITHOUT = {"uvicorn", "aiosqlite", "alembic", "tzdata"} -_NAME = re.compile(r"^[A-Za-z0-9._-]+") +#: What an environment marker is asked on the function's platform: CPython on +#: x86-64 Linux, at the Python the lock's header names. Only what a marker in +#: this dependency tree can plausibly ask is spelled out; the rest is left to +#: ``packaging``'s defaults, which no marker here reads. +_LINUX = { + "os_name": "posix", + "sys_platform": "linux", + "platform_system": "Linux", + "platform_machine": "x86_64", + "implementation_name": "cpython", + "platform_python_implementation": "CPython", +} + + +def _requirements(path: pathlib.Path) -> list[str]: + """Every requirement line of a pip requirements file, comments dropped.""" + return [ + line.split(" #", 1)[0].strip() + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] -def _name(requirement: str) -> str: - """``httpx>=0.28.1,<0.29`` → ``httpx``, ``uvicorn[standard]>=0.30`` → ``uvicorn``.""" - match = _NAME.match(requirement.strip()) - assert match, requirement - return match.group(0).lower().replace("_", "-") +def _by_name(requirements: list[str]) -> dict[NormalizedName, str]: + return {canonicalize_name(Requirement(item).name): item.strip() for item in requirements} -def _declared() -> dict[str, str]: +def _declared() -> dict[NormalizedName, str]: data = tomllib.loads(PYPROJECT.read_text(encoding="utf-8")) - return {_name(item): item.strip() for item in data["project"]["dependencies"]} + return _by_name(data["project"]["dependencies"]) -def _deployed() -> dict[str, str]: - lines = [ - line.strip() - for line in REQUIREMENTS.read_text(encoding="utf-8").splitlines() - if line.strip() and not line.lstrip().startswith("#") - ] - return {_name(line): line for line in lines} +def _deployed() -> dict[NormalizedName, str]: + return _by_name(_requirements(LOCK_INPUT)) + + +def _pins() -> dict[NormalizedName, str]: + """``name -> version`` for every line of the lock that pins one; + ``test_the_lock_pins_every_package_to_one_version`` names the others.""" + pins: dict[NormalizedName, str] = {} + for line in _requirements(LOCK): + requirement = Requirement(line) + specifiers = list(requirement.specifier) + if len(specifiers) == 1 and specifiers[0].operator == "==": + pins[canonicalize_name(requirement.name)] = specifiers[0].version + return pins + + +def _header() -> str: + lines = LOCK.read_text(encoding="utf-8").splitlines() + return "\n".join(line for line in lines[:5] if line.startswith("#")) + + +def _compiled_python() -> str: + match = re.search(r"--python-version[= ](\S+)", _header()) + assert match, "the lock's header does not say which Python it was resolved for" + return match.group(1) + + +# ---- the input: the deployed share of pyproject.toml ---------------------- def test_every_dependency_the_code_needs_is_in_the_deployed_set(): @@ -61,27 +114,29 @@ def test_every_dependency_the_code_needs_is_in_the_deployed_set(): if name not in DEPLOYED_WITHOUT and name not in _deployed() } assert not missing, ( - "requirements.txt does not install: " + "requirements.in does not ask for: " + ", ".join(sorted(missing)) - + " — Vercel installs from it, so the function would import what is not there." + + " — Vercel installs its lock, so the function would import what is not there." ) def test_the_deployed_set_installs_nothing_the_project_does_not_declare(): - """The other direction: a package only the copy knows about is a package - nothing tests against, and it stays in the bundle long after whatever + """The other direction: a package only the lock's input knows about is a + package nothing declares, and it stays in the bundle long after whatever wanted it is gone.""" extra = set(_deployed()) - set(_declared()) - assert not extra, f"requirements.txt names what pyproject.toml does not: {sorted(extra)}" + assert not extra, f"requirements.in names what pyproject.toml does not: {sorted(extra)}" -def test_the_two_lists_pin_the_same_versions(): - """A floor raised in one place only is invisible until production. +def test_the_two_lists_ask_for_the_same_versions(): + """A floor raised in one place only is a floor one of the two installs + ignores. ``aiogram>=3.31`` is the example that is already written down: below it every coloured keyboard raises at construction. Raising that floor in - ``pyproject.toml`` alone would leave CI green — it installs the original — - and give the deployment a bot whose every menu throws. + ``pyproject.toml`` alone and leaving the lock's input behind would keep + the deployment on whatever the lock held — until the next regeneration, + which reads the input and would happily keep it there. """ declared, deployed = _declared(), _deployed() differing = { @@ -89,4 +144,147 @@ def test_the_two_lists_pin_the_same_versions(): for name in sorted(set(declared) & set(deployed)) if declared[name] != deployed[name] } - assert not differing, f"the two lists disagree: {differing}" + assert not differing, f"pyproject.toml and requirements.in disagree: {differing}" + + +# ---- the lock: requirements.txt -------------------------------------------- + + +def test_the_lock_pins_every_package_to_one_version(): + """A range left in the lock is a version the deploy chooses on the day, + which is exactly what the lock exists to stop.""" + loose = [] + for line in _requirements(LOCK): + requirement = Requirement(line) + specifiers = list(requirement.specifier) + if ( + len(specifiers) != 1 + or specifiers[0].operator != "==" + or "*" in specifiers[0].version + or requirement.url + ): + loose.append(line) + assert not loose, f"requirements.txt must pin with == and nothing else: {loose}" + + +def test_every_deployed_requirement_is_pinned_at_a_version_it_allows(): + """The floors and the httpx ceiling, held against what is actually + deployed. CI's install would refuse the pair as well — this names the + package and the fix, where pip names a resolution conflict.""" + pins = _pins() + wrong = {} + for name, line in _deployed().items(): + requirement = Requirement(line) + pinned = pins.get(name) + if pinned is None or not requirement.specifier.contains(pinned, prereleases=True): + wrong[name] = (line, pinned) + assert not wrong, ( + f"requirements.txt pins versions its input refuses: {wrong} — regenerate it with the " + "command in its header" + ) + + +def test_the_lock_was_compiled_from_this_input(): + """uv marks each package the input asked for by name with ``-r + requirements.in``. A package added to the input with no regeneration is + missing from the lock; one removed is still marked there, and still + deployed.""" + direct: set[NormalizedName] = set() + current: NormalizedName | None = None + for line in LOCK.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if stripped and not stripped.startswith("#"): + current = canonicalize_name(Requirement(stripped).name) + elif current is not None and "-r requirements.in" in stripped: + direct.add(current) + assert direct == set(_deployed()), ( + f"the lock was compiled from another input: it marks {sorted(direct)}, " + f"requirements.in asks for {sorted(_deployed())} — regenerate it with the command " + "in its header" + ) + + +def test_the_lock_is_resolved_for_the_python_and_platform_the_function_runs_on(): + """A lock answers for one Python on one platform. Resolved for another, it + can pin a release that does not install on the function's, or leave out a + dependency only the function's needs — which the deploy then picks for + itself. ``.python-version`` is this repository's statement of that + Python, and CI's ``setup-python`` asks for the same one.""" + header = _header() + assert "uv pip compile requirements.in" in header, ( + "the lock's header no longer names the command that regenerates it" + ) + assert "--python-platform linux" in header, "the function runs on Linux" + assert _compiled_python() == PYTHON_VERSION.read_text(encoding="utf-8").strip(), ( + "requirements.txt was resolved for another Python than .python-version names" + ) + + +def test_the_lock_is_exactly_what_the_input_needs_on_the_function_platform(): + """Every package a pinned package needs on the function's platform is + pinned too, and nothing else is. + + ``pip install -r requirements.txt`` resolves: a dependency the lock does + not name is still installed, at whatever version is newest that day. uv + writes a closed lock, so this can only go wrong by hand — a pin moved to a + release that brought a new dependency along, or a line added that nothing + asks for and that nothing tests. The dependencies are read from the + installed packages' own metadata, which is the metadata of the pinned + versions only where the environment was installed from the lock; CI's + always is, and a local environment that is not is skipped with the command + that makes it so. + """ + pins = _pins() + stale = { + name: version + for name, version in pins.items() + if (installed := _installed_version(name)) is None or Version(installed) != Version(version) + } + if stale: + message = ( + f"this environment is not the lock's ({len(stale)} packages differ, " + f'{sorted(stale)[:3]}…): pip install -r ../requirements.txt -e ".[dev]"' + ) + if os.environ.get("CI"): + pytest.fail(message) + pytest.skip(message) + + environment = {**_LINUX, "python_version": _compiled_python()} + environment["python_full_version"] = environment["python_version"] + ".0" + + unpinned: dict[str, set[str]] = {} + seen: set[tuple[NormalizedName, frozenset[str]]] = set() + queue = [ + (canonicalize_name(r.name), frozenset(r.extras)) + for r in map(Requirement, _deployed().values()) + ] + while queue: + name, extras = queue.pop() + if (name, extras) in seen: + continue + seen.add((name, extras)) + for line in metadata.requires(name) or []: + requirement = Requirement(line) + if requirement.marker and not any( + requirement.marker.evaluate({**environment, "extra": extra}) + for extra in {"", *extras} + ): + continue + needed = canonicalize_name(requirement.name) + if needed not in pins: + unpinned.setdefault(needed, set()).add(name) + continue + queue.append((needed, frozenset(requirement.extras))) + assert not unpinned, ( + f"requirements.txt leaves these to the deploy: {unpinned} — regenerate it with the " + "command in its header rather than editing a pin" + ) + orphans = set(pins) - {name for name, _ in seen} + assert not orphans, f"requirements.txt pins what nothing deployed needs: {sorted(orphans)}" + + +def _installed_version(name: str) -> str | None: + try: + return metadata.version(name) + except metadata.PackageNotFoundError: + return None From 2f8b920ef93b9f7d6ce55e51056bc9b01a8831e2 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 17:18:10 +0300 Subject: [PATCH 30/43] Run mypy in CI, right after ruff, on the versions the deployment gets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `python -m mypy` asks one question of the whole server — does anything reach for an attribute its type does not have — and it is the check that reproduces the «🗓 Четверти» crash. It was clean, and it ran only when somebody remembered it: the owner asked for it as a gate through the audit of 27 September 2026 (#210). It is now the server job's `Type check` step, between `Lint` and `Test`, in the same plain shape as ruff: a finding stops the job before the suite, as a lint finding already does. It runs against the lock the job now installs, which matters for mypy in particular — SQLAlchemy 2.1 alone once made it unclean with no change to the code (#164). Fourteen seconds from cold here. The sentences that said mypy is not in CI are corrected where they stood: CLAUDE.md's mypy bullet, the gates skill's step (and its stale module count, 81 to 100), the steward skill, the build-ci agent, AGENTS.md and CONTRIBUTING.md, whose lists of what CI runs now name it. Left for the merge, because the detekt branch rewrites the same lines: CLAUDE.md's "CI (`.github/workflows/ci.yml`) is:" line and the gates skill's "What CI is". Not covered: the Kotlin half of #210 is another branch's. mypy itself is a dev dependency and is not locked, so a mypy release can turn this step red with no change here. The step has not run on GitHub; it was run locally on Windows with Python 3.13, clean on 100 files. Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/agents/build-ci.md | 9 +++++---- .claude/skills/gates/SKILL.md | 7 ++++--- .claude/skills/steward/SKILL.md | 9 +++++---- .github/workflows/ci.yml | 12 ++++++++++++ AGENTS.md | 4 ++-- CLAUDE.md | 5 +++-- CONTRIBUTING.md | 17 +++++++++-------- 7 files changed, 40 insertions(+), 23 deletions(-) diff --git a/.claude/agents/build-ci.md b/.claude/agents/build-ci.md index 366edb96..87c7106c 100644 --- a/.claude/agents/build-ci.md +++ b/.claude/agents/build-ci.md @@ -8,10 +8,11 @@ You own `.github/`. **The workflows work — do not edit them casually.** ## What CI is -`ci.yml` is: `ruff`, `pytest -n auto`, `./gradlew test`, `assembleDebug`, `assembleRelease`. -Nothing else. `python -m mypy` is **not** in CI (the owner has not been asked) but is run -before server code is pushed. `./gradlew lint` is not in CI either — do not report it as a -gate. +`ci.yml` is: `ruff`, `python -m mypy`, `pytest -n auto`, `./gradlew test`, `assembleDebug`, +`assembleRelease`. Nothing else. mypy joined on 27 September 2026, when the owner asked for +it through that day's audit (#210). The server job installs the root `requirements.txt` — +the lock Vercel installs — together with the package (#192), so its verdict is about the +deployed versions. `./gradlew lint` is not in CI — do not report it as a gate. `apk.yml` builds an installable APK on demand or on a `v*` tag. Its keystore step checks all four `LESSONS_KEYSTORE_*` secrets and fails with `::error::` if any is empty, because a diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index a33d8413..2cd3c8bb 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -15,10 +15,11 @@ the `-r` you test on whatever is newest today, which production does not run. 1. `ruff check app tests scripts migrations` — exactly what CI lints. `ruff check .` from `server/` covers the same tree. -2. `python -m mypy` — one question of all 81 modules, in seconds: does anything reach for an +2. `python -m mypy` — one question of all 100 modules, in seconds: does anything reach for an attribute its type does not have? Every other error code is switched off by name in - `pyproject.toml`, with its count and its reason. **Not in CI** — the owner has not been - asked — but run it before you push server code. It is the thing that reproduces the + `pyproject.toml`, with its count and its reason. **In CI** since 27 September 2026, right + after ruff — the owner asked for it through that day's audit (#210) — and still worth + running before a push: seconds here, minutes there. It is the thing that reproduces the «🗓 Четверти» crash. 3. `python -m pytest -q -n auto` — 1559 tests today. Serial takes about five minutes; `-n auto` finishes in a third of that and is what CI runs. diff --git a/.claude/skills/steward/SKILL.md b/.claude/skills/steward/SKILL.md index b4d7dd21..3f202526 100644 --- a/.claude/skills/steward/SKILL.md +++ b/.claude/skills/steward/SKILL.md @@ -31,13 +31,14 @@ One validated push beats three speculative ones. ## What a CI failure here usually is -`.github/workflows/ci.yml` is ruff, pytest `-n auto`, `./gradlew test`, and **both** -assembles. If `assembleRelease` is the one that failed and `assembleDebug` passed, look at +`.github/workflows/ci.yml` is ruff, `python -m mypy`, pytest `-n auto`, `./gradlew test`, +and **both** assembles. If `assembleRelease` is the one that failed and `assembleDebug` passed, look at R8 and resource shrinking before anything else — that is what the second assemble exists to catch. -`./gradlew lint` is **not** in CI and `python -m mypy` is **not** in CI. A finding from -either is real, but it is not the thing that turned the check red. +`./gradlew lint` is **not** in CI. A finding from it is real, but it is not the thing that +turned the check red. `python -m mypy` **is**, since 27 September 2026 (#210): a red +`Type check` step in the server job is mypy's. A failing `ResourceTranslationTest` means a name is missing from a module's `values-en/`, or a plural has the wrong forms — see the `strings` skill. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e7936b4..7cdf87eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,6 +143,18 @@ jobs: run: pip install -r ../requirements.txt -e ".[dev]" - name: Lint run: ruff check app tests scripts migrations + # One question of the whole server: does anything reach for an attribute + # its type does not have? «🗓 Четверти» crashed on every press in + # production because a card printed `term.days` off a type that has + # none, and this reproduces it; every other error code is switched off + # by name in pyproject.toml, with its count and its reason. It ran only + # when somebody remembered to until the owner asked for it here (#210), + # and it runs against the locked versions installed above, which is + # where its verdict comes from: SQLAlchemy 2.1 alone made it unclean + # once, with no change to the code (#164). Fourteen seconds from cold + # on a laptop. + - name: Type check + run: python -m mypy # `-n auto`, because this step was the whole run. It was twelve and a # half minutes of a twenty-one minute CI run and is now three and a # half: that started as a bill to cut and stayed for the feedback. The diff --git a/AGENTS.md b/AGENTS.md index 546a7299..b567ab09 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,8 +42,8 @@ From `android/` (JDK 21, compileSdk 37, wrapper Gradle): ./gradlew assembleRelease ``` -CI is exactly: ruff, pytest `-n auto`, `./gradlew test`, both assembles. `./gradlew lint` is -**not** a gate. `python -m mypy` is not in CI but is run before server code is pushed. +CI is exactly: ruff, `python -m mypy`, pytest `-n auto`, `./gradlew test`, both assembles. +`./gradlew lint` is **not** a gate. `--offline` is needed for Gradle in a sandbox. **No commit without lint and tests green.** Touch both halves, run both. diff --git a/CLAUDE.md b/CLAUDE.md index 18b07914..58834768 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,8 +60,9 @@ Server, from `server/`: pytest loads by path rather than by import - **`python -m mypy`** — one question, of all 100 modules, in seconds: does anything reach for an attribute its type does not have? Configured in `pyproject.toml`, where every - other error code is switched off by name with its count and its reason. Not in CI — the - owner has not been asked — but run it before you push server code + other error code is switched off by name with its count and its reason. A CI step since + 27 September 2026, right after ruff, because the owner asked for it through that day's + audit (#210) — and still worth running before you push: seconds here, minutes there - `python -m pytest -q tests/test_schedule.py -k parity` — one file, one test - `python -m uvicorn app.main:app --reload` — run it; add `--host 0.0.0.0` for a phone to reach it diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 04bec2ac..8e7a1cb5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,14 +48,15 @@ cp .env.example .env # BOT_TOKEN and OWNER_IDS are your own The first six run from `server/`, the rest from `android/`. -CI (`.github/workflows/ci.yml`) runs exactly this: `ruff`, `pytest -n auto`, -`./gradlew test`, `assembleDebug` and `assembleRelease`. The release build runs on every -push, not only on a release: R8 and resource shrinking are the classic "it worked in debug -and broke in the installed APK", and catching that on a pull request is cheaper than -catching it on people. - -`python -m mypy` is not in CI, but run it before you push server code — it is the only -thing in this project that answers "is this renderer written against a type that exists?" +CI (`.github/workflows/ci.yml`) runs exactly this: `ruff`, `python -m mypy`, +`pytest -n auto`, `./gradlew test`, `assembleDebug` and `assembleRelease`. The release +build runs on every push, not only on a release: R8 and resource shrinking are the classic +"it worked in debug and broke in the installed APK", and catching that on a pull request is +cheaper than catching it on people. + +`python -m mypy` is in CI since 27 September 2026 (#210), but run it before you push server +code anyway — it takes seconds, and it is the only thing in this project that answers "is +this renderer written against a type that exists?" ## Rules that may not be broken From 741ce74884f507756dc06f9849dac2c681e84224 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 18:04:51 +0300 Subject: [PATCH 31/43] Give the bot and /api/v1/manage one implementation of every operation they share MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both shells carried their own copy of running a class: the check in front of a change, the write, the audit line and its Russian wording, and the commit. `services/manage/` now holds each operation once, one module per screen named like the shells' own (subjects, bells, devices, classes, requests, journal, terms, timetable), and the bot handlers and the endpoints only translate: a callback, a paste or a payload in; a message, an alert or JSON out. A refusal is an exception carrying facts (the clashing subject, the days, the number of lessons), so each shell keeps its own words for it and the user-facing text of every refusal is unchanged. Nothing in the new services commits or imports `app.bot`. Moved into one function each: list the subjects (adopting the timetable's names), find a subject, add, rename, set the short name / teacher / colour, delete; list the bell schedules, find one, create, replace its rows, make it the default, delete (and rename, which only the API does); export the template, apply an import with its log line; list the devices' owner roles once per owner, find a device, revoke, unlink; a page of the log; the class card's three counts and the member list; set a class field, the time zone, the join mode; delete the class against its typed name; list and find pending access requests, decline one and its notice; this year's terms, change the scheme, move a term. Approving a request, the statistics and the school search were already one service each. Six copies had drifted, and taking one wording or one rule for both is a visible change on the side that differed: - The bot's time-zone picker (`handlers/start.py`) changed the zone without an audit line; it now logs «часовой пояс: …» as the API did. - A colour removed from the phone was logged «цвет предмета «X»: убрано», from the bot «… убран»; both now write the bot's «убран». - The bot logged a second «отключено устройство» for a phone already revoked (a stale button); now neither side logs a revoke that changes nothing, as the API promised. - The bot's import line never said «перестали звонить N» when the pasted bells stopped ringing stored lessons; now both say it. - `PATCH /manage/class` logged a join-mode line even when the mode was already in force, and the bot's ⭐ logged «основное расписание» for the schedule that already was; neither writes a no-op now. The bot's join-mode switch (`handlers/access.py`) and zone picker (`handlers/start.py`) are touched only where they called the service. Not covered: `/api/v1/edit` and the bot's day-to-day handlers (homework, substitutions, events, special days) are the other pair of shells, with their own audit actions (`day.set` against `dayoverride.set`); they were not part of this. Closes #206 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/api/manage/_common.py | 11 +- server/app/api/manage/bells.py | 157 +++--------- server/app/api/manage/classes.py | 68 ++---- server/app/api/manage/devices.py | 52 +--- server/app/api/manage/journal.py | 15 +- server/app/api/manage/requests.py | 37 +-- server/app/api/manage/subjects.py | 116 +++------ server/app/api/manage/terms.py | 38 +-- server/app/api/manage/timetable.py | 35 +-- server/app/bot/handlers/access.py | 20 +- server/app/bot/handlers/manage/_common.py | 16 +- server/app/bot/handlers/manage/audit_log.py | 8 +- server/app/bot/handlers/manage/bells.py | 120 ++------- server/app/bot/handlers/manage/class_card.py | 48 +--- server/app/bot/handlers/manage/devices.py | 44 ++-- .../app/bot/handlers/manage/import_export.py | 36 +-- server/app/bot/handlers/manage/requests.py | 25 +- server/app/bot/handlers/manage/subjects.py | 103 +++----- server/app/bot/handlers/manage/terms.py | 36 +-- server/app/bot/handlers/start.py | 9 +- server/app/services/manage/__init__.py | 24 ++ server/app/services/manage/bells.py | 227 ++++++++++++++++++ server/app/services/manage/classes.py | 138 +++++++++++ server/app/services/manage/devices.py | 90 +++++++ server/app/services/manage/journal.py | 21 ++ server/app/services/manage/requests.py | 65 +++++ server/app/services/manage/subjects.py | 191 +++++++++++++++ server/app/services/manage/terms.py | 80 ++++++ server/app/services/manage/timetable.py | 68 ++++++ 29 files changed, 1145 insertions(+), 753 deletions(-) create mode 100644 server/app/services/manage/__init__.py create mode 100644 server/app/services/manage/bells.py create mode 100644 server/app/services/manage/classes.py create mode 100644 server/app/services/manage/devices.py create mode 100644 server/app/services/manage/journal.py create mode 100644 server/app/services/manage/requests.py create mode 100644 server/app/services/manage/subjects.py create mode 100644 server/app/services/manage/terms.py create mode 100644 server/app/services/manage/timetable.py diff --git a/server/app/api/manage/_common.py b/server/app/api/manage/_common.py index 85eea2b4..257c0955 100644 --- a/server/app/api/manage/_common.py +++ b/server/app/api/manage/_common.py @@ -7,16 +7,15 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import UTC, datetime -from typing import Any from dishka.integrations.fastapi import FromDishka, inject from fastapi import Depends, HTTPException, status -from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_device -from app.models import BotUser, DeviceToken, Role, SchoolClass +from app.models import DeviceToken, Role, SchoolClass from app.services import linking +from app.services.manage import classes as classes_service # -------------------------------------------------------------------------- # Who may manage @@ -102,17 +101,13 @@ def _person(full_name: str | None, username: str | None, telegram_id: int | None async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: """Telegram id -> the name to show. Plain text: this is JSON, not HTML.""" - members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) + members = await classes_service.members(session, class_id) return { member.telegram_id: _person(member.full_name, member.username, member.telegram_id) for member in members } -async def _count(session: AsyncSession, model: Any, *where: Any) -> int: - return int(await session.scalar(select(func.count()).select_from(model).where(*where)) or 0) - - def _conflict(detail: str) -> HTTPException: """409, for a request that is well-formed and refused by the class's own state: a name already taken, a schedule days still point at.""" diff --git a/server/app/api/manage/bells.py b/server/app/api/manage/bells.py index c318eb00..a40ce898 100644 --- a/server/app/api/manage/bells.py +++ b/server/app/api/manage/bells.py @@ -10,13 +10,12 @@ from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class -from app.api.manage._common import Actor, _conflict, _count, admin_actor +from app.api.manage._common import Actor, _conflict, admin_actor from app.api.routing import DishkaAnnotatedRoute -from app.models import BellSchedule, DayOverride, SchoolClass +from app.models import BellSchedule, SchoolClass from app.schemas import ( BellPeriodOut, BellPeriodsIn, @@ -25,7 +24,7 @@ BellSchedulePatch, DeletedOut, ) -from app.services import audit, structure +from app.services.manage import bells as bells_service router = APIRouter(route_class=DishkaAnnotatedRoute) @@ -53,11 +52,7 @@ def _schedule_out( async def _schedule_or_404( session: AsyncSession, school_class: SchoolClass, schedule_id: int ) -> BellSchedule: - schedule = await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) + schedule = await bells_service.schedule_of(session, school_class.id, schedule_id) if schedule is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown bell schedule") return schedule @@ -77,11 +72,7 @@ async def bells_list( ) -> list[BellScheduleOut]: """Every schedule the class keeps - «Обычное», «Сокращённое», «Суббота» - with the class default marked.""" - rows = await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == school_class.id) - .order_by(BellSchedule.id) - ) + rows = await bells_service.schedules_of(session, school_class.id) return [_schedule_out(row, school_class) for row in rows] @@ -99,39 +90,14 @@ async def bells_create( order to be pointed at by particular days, and making it the default the moment it exists would move every day onto it. """ - schedule = BellSchedule(class_id=school_class.id, name=payload.name) - session.add(schedule) - await session.flush() - if payload.periods: - await structure.write_bell_periods(session, schedule, _rows_of(payload)) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.create", - f"создано расписание звонков «{payload.name}»: {len(payload.periods)} уроков", + schedule = await bells_service.create( + session, school_class, actor.telegram_id, payload.name, _rows_of(payload) ) await session.commit() await session.refresh(schedule, ["periods"]) return _schedule_out(schedule, school_class) -async def _rung_by_default( - session: AsyncSession, school_class: SchoolClass -) -> set[int]: - """The lesson numbers the class rings today, before anything is changed. - - An empty set when the class has no default at all, which is the honest - reading: nothing was ringing, so nothing can stop. - """ - if school_class.bell_schedule_id is None: - return set() - current = await session.scalar( - select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) - ) - return {period.index for period in current.periods} if current is not None else set() - - @router.patch("/bells/{schedule_id}", response_model=BellScheduleOut) async def bells_update( schedule_id: int, @@ -150,15 +116,9 @@ async def bells_update( schedule = await _schedule_or_404(session, school_class, schedule_id) silenced: list[tuple[int, int]] = [] - if payload.name is not None and payload.name != schedule.name: - old_name = schedule.name - schedule.name = payload.name - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.rename", - f"звонки «{old_name}» → «{payload.name}»", + if payload.name is not None: + await bells_service.rename( + session, school_class, actor.telegram_id, schedule, payload.name ) if payload.is_default is not None: @@ -167,53 +127,17 @@ async def bells_update( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="make another schedule the default instead", ) - # A schedule may be created empty and filled in afterwards, which is - # the point of the two-step flow — but the class default is what every - # ordinary day rings, and a default that rings nothing draws nothing: - # no lesson on any weekday can be placed on a timeline, so `/bundle` - # answers zero lessons, `/now` answers «day_off» on a Monday, and the - # phone, the widget, the calendar feed and the morning digest all go - # blank at once with nothing anywhere reporting a problem. Worse, - # `rung_indexes` then returns an empty set, which `can_ring` reads as - # «this class has not set its bells up yet» and waves every lesson - # number through. `edit.day_put` refuses the same thing at day level. - if not schedule.periods: + # Refused when it rings nothing, for the reason `ScheduleEmpty` gives; + # making the default what it already is writes nothing. + try: + silenced = await bells_service.make_default( + session, school_class, actor.telegram_id, schedule + ) + except bells_service.ScheduleEmpty as empty: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="в этом расписании звонков нет ни одного урока", - ) - if school_class.bell_schedule_id != schedule.id: - # Moving the default to a *shorter* schedule takes lessons off - # every weekday exactly as shrinking the current one does — the - # rows past its last rung stay in the database and are drawn, - # logged and announced nowhere. `write_bell_periods` has answered - # this question since the other way in was closed, but it is only - # reached when a schedule's rows are rewritten, and re-pointing - # the class rewrites none. Asked here with the incoming - # schedule's numbers, through the same function, so the two - # cannot answer differently. - # What the class rang a moment ago, against what it will ring - # now. Asking only the incoming schedule counts rows that were - # already silent, which said «перестали звонить уроков: N» on a - # move to a schedule ringing exactly the same numbers. - was = await _rung_by_default(session, school_class) - silenced = await structure.lessons_silenced_by( - session, - school_class.id, - was, - {period.index for period in schedule.periods}, - ) - school_class.bell_schedule_id = schedule.id - summary = f"основное расписание звонков: «{schedule.name}»" - if silenced: - summary += f", перестали звонить уроков: {len(silenced)}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.default", - summary, - ) + ) from empty await session.commit() await session.refresh(schedule, ["periods"]) @@ -236,19 +160,8 @@ async def bells_periods( sending the six rows that are now true is one intention, not six. """ schedule = await _schedule_or_404(session, school_class, schedule_id) - orphaned = await structure.write_bell_periods(session, schedule, _rows_of(payload)) - summary = f"звонки «{schedule.name}»: {len(payload.periods)} уроков" - if orphaned: - # Shrinking the class's own schedule takes lessons off every weekday - # that carried a number past the new last rung. They are still stored - # and they are drawn nowhere, so the log is where an admin finds out. - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.edit", - summary, + orphaned = await bells_service.replace_rows( + session, school_class, actor.telegram_id, schedule, _rows_of(payload) ) await session.commit() await session.refresh(schedule, ["periods"]) @@ -270,27 +183,13 @@ async def bells_delete( an admin is not looking at. """ schedule = await _schedule_or_404(session, school_class, schedule_id) - - if schedule.id == school_class.bell_schedule_id: - raise _conflict("this is the class default; make another one the default first") - - used = await _count( - session, - DayOverride, - DayOverride.class_id == school_class.id, - DayOverride.bell_schedule_id == schedule.id, - ) - if used: - raise _conflict(f"{used} special day(s) still use this schedule") - - name = schedule.name - await session.delete(schedule) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "bells.delete", - f"удалено расписание звонков «{name}»", - ) + try: + await bells_service.delete(session, school_class, actor.telegram_id, schedule) + except bells_service.ScheduleIsDefault as default: + raise _conflict( + "this is the class default; make another one the default first" + ) from default + except bells_service.ScheduleInUse as in_use: + raise _conflict(f"{in_use.days} special day(s) still use this schedule") from in_use await session.commit() return DeletedOut(id=schedule_id) diff --git a/server/app/api/manage/classes.py b/server/app/api/manage/classes.py index 53ec429d..f2bc54c7 100644 --- a/server/app/api/manage/classes.py +++ b/server/app/api/manage/classes.py @@ -13,12 +13,13 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class -from app.api.manage._common import Actor, _count, admin_actor, owner_actor +from app.api.manage._common import Actor, admin_actor, owner_actor from app.api.routing import DishkaAnnotatedRoute -from app.models import AccessRequest, BotUser, DeviceToken, JoinMode, SchoolClass +from app.models import JoinMode, SchoolClass from app.schemas import ClassDeleteIn, ClassPatch, DeletedOut, ManagedClassOut from app.services import audit from app.services import terms as terms_service +from app.services.manage import classes as classes_service from app.timezones import is_supported, label_for log = logging.getLogger(__name__) @@ -32,6 +33,7 @@ async def _class_out(session: AsyncSession, school_class: SchoolClass) -> ManagedClassOut: + counts = await classes_service.counts(session, school_class.id) return ManagedClassOut( id=school_class.id, name=school_class.name, @@ -40,19 +42,9 @@ async def _class_out(session: AsyncSession, school_class: SchoolClass) -> Manage timezone=school_class.timezone_name, timezone_label=label_for(school_class.timezone_name), join_code=school_class.join_code, - members=await _count(session, BotUser, BotUser.class_id == school_class.id), - devices=await _count( - session, - DeviceToken, - DeviceToken.class_id == school_class.id, - DeviceToken.revoked.is_(False), - ), - pending_requests=await _count( - session, - AccessRequest, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ), + members=counts.members, + devices=counts.devices, + pending_requests=counts.pending, bell_schedule_id=school_class.bell_schedule_id, calendar_ready=bool(school_class.calendar_token), # `.value`, so the wire says «open». The column stores the member name @@ -109,23 +101,9 @@ async def class_update( ) for column, value in changes.items(): - setattr(school_class, column, value) - await audit.record( - session, - school_class.id, - actor.telegram_id, - f"class.{column}", - f"{column}: {value or 'убрано'}", - ) + await classes_service.set_field(session, school_class, actor.telegram_id, column, value) if zone is not None: - school_class.timezone = zone - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.timezone", - f"часовой пояс: {zone}", - ) + await classes_service.set_timezone(session, school_class, actor.telegram_id, zone) if ("grade" in changes or "letter" in changes) and "name" not in changes: # A class moved from 9 to 10 is not called «9А» any more. The name was # composed from these two at creation (`bot/handlers/start.py`), and a @@ -147,19 +125,12 @@ async def class_update( ) if mode is not None: # Through the enum rather than by the string, because the attribute is - # read back as one by `_class_out` in this same request - and because - # the audit line should say what changed rather than echo a wire value. - school_class.join_mode = JoinMode(mode) - await audit.record( - session, - school_class.id, - actor.telegram_id, - # The same action name the bot's own toggle writes, so the log - # reads as one history however the switch was flipped. - "access.join_mode", - "вход только по личным приглашениям" - if school_class.join_mode is JoinMode.INVITE - else "вход по коду класса снова разрешён", + # read back as one by `_class_out` in this same request. The same + # service the bot's own switch calls, so the log reads as one history + # however the switch was flipped - and a switch to the mode already in + # force writes no line from either side. + await classes_service.set_join_mode( + session, school_class, actor.telegram_id, JoinMode(mode) ) await session.commit() @@ -186,14 +157,15 @@ async def class_delete( with it. Every device token goes too, so the caller's own token stops working - which is correct, there is nothing left for it to read. """ - if payload.confirm_name.strip() != school_class.name: + class_id = school_class.id + try: + await classes_service.delete(session, school_class, payload.confirm_name) + except classes_service.NameMismatch as mismatch: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="confirm_name does not match the class name", - ) + ) from mismatch - class_id = school_class.id log.info("class %s deleted by %s", class_id, actor.telegram_id) - await session.delete(school_class) await session.commit() return DeletedOut(id=class_id) diff --git a/server/app/api/manage/devices.py b/server/app/api/manage/devices.py index ebe44180..46b79316 100644 --- a/server/app/api/manage/devices.py +++ b/server/app/api/manage/devices.py @@ -10,7 +10,6 @@ from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, Query, status -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class @@ -18,7 +17,8 @@ from app.api.routing import DishkaAnnotatedRoute from app.models import DeviceToken, Role, SchoolClass from app.schemas import ManagedDeviceOut -from app.services import audit, linking +from app.services import linking +from app.services.manage import devices as devices_service log = logging.getLogger(__name__) @@ -52,11 +52,7 @@ def _device_out( async def _device_or_404( session: AsyncSession, school_class: SchoolClass, device_id: int ) -> DeviceToken: - device = await session.scalar( - select(DeviceToken).where( - DeviceToken.id == device_id, DeviceToken.class_id == school_class.id - ) - ) + device = await devices_service.device_of(session, school_class.id, device_id) if device is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown device") return device @@ -79,14 +75,9 @@ async def devices_list( """ devices = await linking.devices_of(session, school_class.id, include_revoked=include_revoked) names = await _member_names(session, school_class.id) - # Once per owner, not once per phone: the role hangs off the account, and a - # class where everybody joined from their own phone was paying a round trip - # a row for an answer already in hand. «📱 Устройства» in the bot resolves - # it the same way. - roles: dict[int, Role | None] = {} - for device in devices: - if device.telegram_id is not None and device.telegram_id not in roles: - roles[device.telegram_id] = await linking.effective_role(session, device) + # Once per owner, not once per phone, through the function «📱 Устройства» + # in the bot resolves it with. + roles = await devices_service.owner_roles(session, devices) return [ _device_out(device, school_class, names, roles.get(device.telegram_id)) for device in devices @@ -113,19 +104,8 @@ async def device_revoke( device = await _device_or_404(session, school_class, device_id) names = await _member_names(session, school_class.id) role = await linking.effective_role(session, device) - if device.revoked: - return _device_out(device, school_class, names, role) - - device.revoked = True - name = device.device_name or f"Устройство {device.id}" - await audit.record( - session, - school_class.id, - actor.telegram_id, - "device.revoke", - f"отключено устройство «{name}»", - ) - await session.commit() + if await devices_service.revoke(session, school_class.id, actor.telegram_id, device): + await session.commit() return _device_out(device, school_class, names, role) @@ -145,18 +125,10 @@ async def device_unlink( something to change. """ device = await _device_or_404(session, school_class, device_id) - if device.telegram_id is None: - raise _conflict("device is not linked") - - name = device.device_name or f"Устройство {device.id}" - await linking.unlink_device(session, device) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "device.unlink", - f"отвязано устройство «{name}» — снова только чтение", - ) + try: + await devices_service.unlink(session, school_class.id, actor.telegram_id, device) + except devices_service.DeviceNotLinked as not_linked: + raise _conflict("device is not linked") from not_linked await session.commit() names = await _member_names(session, school_class.id) role = await linking.effective_role(session, device) diff --git a/server/app/api/manage/journal.py b/server/app/api/manage/journal.py index 0ee5b7a4..dbbc5654 100644 --- a/server/app/api/manage/journal.py +++ b/server/app/api/manage/journal.py @@ -15,7 +15,7 @@ from app.api.routing import DishkaAnnotatedRoute from app.models import AuditEntry, SchoolClass from app.schemas import AuditEntryOut, AuditPageOut -from app.services import audit +from app.services.manage import journal as journal_service router = APIRouter(route_class=DishkaAnnotatedRoute) @@ -37,15 +37,10 @@ async def audit_log( *, session: FromDishka[AsyncSession], ) -> AuditPageOut: - """Who changed what, newest first. - - One row more than ``limit`` is read and thrown away: that is what - ``has_more`` is, and it costs one row instead of the count of an - append-only table on every page turn. - """ - entries = await audit.recent(session, school_class.id, limit=limit + 1, offset=offset) - has_more = len(entries) > limit - entries = entries[:limit] + """Who changed what, newest first; ``has_more`` says whether a page follows.""" + entries, has_more = await journal_service.page( + session, school_class.id, limit=limit, offset=offset + ) names = await _member_names(session, school_class.id) def _entry(row: AuditEntry) -> AuditEntryOut: diff --git a/server/app/api/manage/requests.py b/server/app/api/manage/requests.py index bd58d0fc..16cf1def 100644 --- a/server/app/api/manage/requests.py +++ b/server/app/api/manage/requests.py @@ -7,13 +7,10 @@ from __future__ import annotations import logging -from datetime import UTC, datetime -from html import escape from typing import Any from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class @@ -23,7 +20,7 @@ from app.models import AccessRequest, Role, SchoolClass from app.schemas import AccessRequestOut, RequestDecisionIn, RequestDecisionOut from app.services import access as access_service -from app.services import audit +from app.services.manage import requests as requests_service log = logging.getLogger(__name__) @@ -72,13 +69,7 @@ async def _request_or_404( """Pending, and this class's. A request that has already been answered is gone as far as this endpoint is concerned, so two admins tapping «Выдать» at once cannot grant twice.""" - request = await session.scalar( - select(AccessRequest).where( - AccessRequest.id == request_id, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ) - ) + request = await requests_service.pending_one(session, school_class.id, request_id) if request is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown request") return request @@ -92,13 +83,7 @@ async def requests_list( session: FromDishka[AsyncSession], ) -> list[AccessRequestOut]: """Everybody waiting for a role, oldest first.""" - rows = list( - await session.scalars( - select(AccessRequest) - .where(AccessRequest.class_id == school_class.id, AccessRequest.status == "pending") - .order_by(AccessRequest.id) - ) - ) + rows = await requests_service.pending(session, school_class.id) names = await _member_names(session, school_class.id) return [ AccessRequestOut( @@ -169,20 +154,8 @@ async def request_decline( names = await _member_names(session, school_class.id) who = names.get(request.telegram_id, str(request.telegram_id)) - request.status = "declined" - request.decided_by = actor.telegram_id - request.decided_at = datetime.now(UTC).replace(tzinfo=None) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "access.decline", - f"отклонён запрос доступа от {request.telegram_id}", - ) + await requests_service.decline(session, school_class.id, actor.telegram_id, request) await session.commit() - await _tell( - request.telegram_id, - f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", - ) + await _tell(request.telegram_id, requests_service.decline_notice(school_class)) return RequestDecisionOut(id=request_id, status="declined", who=who) diff --git a/server/app/api/manage/subjects.py b/server/app/api/manage/subjects.py index 88d92cb6..839053a3 100644 --- a/server/app/api/manage/subjects.py +++ b/server/app/api/manage/subjects.py @@ -8,7 +8,6 @@ from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class @@ -16,8 +15,7 @@ from app.api.routing import DishkaAnnotatedRoute from app.models import SchoolClass, Subject from app.schemas import DeletedOut, ManagedSubjectOut, SubjectIn, SubjectPatch, SubjectSavedOut -from app.services import audit, structure -from app.services import subjects as subjects_service +from app.services.manage import subjects as subjects_service router = APIRouter(route_class=DishkaAnnotatedRoute) @@ -40,21 +38,12 @@ def _subject_out(subject: Subject) -> ManagedSubjectOut: async def _subject_or_404( session: AsyncSession, school_class: SchoolClass, subject_id: int ) -> Subject: - subject = await session.scalar( - select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) - ) + subject = await subjects_service.subject_of(session, school_class.id, subject_id) if subject is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown subject") return subject -async def _name_taken( - session: AsyncSession, class_id: int, name: str, *, besides: int | None = None -) -> bool: - """Ignores case, because everything downstream of it does.""" - return await subjects_service.clashing(session, class_id, name, besides=besides) is not None - - @router.get("/subjects", response_model=list[ManagedSubjectOut]) async def subjects_list( _: Actor = Depends(editor_actor), @@ -77,11 +66,8 @@ async def subjects_list( # read, forever. It healed only because `/bundle` commits unconditionally # and a phone polls it; the screen that exists to edit this list did the # work and threw it away. - await subjects_service.sync_from_timetable(session, school_class.id) + rows = await subjects_service.listing(session, school_class.id) await session.commit() - rows = await session.scalars( - select(Subject).where(Subject.class_id == school_class.id).order_by(Subject.name) - ) return [_subject_out(row) for row in rows] @@ -96,24 +82,18 @@ async def subject_create( """Add a subject. The name is unique within the class - that uniqueness is the whole point of the dictionary, so a duplicate is a 409, not a silent second «Алгебра».""" - if await _name_taken(session, school_class.id, payload.name): - raise _conflict("a subject with that name is already in this class") - - subject = Subject( - class_id=school_class.id, - name=payload.name, - short_name=payload.short_name, - teacher=payload.teacher, - color=payload.color, - ) - session.add(subject) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.add", - f"добавлен предмет «{payload.name}»", - ) + try: + subject = await subjects_service.create( + session, + school_class.id, + actor.telegram_id, + payload.name, + short_name=payload.short_name, + teacher=payload.teacher, + color=payload.color, + ) + except subjects_service.SubjectExists as taken: + raise _conflict("a subject with that name is already in this class") from taken await session.commit() await session.refresh(subject) return SubjectSavedOut(subject=_subject_out(subject)) @@ -141,46 +121,22 @@ async def subject_update( new_name = changes.pop("name", None) moved = 0 - if new_name is not None and new_name != subject.name: - if await _name_taken(session, school_class.id, new_name, besides=subject.id): - raise _conflict("a subject with that name is already in this class") - # The dictionary check above cannot see this one: homework may be - # written under a name that is not a dictionary entry, and homework is - # unique per subject per day. See `structure.homework_clashing`. - clash = await structure.homework_clashing( - session, school_class.id, subject.name, new_name - ) - if clash: - days = ", ".join(day.isoformat() for day in clash) - raise _conflict( - f"homework under both names on the same day: {days}" + if new_name is not None: + try: + moved = ( + await subjects_service.rename( + session, school_class.id, actor.telegram_id, subject, new_name + ) + or 0 ) - old_name = subject.name - moved = await structure.rename_subject(session, school_class.id, subject, new_name) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.rename", - f"предмет «{old_name}» → «{new_name}», строк обновлено: {moved}", - ) + except subjects_service.SubjectExists as taken: + raise _conflict("a subject with that name is already in this class") from taken + except subjects_service.HomeworkClash as clash: + raise _conflict(f"homework under both names on the same day: {clash}") from clash - #: Column -> (audit tag, the word the log line uses). The bot writes the - #: colour as «цвет», not «color», and the two logs are read side by side. - labels = { - "short_name": ("subject.short_name", "сокращение"), - "teacher": ("subject.teacher", "учитель"), - "color": ("subject.colour", "цвет"), - } for column, value in changes.items(): - setattr(subject, column, value) - action, label = labels[column] - await audit.record( - session, - school_class.id, - actor.telegram_id, - action, - f"{label} предмета «{subject.name}»: {value or 'убрано'}", + await subjects_service.set_detail( + session, school_class.id, actor.telegram_id, subject, column, value ) await session.commit() @@ -212,17 +168,9 @@ async def subject_delete( was really for. """ subject = await _subject_or_404(session, school_class, subject_id) - in_use = await subjects_service.lessons_using(session, school_class.id, subject) - if in_use: - raise _conflict(f"{in_use} lesson(s) still use this subject") - name = subject.name - await session.delete(subject) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "subject.delete", - f"удалён предмет «{name}»", - ) + try: + await subjects_service.delete(session, school_class.id, actor.telegram_id, subject) + except subjects_service.SubjectInUse as in_use: + raise _conflict(f"{in_use.lessons} lesson(s) still use this subject") from in_use await session.commit() return DeletedOut(id=subject_id) diff --git a/server/app/api/manage/terms.py b/server/app/api/manage/terms.py index 83dee910..de3fa0b1 100644 --- a/server/app/api/manage/terms.py +++ b/server/app/api/manage/terms.py @@ -6,8 +6,6 @@ from __future__ import annotations -from datetime import datetime - from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession @@ -17,8 +15,8 @@ from app.api.routing import DishkaAnnotatedRoute from app.models import SchoolClass, TermKind from app.schemas import TermBoundsIn, TermOut, TermSchemeIn, TermsOut -from app.services import audit from app.services import terms as terms_service +from app.services.manage import terms as terms_manage router = APIRouter(route_class=DishkaAnnotatedRoute) @@ -48,11 +46,6 @@ def _terms_out(school_class: SchoolClass, year: int, rows) -> TermsOut: ) -def _term_year(school_class: SchoolClass) -> int: - """The school year in force for this class, in the class's own zone.""" - return terms_service.opening_year_of(datetime.now(school_class.tz).date()) - - @router.get("/terms", response_model=TermsOut) async def terms_list( _: Actor = Depends(admin_actor), @@ -61,8 +54,7 @@ async def terms_list( session: FromDishka[AsyncSession], ) -> TermsOut: """This class's terms, seeding the conventional set if it has none.""" - year = _term_year(school_class) - rows = await terms_service.ensure(session, school_class, year) + year, rows = await terms_manage.current(session, school_class) await session.commit() return _terms_out(school_class, year, rows) @@ -81,15 +73,9 @@ async def terms_set_scheme( onto each other, and a leftover third quarter inside a year that has two is not a state worth keeping. """ - year = _term_year(school_class) - wanted = TermKind(payload.kind) - rows = await terms_service.set_scheme(session, school_class, wanted, year) - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.term_kind", - f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", + year = terms_manage.current_year(school_class) + rows = await terms_manage.change_scheme( + session, school_class, actor.telegram_id, TermKind(payload.kind) ) await session.commit() return _terms_out(school_class, year, rows) @@ -111,24 +97,14 @@ async def terms_set_bounds( its neighbours, and «конец периода раньше его начала» is the thing worth putting on the screen. """ - year = _term_year(school_class) - await terms_service.ensure(session, school_class, year) try: - await terms_service.set_bounds( - session, school_class, year, index, payload.starts_on, payload.ends_on + year = await terms_manage.move_term( + session, school_class, actor.telegram_id, index, payload.starts_on, payload.ends_on ) except terms_service.TermError as error: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) ) from error - - await audit.record( - session, - school_class.id, - actor.telegram_id, - "class.term", - f"период {index}: {payload.starts_on:%d.%m.%Y} — {payload.ends_on:%d.%m.%Y}", - ) await session.commit() rows = await terms_service.read(session, school_class.id, year) return _terms_out(school_class, year, rows) diff --git a/server/app/api/manage/timetable.py b/server/app/api/manage/timetable.py index 9d99650e..02db2374 100644 --- a/server/app/api/manage/timetable.py +++ b/server/app/api/manage/timetable.py @@ -8,16 +8,16 @@ from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api.deps import current_class from app.api.manage._common import Actor, admin_actor from app.api.routing import DishkaAnnotatedRoute from app.bot.render import WEEKDAYS -from app.models import BellSchedule, SchoolClass, TimetableEntry +from app.models import SchoolClass from app.schemas import ImportConflictOut, TimetableExportOut, TimetableImportIn, TimetableImportOut -from app.services import audit, structure, timetable_io +from app.services import structure, timetable_io +from app.services.manage import timetable as timetable_service router = APIRouter(route_class=DishkaAnnotatedRoute) @@ -41,21 +41,8 @@ async def timetable_export( round. An empty timetable is an empty string, not a 404 - there is nothing wrong with a class that has not filled one in yet. """ - entries = list( - await session.scalars( - select(TimetableEntry) - .where(TimetableEntry.class_id == school_class.id) - .order_by(TimetableEntry.weekday, TimetableEntry.index) - ) - ) - periods = [] - if school_class.bell_schedule_id: - schedule = await session.get(BellSchedule, school_class.bell_schedule_id) - if schedule is not None: - periods = list(schedule.periods) - return TimetableExportOut( - text=timetable_io.export_timetable(entries, periods), lessons=len(entries) - ) + text, lessons = await timetable_service.export(session, school_class) + return TimetableExportOut(text=text, lessons=lessons) @router.post("/timetable/import", response_model=TimetableImportOut) @@ -103,7 +90,7 @@ async def timetable_import( rejected=rejected, ) - result = await structure.apply_timetable(session, school_class, days, bells) + result = await timetable_service.apply(session, school_class, actor.telegram_id, days, bells) total = result.written schedule = result.schedule # Reported, not silently dropped: a lesson past the last bell has nowhere @@ -124,16 +111,6 @@ async def timetable_import( "больше не звонит — новые звонки короче" for weekday, index in result.orphaned ] - summary = f"импорт расписания: дней {len(days)}, уроков {total}" - if bells: - summary += f", звонков {len(bells)}" - if result.dropped: - summary += f", без звонка пропущено {len(result.dropped)}" - if result.orphaned: - summary += f", перестали звонить {len(result.orphaned)}" - await audit.record( - session, school_class.id, actor.telegram_id, "timetable.import", summary - ) await session.commit() if schedule is not None: await session.refresh(schedule, ["periods"]) diff --git a/server/app/bot/handlers/access.py b/server/app/bot/handlers/access.py index 790d32e8..dcd4c8d9 100644 --- a/server/app/bot/handlers/access.py +++ b/server/app/bot/handlers/access.py @@ -42,6 +42,7 @@ from app.security import normalise_phone from app.services import audit, device_invites, diary_link, reminders from app.services import diary as diary_service +from app.services.manage import classes as classes_service router = Router(name="access") @@ -296,25 +297,20 @@ async def switch_join_mode( await callback.answer("Кнопка устарела. Откройте «👥 Доступ» заново.", show_alert=True) return - if school_class.join_mode is wanted: + # The same service `PATCH /manage/class` calls, so the log reads as one + # history however the switch was flipped. + if not await classes_service.set_join_mode( + session, school_class, callback.from_user.id, wanted + ): await callback.message.edit_text( f"{JOIN_MODE_TEXT[wanted]}\n\nЭто уже так — ничего не изменилось.", reply_markup=back_to_menu(), ) await callback.answer("Уже так") return + await session.commit() to_invite = wanted is JoinMode.INVITE - school_class.join_mode = wanted - note = ( - "вход только по личным приглашениям" - if to_invite - else "вход по коду класса снова разрешён" - ) - await audit.record( - session, school_class.id, callback.from_user.id, "access.join_mode", note - ) - await session.commit() if to_invite: tail = ( @@ -332,7 +328,7 @@ async def switch_join_mode( f"{JOIN_MODE_TEXT[school_class.join_mode]}\n\n{tail}", reply_markup=back_to_menu(), ) - await callback.answer(note.capitalize()) + await callback.answer(classes_service.JOIN_MODE_SUMMARY[wanted].capitalize()) @router.callback_query(AccessAction.filter(F.action == "invite")) diff --git a/server/app/bot/handlers/manage/_common.py b/server/app/bot/handlers/manage/_common.py index e3ccf6d2..ca5f7d79 100644 --- a/server/app/bot/handlers/manage/_common.py +++ b/server/app/bot/handlers/manage/_common.py @@ -11,11 +11,11 @@ from datetime import datetime from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.models import AccessRequest, BotUser, DayKind, Role, SchoolClass +from app.models import DayKind, Role, SchoolClass +from app.services.manage import classes as classes_service NO_ACCESS = "Нет доступа. Откройте /start, чтобы получить его." NEED_ADMIN = "Только для администраторов" @@ -125,19 +125,9 @@ def _parse_day(raw: str, today: Date) -> Date | None: return result -async def _pending_requests(session: AsyncSession, class_id: int) -> list[AccessRequest]: - return list( - await session.scalars( - select(AccessRequest) - .where(AccessRequest.class_id == class_id, AccessRequest.status == "pending") - .order_by(AccessRequest.id) - ) - ) - - async def _member_names(session: AsyncSession, class_id: int) -> dict[int, str]: """Telegram id -> the name to show, already escaped by ``manage_render``.""" - members = await session.scalars(select(BotUser).where(BotUser.class_id == class_id)) + members = await classes_service.members(session, class_id) return { member.telegram_id: mr.person(member.full_name, member.username, member.telegram_id) for member in members diff --git a/server/app/bot/handlers/manage/audit_log.py b/server/app/bot/handlers/manage/audit_log.py index 78591e48..87363fcb 100644 --- a/server/app/bot/handlers/manage/audit_log.py +++ b/server/app/bot/handlers/manage/audit_log.py @@ -16,7 +16,7 @@ from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal from app.bot.manage_keyboards import AuditAction, audit_keyboard from app.models import Role, SchoolClass -from app.services import audit +from app.services.manage import journal as journal_service router = Router(name="manage.audit_log") @@ -27,9 +27,9 @@ async def _audit_view(session: AsyncSession, school_class: SchoolClass, offset: int): - entries = await audit.recent(session, school_class.id, limit=mr.AUDIT_PAGE + 1, offset=offset) - more = len(entries) > mr.AUDIT_PAGE - entries = entries[:mr.AUDIT_PAGE] + entries, more = await journal_service.page( + session, school_class.id, limit=mr.AUDIT_PAGE, offset=offset + ) names = await _member_names(session, school_class.id) return ( mr.render_audit(entries, names, school_class.tz, offset), diff --git a/server/app/bot/handlers/manage/bells.py b/server/app/bot/handlers/manage/bells.py index 641fa3b0..a4da8544 100644 --- a/server/app/bot/handlers/manage/bells.py +++ b/server/app/bot/handlers/manage/bells.py @@ -12,7 +12,6 @@ from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr @@ -23,8 +22,9 @@ from app.bot.manage_keyboards import BellsAction, bells_list_keyboard from app.bot.manage_states import EditBellRows, NewBellSchedule from app.bot.render import clamp, more_line, plural -from app.models import BellSchedule, DayOverride, Role, SchoolClass -from app.services import audit, structure, timetable_io +from app.models import BellSchedule, Role, SchoolClass +from app.services import timetable_io +from app.services.manage import bells as bells_service router = Router(name="manage.bells") @@ -58,41 +58,17 @@ def _parse_bells(raw: str): return timetable_io.parse_bells_block("== Звонки ==\n" + (raw or "")) -async def _schedules_of(session: AsyncSession, class_id: int) -> list[BellSchedule]: - return list( - await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == class_id) - .order_by(BellSchedule.id) - ) - ) - - -async def _rung_by_default(session: AsyncSession, school_class: SchoolClass) -> set[int]: - """The lesson numbers the class rings today. Empty when it has no default.""" - if school_class.bell_schedule_id is None: - return set() - current = await session.scalar( - select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) - ) - return {period.index for period in current.periods} if current is not None else set() - - async def _schedule_by_id( session: AsyncSession, school_class: SchoolClass, raw: str ) -> BellSchedule | None: schedule_id = _int_or_none(raw) if schedule_id is None: return None - return await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) + return await bells_service.schedule_of(session, school_class.id, schedule_id) async def _bells_view(session: AsyncSession, school_class: SchoolClass): - schedules = await _schedules_of(session, school_class.id) + schedules = await bells_service.schedules_of(session, school_class.id) return mr.render_bells(schedules, school_class.bell_schedule_id), bells_list_keyboard( schedules, school_class.bell_schedule_id ) @@ -188,16 +164,8 @@ async def bells_rows_apply( ) return - orphaned = await structure.write_bell_periods(session, schedule, rows) - summary = f"звонки «{schedule.name}»: {len(rows)} уроков" - if orphaned: - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, - school_class.id, - message.from_user.id, - "bells.edit", - summary, + orphaned = await bells_service.replace_rows( + session, school_class, message.from_user.id, schedule, rows ) await session.commit() await session.refresh(schedule, ["periods"]) @@ -290,16 +258,10 @@ async def bells_new_rows( ) return - schedule = BellSchedule(class_id=school_class.id, name=name[:64]) - session.add(schedule) - await session.flush() - await structure.write_bell_periods(session, schedule, rows) - await audit.record( - session, - school_class.id, - message.from_user.id, - "bells.create", - f"создано расписание звонков «{name}»: {len(rows)} уроков", + # The name step already held it to 64 characters; the cut is for a state + # written by anything else. + schedule = await bells_service.create( + session, school_class, message.from_user.id, name[:64], rows ) await session.commit() await session.refresh(schedule, ["periods"]) @@ -344,40 +306,20 @@ async def bells_make_default( return # A schedule may be created empty — that is the two-step flow, and the rows - # are the next screen. Making an empty one the *class default* is another - # thing: every ordinary day rings it, and a day that rings nothing draws - # nothing. `/bundle` answers zero lessons, `/now` answers «выходной» on a - # Monday, and the phone, the widget, the calendar feed and the morning - # digest go blank together with nothing anywhere reporting a problem — - # while the class's own timetable sits untouched underneath, which is what - # makes it so hard to see. Worse, `rung_indexes` then returns an empty set, - # which `can_ring` reads as «this class has not set its bells up yet» and - # waves every lesson number through. `api/manage.bells_update` has refused - # this since it was written and the «⭐» beside it did not; one rule, two - # shells, is the whole reason `services/` exists. - if not schedule.periods: + # are the next screen — but it may not be the *class default*: see + # `ScheduleEmpty`. The «⭐» here refused nothing while the API refused it, + # which is how this rule came to live in one place. + try: + orphaned = await bells_service.make_default( + session, school_class, callback.from_user.id, schedule + ) + except bells_service.ScheduleEmpty: await callback.answer( "В этом расписании звонков нет ни одного урока — сделать его " "основным нельзя. Сначала добавьте времена.", show_alert=True, ) return - - # Moving the default to a *shorter* schedule takes lessons off every - # weekday exactly as shrinking the current one does, and nothing rewrites a - # row, so `write_bell_periods` never runs and never counts them. Asked here - # through the same function the API asks, so the two answer alike. - was = await _rung_by_default(session, school_class) - orphaned = await structure.lessons_silenced_by( - session, school_class.id, was, {period.index for period in schedule.periods} - ) - school_class.bell_schedule_id = schedule.id - summary = f"основное расписание звонков: «{schedule.name}»" - if orphaned: - summary += f", перестали звонить уроков: {len(orphaned)}" - await audit.record( - session, school_class.id, callback.from_user.id, "bells.default", summary, - ) await session.commit() text, keyboard = await _bells_view(session, school_class) @@ -418,33 +360,19 @@ async def bells_delete( await callback.answer("Расписание не найдено", show_alert=True) return - if schedule.id == school_class.bell_schedule_id: + try: + name = await bells_service.delete(session, school_class, callback.from_user.id, schedule) + except bells_service.ScheduleIsDefault: await callback.answer( "Это основное расписание класса. Сначала сделайте основным другое.", show_alert=True, ) return - - used = await session.scalar( - select(func.count()) - .select_from(DayOverride) - .where( - DayOverride.class_id == school_class.id, - DayOverride.bell_schedule_id == schedule.id, - ) - ) - if used: + except bells_service.ScheduleInUse as in_use: await callback.answer( - f"По нему идут особые дни ({used}). Сначала измените их.", show_alert=True + f"По нему идут особые дни ({in_use.days}). Сначала измените их.", show_alert=True ) return - - name = schedule.name - await session.delete(schedule) - await audit.record( - session, school_class.id, callback.from_user.id, "bells.delete", - f"удалено расписание звонков «{name}»", - ) await session.commit() text, keyboard = await _bells_view(session, school_class) diff --git a/server/app/bot/handlers/manage/class_card.py b/server/app/bot/handlers/manage/class_card.py index 9da7e22d..65e94a10 100644 --- a/server/app/bot/handlers/manage/class_card.py +++ b/server/app/bot/handlers/manage/class_card.py @@ -12,7 +12,6 @@ from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr @@ -21,7 +20,6 @@ NO_ACCESS, _allowed, _int_or_none, - _pending_requests, _refusal, ) from app.bot.keyboards import Menu, back_to_menu, cancel_keyboard @@ -31,9 +29,9 @@ from app.bot.roles import list_memberships from app.db import SessionLocal from app.fsm_storage import DatabaseStorage -from app.models import BotUser, DeviceToken, Role, SchoolClass +from app.models import Role, SchoolClass from app.providers.diary.registry import binding as diary_binding -from app.services import audit +from app.services.manage import classes as classes_service from app.timezones import label_for router = Router(name="manage.class_card") @@ -48,29 +46,15 @@ async def _class_card( session: AsyncSession, school_class: SchoolClass, role: Role, telegram_id: int ): memberships = await list_memberships(session, telegram_id) - members = int( - await session.scalar( - select(func.count()).select_from(BotUser).where(BotUser.class_id == school_class.id) - ) - or 0 - ) - devices = int( - await session.scalar( - select(func.count()) - .select_from(DeviceToken) - .where(DeviceToken.class_id == school_class.id, DeviceToken.revoked.is_(False)) - ) - or 0 - ) - pending = len(await _pending_requests(session, school_class.id)) + counts = await classes_service.counts(session, school_class.id) text = mr.render_class_card( school_class, zone_label=label_for(school_class.timezone_name), feed_ready=bool(school_class.calendar_token), - members=members, - devices=devices, - pending=pending, + members=counts.members, + devices=counts.devices, + pending=counts.pending, diary_label=_diary_label(school_class), ) keyboard = class_menu( @@ -78,7 +62,7 @@ async def _class_card( # The button only appears for somebody who actually has somewhere to # switch to; one membership is the overwhelmingly common case. many_classes=len(memberships) > 1, - pending=pending, + pending=counts.pending, diary_bound=bool(school_class.diary_provider), ) return text, keyboard @@ -205,14 +189,7 @@ async def class_field_apply( else: value = None if raw in {"-", "—", ""} else raw[:limit] - setattr(school_class, column, value) - await audit.record( - session, - school_class.id, - message.from_user.id, - f"class.{column}", - f"{column}: {value or 'убрано'}", - ) + await classes_service.set_field(session, school_class, message.from_user.id, column, value) await session.commit() await state.clear() @@ -345,16 +322,15 @@ async def class_delete_apply( await state.clear() return - typed = (message.text or "").strip() - if typed != school_class.name: + name = school_class.name + try: + await classes_service.delete(session, school_class, message.text or "") + except classes_service.NameMismatch: await message.answer( "Название не совпало — класс не тронут.\n" f"Чтобы удалить, пришлите ровно: <code>{escape(school_class.name)}</code>" ) return - - name = school_class.name - await session.delete(school_class) await session.commit() await state.clear() await message.answer( diff --git a/server/app/bot/handlers/manage/devices.py b/server/app/bot/handlers/manage/devices.py index 11d8af45..ceb0b582 100644 --- a/server/app/bot/handlers/manage/devices.py +++ b/server/app/bot/handlers/manage/devices.py @@ -10,14 +10,14 @@ from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal from app.bot.manage_keyboards import DeviceAction, device_keyboard from app.models import DeviceToken, Role, SchoolClass -from app.services import audit, linking +from app.services import linking +from app.services.manage import devices as devices_service router = Router(name="manage.devices") @@ -35,15 +35,13 @@ async def _device_view(session: AsyncSession, school_class: SchoolClass): devices = await linking.devices_of(session, school_class.id) - owners: dict[int, tuple[str, Role | None]] = {} names = await _member_names(session, school_class.id) - for device in devices: - if device.telegram_id is None or device.telegram_id in owners: - continue - owners[device.telegram_id] = ( - names.get(device.telegram_id, str(device.telegram_id)), - await linking.effective_role(session, device), - ) + owners: dict[int, tuple[str, Role | None]] = { + telegram_id: (names.get(telegram_id, str(telegram_id)), owner_role) + for telegram_id, owner_role in ( + await devices_service.owner_roles(session, devices) + ).items() + } return mr.render_devices(devices, owners), device_keyboard(devices) @@ -53,11 +51,7 @@ async def _device_by_id( device_id = _int_or_none(raw) if device_id is None: return None - return await session.scalar( - select(DeviceToken).where( - DeviceToken.id == device_id, DeviceToken.class_id == school_class.id - ) - ) + return await devices_service.device_of(session, school_class.id, device_id) @router.message(Command("devices")) @@ -112,13 +106,10 @@ async def device_revoke( await callback.answer("Устройство не найдено", show_alert=True) return - device.revoked = True - name = device.device_name or f"Устройство {device.id}" - await audit.record( - session, school_class.id, callback.from_user.id, "device.revoke", - f"отключено устройство «{name}»", - ) + # A phone already off is answered the same and logged once, not again. + await devices_service.revoke(session, school_class.id, callback.from_user.id, device) await session.commit() + name = devices_service.label(device) text, keyboard = await _device_view(session, school_class) await callback.message.edit_text(text, reply_markup=keyboard) @@ -142,16 +133,11 @@ async def device_unlink( if device is None: await callback.answer("Устройство не найдено", show_alert=True) return - if device.telegram_id is None: + try: + await devices_service.unlink(session, school_class.id, callback.from_user.id, device) + except devices_service.DeviceNotLinked: await callback.answer("Устройство и так не привязано", show_alert=True) return - - name = device.device_name or f"Устройство {device.id}" - await linking.unlink_device(session, device) - await audit.record( - session, school_class.id, callback.from_user.id, "device.unlink", - f"отвязано устройство «{name}» — снова только чтение", - ) await session.commit() text, keyboard = await _device_view(session, school_class) diff --git a/server/app/bot/handlers/manage/import_export.py b/server/app/bot/handlers/manage/import_export.py index 69513241..2855b315 100644 --- a/server/app/bot/handlers/manage/import_export.py +++ b/server/app/bot/handlers/manage/import_export.py @@ -12,7 +12,6 @@ from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr @@ -20,8 +19,9 @@ from app.bot.keyboards import WEEKDAY_FULL, back_to_menu, cancel_keyboard from app.bot.manage_keyboards import ImportAction, import_keyboard from app.bot.manage_states import ImportTimetable -from app.models import BellPeriod, BellSchedule, Role, SchoolClass, TimetableEntry -from app.services import audit, structure, timetable_io +from app.models import Role, SchoolClass +from app.services import timetable_io +from app.services.manage import timetable as timetable_service router = Router(name="manage.import_export") @@ -69,20 +69,7 @@ async def cmd_export( return await state.clear() - entries = list( - await session.scalars( - select(TimetableEntry) - .where(TimetableEntry.class_id == school_class.id) - .order_by(TimetableEntry.weekday, TimetableEntry.index) - ) - ) - periods: list[BellPeriod] = [] - if school_class.bell_schedule_id: - schedule = await session.get(BellSchedule, school_class.bell_schedule_id) - if schedule is not None: - periods = list(schedule.periods) - - body = timetable_io.export_timetable(entries, periods) + body, _lessons = await timetable_service.export(session, school_class) if not body: await message.answer("Расписание пустое — экспортировать нечего.") return @@ -194,21 +181,12 @@ async def import_apply( await callback.answer("Нечего применять — начните заново: /import", show_alert=True) return - result = await structure.apply_timetable(session, school_class, days, bells) + result = await timetable_service.apply( + session, school_class, callback.from_user.id, days, bells + ) total = result.written schedule = result.schedule unrung = result.unrung - - summary = f"импорт расписания: дней {len(days)}, уроков {total}" - if bells: - summary += f", звонков {len(bells)}" - if result.dropped: - # Rows, not numbers. «8. Алгебра» under Monday and under Tuesday is two - # lessons nobody will see, and this line is the only record of them. - summary += f", без звонка пропущено {len(result.dropped)}" - await audit.record( - session, school_class.id, callback.from_user.id, "timetable.import", summary - ) await session.commit() if schedule is not None: await session.refresh(schedule, ["periods"]) diff --git a/server/app/bot/handlers/manage/requests.py b/server/app/bot/handlers/manage/requests.py index 0906978c..950d2865 100644 --- a/server/app/bot/handlers/manage/requests.py +++ b/server/app/bot/handlers/manage/requests.py @@ -7,7 +7,6 @@ from __future__ import annotations import logging -from datetime import UTC, datetime from html import escape from aiogram import F, Router @@ -25,6 +24,7 @@ from app.models import AccessRequest, BotUser, Role, SchoolClass from app.services import access as access_service from app.services import audit, linking +from app.services.manage import requests as requests_service log = logging.getLogger(__name__) @@ -243,13 +243,7 @@ async def _request_by_id( request_id = _int_or_none(raw) if request_id is None: return None - return await session.scalar( - select(AccessRequest).where( - AccessRequest.id == request_id, - AccessRequest.class_id == school_class.id, - AccessRequest.status == "pending", - ) - ) + return await requests_service.pending_one(session, school_class.id, request_id) @router.callback_query(RequestAction.filter(F.action == "approve")) @@ -321,22 +315,11 @@ async def request_decline( await callback.answer("Запрос уже закрыт", show_alert=True) return - request.status = "declined" - request.decided_by = callback.from_user.id - request.decided_at = datetime.now(UTC).replace(tzinfo=None) - await audit.record( - session, - school_class.id, - callback.from_user.id, - "access.decline", - f"отклонён запрос доступа от {request.telegram_id}", - ) + await requests_service.decline(session, school_class.id, callback.from_user.id, request) await session.commit() await _tell_requester( - _bot_of(callback), - request.telegram_id, - f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён.", + _bot_of(callback), request.telegram_id, requests_service.decline_notice(school_class) ) await callback.message.edit_text("✖️ Запрос отклонён.", reply_markup=back_to_menu()) await callback.answer("Отклонено") diff --git a/server/app/bot/handlers/manage/subjects.py b/server/app/bot/handlers/manage/subjects.py index a87b618d..54b139e7 100644 --- a/server/app/bot/handlers/manage/subjects.py +++ b/server/app/bot/handlers/manage/subjects.py @@ -29,8 +29,8 @@ from app.bot.manage_states import EditSubject from app.bot.render import plural from app.models import Role, SchoolClass, Subject, TimetableEntry -from app.services import audit, structure -from app.services import subjects as subjects_service +from app.services import audit +from app.services.manage import subjects as subjects_service router = Router(name="manage.subjects") @@ -64,8 +64,7 @@ async def _subject_view(session: AsyncSession, school_class: SchoolClass, role: # cannot be empty while the class has a full timetable. «Собрать из # расписания» stays: it is now the button for "I have just pasted a day and # want to see its subjects without leaving", and it is still free to press. - await subjects_service.sync_from_timetable(session, school_class.id) - subjects = await _subjects_of(session, school_class.id) + subjects = await subjects_service.listing(session, school_class.id) return mr.render_subjects(subjects), subject_list_keyboard( subjects, can_edit=role.at_least(Role.ADMIN), @@ -81,9 +80,7 @@ async def _subject_by_id( subject_id = _int_or_none(raw) if subject_id is None: return None - return await session.scalar( - select(Subject).where(Subject.id == subject_id, Subject.class_id == school_class.id) - ) + return await subjects_service.subject_of(session, school_class.id, subject_id) @router.message(Command("subjects")) @@ -228,21 +225,19 @@ async def subject_rename( await state.clear() await message.answer("Предмет уже удалён.", reply_markup=back_to_menu()) return - if name == subject.name: - await state.clear() - await message.answer("Название не изменилось.", reply_markup=back_to_menu()) - return - clash = await subjects_service.clashing(session, school_class.id, name, besides=subject.id) - if clash is not None: + old_name = subject.name + try: + moved = await subjects_service.rename( + session, school_class.id, message.from_user.id, subject, name + ) + except subjects_service.SubjectExists: await message.answer( f"Предмет <b>{escape(name)}</b> уже есть. Придумайте другое название:" ) return - - days = await structure.homework_clashing(session, school_class.id, subject.name, name) - if days: - listed = ", ".join(f"{day:%d.%m}" for day in days[:5]) + except subjects_service.HomeworkClash as clash: + listed = ", ".join(f"{day:%d.%m}" for day in clash.days[:5]) await message.answer( f"На эти дни уже есть задания и по <b>{escape(subject.name)}</b>, и по " f"<b>{escape(name)}</b>: {listed}. Уберите одно из них и повторите — " @@ -251,16 +246,10 @@ async def subject_rename( ) await state.clear() return - - old_name = subject.name - moved = await structure.rename_subject(session, school_class.id, subject, name) - await audit.record( - session, - school_class.id, - message.from_user.id, - "subject.rename", - f"предмет «{old_name}» → «{name}», строк обновлено: {moved}", - ) + if moved is None: + await state.clear() + await message.answer("Название не изменилось.", reply_markup=back_to_menu()) + return await session.commit() await state.clear() @@ -278,7 +267,6 @@ async def _save_subject_text( school_class: SchoolClass, field: str, limit: int, - label: str, ) -> None: """The short-name and teacher steps: same shape, different column.""" raw = " ".join((message.text or "").split()) @@ -289,13 +277,8 @@ async def _save_subject_text( return value = None if raw in {"-", "—", ""} else raw[:limit] - setattr(subject, field, value) - await audit.record( - session, - school_class.id, - message.from_user.id, - f"subject.{field}", - f"{label} предмета «{subject.name}»: {value or 'убрано'}", + await subjects_service.set_detail( + session, school_class.id, message.from_user.id, subject, field, value ) await session.commit() await state.clear() @@ -315,9 +298,7 @@ async def subject_short_name( if not _allowed(school_class, role, Role.ADMIN): await state.clear() return - await _save_subject_text( - message, state, session, school_class, "short_name", SHORT_NAME_MAX, "сокращение" - ) + await _save_subject_text(message, state, session, school_class, "short_name", SHORT_NAME_MAX) @router.message(EditSubject.teacher) @@ -331,9 +312,7 @@ async def subject_teacher( if not _allowed(school_class, role, Role.ADMIN): await state.clear() return - await _save_subject_text( - message, state, session, school_class, "teacher", TEACHER_MAX, "учитель" - ) + await _save_subject_text(message, state, session, school_class, "teacher", TEACHER_MAX) async def _apply_colour( @@ -343,13 +322,8 @@ async def _apply_colour( telegram_id: int, colour: str | None, ) -> None: - subject.color = colour - await audit.record( - session, - school_class.id, - telegram_id, - "subject.colour", - f"цвет предмета «{subject.name}»: {colour or 'убран'}", + await subjects_service.set_detail( + session, school_class.id, telegram_id, subject, "color", colour ) await session.commit() @@ -465,20 +439,17 @@ async def subject_create( # Ignores case, so «физика» opens the class's «Физика» instead of founding # a second row beside it. - existing = await subjects_service.find(session, school_class.id, name) - if existing is not None: + try: + subject = await subjects_service.create( + session, school_class.id, message.from_user.id, name + ) + except subjects_service.SubjectExists as taken: await state.clear() await message.answer( - f"Предмет <b>{escape(existing.name)}</b> уже есть.", - reply_markup=subject_card_keyboard(existing.id), + f"Предмет <b>{escape(taken.existing.name)}</b> уже есть.", + reply_markup=subject_card_keyboard(taken.existing.id), ) return - - subject = Subject(class_id=school_class.id, name=name) - session.add(subject) - await audit.record( - session, school_class.id, message.from_user.id, "subject.add", f"добавлен предмет «{name}»" - ) await session.commit() await state.clear() await message.answer( @@ -516,24 +487,20 @@ async def subject_delete( await callback.answer("Предмет уже удалён", show_alert=True) return - in_use = await subjects_service.lessons_using(session, school_class.id, subject) - if in_use: + try: + name = await subjects_service.delete( + session, school_class.id, callback.from_user.id, subject + ) + except subjects_service.SubjectInUse as in_use: await callback.answer( # ``plural`` carries the number itself — printing it again beside # the call produced «стоит в расписании: 1 1 урок». f"«{subject.name}» стоит в расписании: " - f"{plural(in_use, 'урок', 'урока', 'уроков')}. " + f"{plural(in_use.lessons, 'урок', 'урока', 'уроков')}. " "Сначала уберите их из расписания.", show_alert=True, ) return - - name = subject.name - await session.delete(subject) - await audit.record( - session, school_class.id, callback.from_user.id, "subject.delete", - f"удалён предмет «{name}»", - ) await session.commit() await state.clear() diff --git a/server/app/bot/handlers/manage/terms.py b/server/app/bot/handlers/manage/terms.py index c9057d43..99317d2b 100644 --- a/server/app/bot/handlers/manage/terms.py +++ b/server/app/bot/handlers/manage/terms.py @@ -19,8 +19,8 @@ from app.bot.manage_keyboards import TermAction, terms_menu from app.bot.manage_states import EditTerm from app.models import Role, SchoolClass, TermKind -from app.services import audit from app.services import terms as terms_service +from app.services.manage import terms as terms_manage router = Router(name="manage.terms") @@ -36,18 +36,8 @@ # -------------------------------------------------------------------------- -def _term_year(school_class: SchoolClass) -> int: - """The school year in force *for this class*, in the class's own zone. - - Not the server's: a class in Kamchatka turns the page on 1 September nine - hours before a class in Kaliningrad, and the server is in neither. - """ - return terms_service.opening_year_of(datetime.now(school_class.tz).date()) - - async def _terms_card(session: AsyncSession, school_class: SchoolClass): - year = _term_year(school_class) - rows = await terms_service.ensure(session, school_class, year) + year, rows = await terms_manage.current(session, school_class) await session.commit() scheme = terms_service.scheme_of(school_class) @@ -106,15 +96,7 @@ async def terms_scheme( return wanted = TermKind.SEMESTER if callback_data.value == "semester" else TermKind.QUARTER - year = _term_year(school_class) - await terms_service.set_scheme(session, school_class, wanted, year) - await audit.record( - session, - school_class.id, - callback.from_user.id, - "class.term_kind", - f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", - ) + await terms_manage.change_scheme(session, school_class, callback.from_user.id, wanted) await session.commit() await state.clear() @@ -180,22 +162,14 @@ async def term_edit_apply( return try: - await terms_service.set_bounds( - session, school_class, _term_year(school_class), index, span[0], span[1] + await terms_manage.move_term( + session, school_class, message.from_user.id, index, span[0], span[1] ) except terms_service.TermError as error: # The message is the rule, in Russian, and the prompt stays open: the # admin has one date to correct, not a form to start again. await message.answer(str(error)) return - - await audit.record( - session, - school_class.id, - message.from_user.id, - "class.term", - f"период {index}: {span[0]:%d.%m.%Y} — {span[1]:%d.%m.%Y}", - ) await session.commit() await state.clear() diff --git a/server/app/bot/handlers/start.py b/server/app/bot/handlers/start.py index 6033a4b8..2d00a9ec 100644 --- a/server/app/bot/handlers/start.py +++ b/server/app/bot/handlers/start.py @@ -53,6 +53,7 @@ from app.services import audit, device_invites, linking from app.services import schools as schools_service from app.services import terms as terms_service +from app.services.manage import classes as classes_service from app.services.terms import TermError, compose_name, normalise_letter, validate_grade from app.timezones import DEFAULT_TIMEZONE, is_supported, label_for @@ -791,11 +792,13 @@ async def change_timezone_apply( if school_class is None or role is None or not role.at_least(Role.ADMIN): await callback.answer("Только для администраторов", show_alert=True) return - if not is_supported(callback_data.zone): + try: + await classes_service.set_timezone( + session, school_class, callback.from_user.id, callback_data.zone + ) + except classes_service.UnknownTimezone: await callback.answer("Неизвестный часовой пояс", show_alert=True) return - - school_class.timezone = callback_data.zone await session.commit() await callback.message.edit_text( diff --git a/server/app/services/manage/__init__.py b/server/app/services/manage/__init__.py new file mode 100644 index 00000000..4fe70f22 --- /dev/null +++ b/server/app/services/manage/__init__.py @@ -0,0 +1,24 @@ +"""Running a class: what «⚙️ Класс» in the bot and ``/api/v1/manage`` both do. + +``app.bot.handlers.manage`` and ``app.api.manage`` are two shells over the same +operations - rename a subject, make a bell schedule the default, switch a phone +off - and each used to carry its own copy of every one of them: the check, the +write, the audit line and its Russian wording. The copies agreed only while +somebody kept checking, and by the time they were brought here several had +drifted: the bot never logged a change of time zone, and a colour taken off a +subject was «убран» in one log and «убрано» in the other, which are read side +by side. + +One module per screen, named like the shells' own, so the twin of +``bot/handlers/manage/bells.py`` and of ``api/manage/bells.py`` is +``services/manage/bells.py``. + +What stays in a shell is translation: reading a payload, a paste or a callback, +and saying the outcome - in Russian in a message or an alert, or as JSON with +an English ``detail``. So a refusal here is an exception carrying the *facts* +(how many lessons, which days, which row), never a sentence, and each shell +keeps its own words for it. + +Nothing here commits, like the rest of ``app/services/``: the caller commits +the change together with its audit line, so the two land as one fact. +""" diff --git a/server/app/services/manage/bells.py b/server/app/services/manage/bells.py new file mode 100644 index 00000000..7a698c24 --- /dev/null +++ b/server/app/services/manage/bells.py @@ -0,0 +1,227 @@ +"""«🔔 Звонки» and ``/manage/bells``: the class's bell schedules. + +A class may keep several - «Обычное», «Сокращённое», «Суббота» - and a +shortened day points at one of them. One is the class default, and that one is +what every ordinary day rings. The rows themselves are written by +:func:`app.services.structure.write_bell_periods`, which also answers what a +change stops ringing; this module is the rest of what the two shells did twice. +""" + +from __future__ import annotations + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import BellSchedule, DayOverride, SchoolClass +from app.services import audit, structure +from app.services.structure import BellRow + + +class ScheduleEmpty(Exception): + """A schedule with no rows may not be the class default. + + Every ordinary day rings the default, and a day that rings nothing draws + nothing: ``/bundle`` answers zero lessons, ``/now`` answers «day_off» on a + Monday, and the phone, the widget, the calendar feed and the morning digest + go blank together with nothing anywhere reporting a problem. Worse, + ``rung_indexes`` then returns an empty set, which ``can_ring`` reads as + «this class has not set its bells up yet» and waves every lesson number + through. ``edit.day_put`` refuses the same thing at day level. + """ + + +class ScheduleIsDefault(Exception): + """The class default cannot be deleted; another one has to become it first.""" + + +class ScheduleInUse(Exception): + """Special days still point at the schedule; ``days`` says how many.""" + + def __init__(self, days: int) -> None: + super().__init__(str(days)) + self.days = days + + +async def schedules_of(session: AsyncSession, class_id: int) -> list[BellSchedule]: + """Every schedule the class keeps, in the order they were made.""" + return list( + await session.scalars( + select(BellSchedule) + .where(BellSchedule.class_id == class_id) + .order_by(BellSchedule.id) + ) + ) + + +async def schedule_of( + session: AsyncSession, class_id: int, schedule_id: int +) -> BellSchedule | None: + """Scoped by the query: another class's schedule id finds nothing.""" + return await session.scalar( + select(BellSchedule).where( + BellSchedule.id == schedule_id, BellSchedule.class_id == class_id + ) + ) + + +async def rung_by_default(session: AsyncSession, school_class: SchoolClass) -> set[int]: + """The lesson numbers the class rings today, before anything is changed. + + An empty set when the class has no default at all, which is the honest + reading: nothing was ringing, so nothing can stop. + """ + if school_class.bell_schedule_id is None: + return set() + current = await session.scalar( + select(BellSchedule).where(BellSchedule.id == school_class.bell_schedule_id) + ) + return {period.index for period in current.periods} if current is not None else set() + + +async def create( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + name: str, + rows: list[BellRow], +) -> BellSchedule: + """A new named schedule, with its rows if it came with any. + + It does not become the class default: a shortened schedule is made in + order to be pointed at by particular days, and making it the default the + moment it exists would move every day onto it. + """ + schedule = BellSchedule(class_id=school_class.id, name=name) + session.add(schedule) + await session.flush() + if rows: + await structure.write_bell_periods(session, schedule, rows) + await audit.record( + session, + school_class.id, + actor_id, + "bells.create", + f"создано расписание звонков «{name}»: {len(rows)} уроков", + ) + return schedule + + +async def rename( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + schedule: BellSchedule, + name: str, +) -> None: + """Rename a schedule. The same name again writes nothing.""" + if name == schedule.name: + return + old_name = schedule.name + schedule.name = name + await audit.record( + session, school_class.id, actor_id, "bells.rename", f"звонки «{old_name}» → «{name}»" + ) + + +async def make_default( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + schedule: BellSchedule, +) -> list[tuple[int, int]]: + """Make ``schedule`` the one every ordinary day rings. + + Moving the default to a *shorter* schedule takes lessons off every weekday + exactly as shrinking the current one does, and nothing rewrites a row, so + ``write_bell_periods`` never runs and never counts them. They are counted + here through the same function, against what the class rang a moment ago: + asking only the incoming schedule counts rows that were already silent, + which said «перестали звонить уроков: N» on a move to a schedule ringing + exactly the same numbers. + + Making the default what it already is changes nothing and logs nothing. + + @return the (weekday, number) rows that stopped ringing. + @raises ScheduleEmpty when the schedule has no rows. + """ + if not schedule.periods: + raise ScheduleEmpty(schedule.name) + if school_class.bell_schedule_id == schedule.id: + return [] + + was = await rung_by_default(session, school_class) + silenced = await structure.lessons_silenced_by( + session, school_class.id, was, {period.index for period in schedule.periods} + ) + school_class.bell_schedule_id = schedule.id + summary = f"основное расписание звонков: «{schedule.name}»" + if silenced: + summary += f", перестали звонить уроков: {len(silenced)}" + await audit.record(session, school_class.id, actor_id, "bells.default", summary) + return silenced + + +async def replace_rows( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + schedule: BellSchedule, + rows: list[BellRow], +) -> list[tuple[int, int]]: + """Replace a schedule's rows wholesale. + + Wholesale because that is what editing bells is: the times after the + lesson that moved all shift with it, and the rows that are now true are + one intention, not six. + + @return the (weekday, number) rows that stopped ringing. Shrinking the + class's own schedule takes lessons off every weekday that carried a + number past the new last rung; they are still stored and drawn nowhere, + so the log line and the shell's answer are where an admin finds out. + """ + orphaned = await structure.write_bell_periods(session, schedule, rows) + summary = f"звонки «{schedule.name}»: {len(rows)} уроков" + if orphaned: + summary += f", перестали звонить уроков: {len(orphaned)}" + await audit.record(session, school_class.id, actor_id, "bells.edit", summary) + return orphaned + + +async def delete( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + schedule: BellSchedule, +) -> str: + """Delete a schedule nothing depends on. + + Refused for the class default and for anything a day still points at. Both + are a ``SET NULL`` at the database level, which would silently move those + days onto the default schedule - a change nobody asked for, on dates an + admin is not looking at. + + @return the name it had, for the shell to say. + @raises ScheduleIsDefault, ScheduleInUse + """ + if schedule.id == school_class.bell_schedule_id: + raise ScheduleIsDefault(schedule.name) + used = int( + await session.scalar( + select(func.count()) + .select_from(DayOverride) + .where( + DayOverride.class_id == school_class.id, + DayOverride.bell_schedule_id == schedule.id, + ) + ) + or 0 + ) + if used: + raise ScheduleInUse(used) + + name = schedule.name + await session.delete(schedule) + await audit.record( + session, school_class.id, actor_id, "bells.delete", f"удалено расписание звонков «{name}»" + ) + return name diff --git a/server/app/services/manage/classes.py b/server/app/services/manage/classes.py new file mode 100644 index 00000000..83bc0482 --- /dev/null +++ b/server/app/services/manage/classes.py @@ -0,0 +1,138 @@ +"""«⚙️ Класс» and ``/manage/class``: the class's own card and settings. + +Three ways in change the class itself - the card's typed fields, the zone +picker in ``handlers/start.py`` and the join switch in ``handlers/access.py`` +- and ``PATCH /manage/class`` changes all of them at once. One audit line per +field changed, with the same action names and the same words from either +side, because that is what the log is read for: «что изменилось», not «кто +открыл настройки». +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import AccessRequest, BotUser, DeviceToken, JoinMode, SchoolClass +from app.services import audit +from app.timezones import is_supported + +#: What the log says when a join mode is switched, by the mode switched to. +JOIN_MODE_SUMMARY = { + JoinMode.INVITE: "вход только по личным приглашениям", + JoinMode.OPEN: "вход по коду класса снова разрешён", +} + + +class UnknownTimezone(ValueError): + """A zone this deployment does not offer.""" + + +class NameMismatch(ValueError): + """The name typed back to confirm a deletion is not the class's name.""" + + +@dataclass(frozen=True) +class Counts: + """The three numbers the class card shows.""" + + members: int + devices: int + pending: int + + +async def _count(session: AsyncSession, model: type, *where: object) -> int: + return int(await session.scalar(select(func.count()).select_from(model).where(*where)) or 0) + + +async def counts(session: AsyncSession, class_id: int) -> Counts: + """Members, phones that are still switched on, and requests nobody answered.""" + return Counts( + members=await _count(session, BotUser, BotUser.class_id == class_id), + devices=await _count( + session, + DeviceToken, + DeviceToken.class_id == class_id, + DeviceToken.revoked.is_(False), + ), + pending=await _count( + session, + AccessRequest, + AccessRequest.class_id == class_id, + AccessRequest.status == "pending", + ), + ) + + +async def members(session: AsyncSession, class_id: int) -> list[BotUser]: + """Everybody with a role in the class, for a shell to put names to ids.""" + return list(await session.scalars(select(BotUser).where(BotUser.class_id == class_id))) + + +async def set_field( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + column: str, + value: object, +) -> None: + """Set one plain column of the class and log it as ``class.<column>``.""" + setattr(school_class, column, value) + await audit.record( + session, school_class.id, actor_id, f"class.{column}", f"{column}: {value or 'убрано'}" + ) + + +async def set_timezone( + session: AsyncSession, school_class: SchoolClass, actor_id: int | None, zone: str +) -> None: + """Move the class to another zone. + + No stored time moves - a bell rings at 08:30 whatever the zone says - what + changes is which instant the class calls «сейчас». Logged from both sides; + the bot's picker used to change it without a line, so the one change that + shifts every «now» on every phone was the one the log could not explain. + + @raises UnknownTimezone for a zone that is not on the list. + """ + if not is_supported(zone): + raise UnknownTimezone(zone) + school_class.timezone = zone + await audit.record( + session, school_class.id, actor_id, "class.timezone", f"часовой пояс: {zone}" + ) + + +async def set_join_mode( + session: AsyncSession, school_class: SchoolClass, actor_id: int | None, mode: JoinMode +) -> bool: + """Who may join with the class code. Revokes no device, in either direction. + + @return whether it changed. Switching to the mode already in force writes + nothing, from either side. + """ + if school_class.join_mode is mode: + return False + school_class.join_mode = mode + await audit.record( + session, school_class.id, actor_id, "access.join_mode", JOIN_MODE_SUMMARY[mode] + ) + return True + + +async def delete(session: AsyncSession, school_class: SchoolClass, confirm_name: str) -> None: + """Delete the class and everything hanging off it. + + The name typed back is the confirmation, and the only one: a «вы уверены?» + button is pressed by the same thumb that pressed the one before it, while a + name has to be read off the screen first. Nothing is written to the log - + the log lives in the class and goes with it. + + @raises NameMismatch unless ``confirm_name`` is the name, give or take + the whitespace around it. + """ + if confirm_name.strip() != school_class.name: + raise NameMismatch(confirm_name) + await session.delete(school_class) diff --git a/server/app/services/manage/devices.py b/server/app/services/manage/devices.py new file mode 100644 index 00000000..43e189f0 --- /dev/null +++ b/server/app/services/manage/devices.py @@ -0,0 +1,90 @@ +"""«📱 Устройства» and ``/manage/devices``: the phones on a class. + +A device token is read-only until its owner links it to a Telegram account; +from then on it writes with whatever role that account holds *right now* +(:func:`app.services.linking.effective_role`). Which is why a role is a lookup +and never something stored on the row: revoking somebody in «Доступ» has +already revoked their phone by the time a list of phones is drawn. +""" + +from __future__ import annotations + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import DeviceToken, Role +from app.services import audit, linking + + +class DeviceNotLinked(Exception): + """There is no account behind the phone, so there is nothing to unlink.""" + + +def label(device: DeviceToken) -> str: + """What the log and the answers call a phone that never gave its name.""" + return device.device_name or f"Устройство {device.id}" + + +async def device_of(session: AsyncSession, class_id: int, device_id: int) -> DeviceToken | None: + """Scoped by the query: another class's device id finds nothing.""" + return await session.scalar( + select(DeviceToken).where(DeviceToken.id == device_id, DeviceToken.class_id == class_id) + ) + + +async def owner_roles( + session: AsyncSession, devices: list[DeviceToken] +) -> dict[int, Role | None]: + """Each linked owner's role right now, looked up once per owner. + + The role hangs off the account, not the phone, and a class where everybody + joined from their own phone was paying a round trip a row for an answer + already in hand. + """ + roles: dict[int, Role | None] = {} + for device in devices: + if device.telegram_id is not None and device.telegram_id not in roles: + roles[device.telegram_id] = await linking.effective_role(session, device) + return roles + + +async def revoke( + session: AsyncSession, class_id: int, actor_id: int | None, device: DeviceToken +) -> bool: + """Switch a phone off. Revoked, not deleted: the row is what a token is + checked against, and keeping it is what makes the refusal instant and + permanent. + + A phone already off changes nothing and adds no second line to the log - + the bot's copy of this used to add one for every press of a stale button. + + @return whether anything changed. + """ + if device.revoked: + return False + device.revoked = True + await audit.record( + session, class_id, actor_id, "device.revoke", f"отключено устройство «{label(device)}»" + ) + return True + + +async def unlink( + session: AsyncSession, class_id: int, actor_id: int | None, device: DeviceToken +) -> None: + """Back to read-only, without taking the phone off the class. + + @raises DeviceNotLinked when nobody's account is behind it: whoever pressed + it expected something to change, and silence would say it had. + """ + if device.telegram_id is None: + raise DeviceNotLinked(label(device)) + name = label(device) + await linking.unlink_device(session, device) + await audit.record( + session, + class_id, + actor_id, + "device.unlink", + f"отвязано устройство «{name}» — снова только чтение", + ) diff --git a/server/app/services/manage/journal.py b/server/app/services/manage/journal.py new file mode 100644 index 00000000..a02630c4 --- /dev/null +++ b/server/app/services/manage/journal.py @@ -0,0 +1,21 @@ +"""«📜 Журнал» and ``/manage/log``: who changed what, a page at a time.""" + +from __future__ import annotations + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import AuditEntry +from app.services import audit + + +async def page( + session: AsyncSession, class_id: int, *, limit: int, offset: int +) -> tuple[list[AuditEntry], bool]: + """``limit`` lines from ``offset``, newest first, and whether more follow. + + One row more than ``limit`` is read and thrown away: that is what «more» + is, and it costs one row instead of the count of an append-only table on + every page turn. + """ + entries = await audit.recent(session, class_id, limit=limit + 1, offset=offset) + return entries[:limit], len(entries) > limit diff --git a/server/app/services/manage/requests.py b/server/app/services/manage/requests.py new file mode 100644 index 00000000..9ebfb410 --- /dev/null +++ b/server/app/services/manage/requests.py @@ -0,0 +1,65 @@ +"""«🙋 Запрос доступа» and ``/manage/requests``: the requests waiting for an answer. + +Granting is :func:`app.services.access.approve_request`, which both shells +already shared; this is the rest of what they wrote twice - finding a request +that is still open, and saying no. +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from html import escape + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import AccessRequest, SchoolClass +from app.services import audit + + +async def pending(session: AsyncSession, class_id: int) -> list[AccessRequest]: + """Everybody waiting for a role, oldest first.""" + return list( + await session.scalars( + select(AccessRequest) + .where(AccessRequest.class_id == class_id, AccessRequest.status == "pending") + .order_by(AccessRequest.id) + ) + ) + + +async def pending_one( + session: AsyncSession, class_id: int, request_id: int +) -> AccessRequest | None: + """Pending, and this class's. A request that has already been answered is + gone as far as either shell is concerned, so two admins tapping «Выдать» at + once cannot grant twice.""" + return await session.scalar( + select(AccessRequest).where( + AccessRequest.id == request_id, + AccessRequest.class_id == class_id, + AccessRequest.status == "pending", + ) + ) + + +async def decline( + session: AsyncSession, class_id: int, actor_id: int, request: AccessRequest +) -> None: + """Say no. The person keeps whatever role they already had.""" + request.status = "declined" + request.decided_by = actor_id + request.decided_at = datetime.now(UTC).replace(tzinfo=None) + await audit.record( + session, + class_id, + actor_id, + "access.decline", + f"отклонён запрос доступа от {request.telegram_id}", + ) + + +def decline_notice(school_class: SchoolClass) -> str: + """What the requester is told in Telegram - silence would leave them asking + again. HTML, because it goes out through the bot.""" + return f"✖️ Запрос доступа в классе <b>{escape(school_class.name)}</b> отклонён." diff --git a/server/app/services/manage/subjects.py b/server/app/services/manage/subjects.py new file mode 100644 index 00000000..7b3f8839 --- /dev/null +++ b/server/app/services/manage/subjects.py @@ -0,0 +1,191 @@ +"""«📚 Предметы» and ``/manage/subjects``: what an admin does to the dictionary. + +The dictionary itself - matching names, adopting the timetable's - is +:mod:`app.services.subjects`; the cascade a rename sets off is +:func:`app.services.structure.rename_subject`. This is the part the two shells +used to write out twice: the checks in front of a change and the line it +leaves in the log. +""" + +from __future__ import annotations + +from datetime import date as Date + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import Subject +from app.services import audit, structure +from app.services import subjects as dictionary + +#: What an admin may set beside the name: column -> (audit action, the word the +#: log line uses, the word for «taken away»). The colour is «цвет … убран» and +#: the other two «убрано», as the bot always wrote them; the phone's copy of +#: this table said «убрано» for all three. +DETAILS: dict[str, tuple[str, str, str]] = { + "short_name": ("subject.short_name", "сокращение", "убрано"), + "teacher": ("subject.teacher", "учитель", "убрано"), + "color": ("subject.colour", "цвет", "убран"), +} + + +class SubjectExists(Exception): + """The name is already an entry of the class, ignoring case. + + ``existing`` is that entry: the bot opens it, the API answers 409. + """ + + def __init__(self, existing: Subject) -> None: + super().__init__(existing.name) + self.existing = existing + + +class HomeworkClash(Exception): + """A rename would put two assignments on one subject and one day. + + Homework is unique per subject per day, and it may be written under a name + that is no dictionary entry, so the name check cannot see this. See + :func:`app.services.structure.homework_clashing`. + """ + + def __init__(self, days: list[Date]) -> None: + super().__init__(", ".join(day.isoformat() for day in days)) + self.days = days + + +class SubjectInUse(Exception): + """The weekly template still teaches the subject; ``lessons`` says how often.""" + + def __init__(self, lessons: int) -> None: + super().__init__(str(lessons)) + self.lessons = lessons + + +async def listing(session: AsyncSession, class_id: int) -> list[Subject]: + """The dictionary, alphabetically, after adopting what the timetable uses. + + So the list cannot be empty while the class has a full timetable. The + adoption writes when something is out of step, and the caller commits it. + """ + await dictionary.sync_from_timetable(session, class_id) + return list( + await session.scalars( + select(Subject).where(Subject.class_id == class_id).order_by(Subject.name) + ) + ) + + +async def subject_of(session: AsyncSession, class_id: int, subject_id: int) -> Subject | None: + """Scoped by the query itself: an id naming another class's subject finds + nothing, whatever the payload claims.""" + return await session.scalar( + select(Subject).where(Subject.id == subject_id, Subject.class_id == class_id) + ) + + +async def create( + session: AsyncSession, + class_id: int, + actor_id: int | None, + name: str, + *, + short_name: str | None = None, + teacher: str | None = None, + color: str | None = None, +) -> Subject: + """Add an entry. The name is unique within the class, ignoring case - that + uniqueness is the whole point of the dictionary. + + @raises SubjectExists when the class already has the name. + """ + existing = await dictionary.clashing(session, class_id, name) + if existing is not None: + raise SubjectExists(existing) + subject = Subject( + class_id=class_id, name=name, short_name=short_name, teacher=teacher, color=color + ) + session.add(subject) + await audit.record(session, class_id, actor_id, "subject.add", f"добавлен предмет «{name}»") + return subject + + +async def rename( + session: AsyncSession, class_id: int, actor_id: int | None, subject: Subject, name: str +) -> int | None: + """Rename ``subject``, and with it every row that spells its old name. + + The timetable, the homework and the substitutions store the subject as + text, so all three move in the caller's one transaction. + + @return how many rows moved, or ``None`` when ``name`` is what the subject + is already called - nothing is written then. + @raises SubjectExists when another entry has the name: merging two subjects + is a different operation, and doing it by accident cannot be undone. + @raises HomeworkClash when both names have homework on the same day. + """ + if name == subject.name: + return None + clash = await dictionary.clashing(session, class_id, name, besides=subject.id) + if clash is not None: + raise SubjectExists(clash) + days = await structure.homework_clashing(session, class_id, subject.name, name) + if days: + raise HomeworkClash(days) + + old_name = subject.name + moved = await structure.rename_subject(session, class_id, subject, name) + await audit.record( + session, + class_id, + actor_id, + "subject.rename", + f"предмет «{old_name}» → «{name}», строк обновлено: {moved}", + ) + return moved + + +async def set_detail( + session: AsyncSession, + class_id: int, + actor_id: int | None, + subject: Subject, + column: str, + value: str | None, +) -> None: + """Set the short name, the teacher or the colour; ``None`` takes it away. + + ``column`` is a key of :data:`DETAILS`, and anything else is a ``KeyError`` + rather than a column written blind. + """ + action, label, removed = DETAILS[column] + setattr(subject, column, value) + await audit.record( + session, + class_id, + actor_id, + action, + f"{label} предмета «{subject.name}»: {value or removed}", + ) + + +async def delete( + session: AsyncSession, class_id: int, actor_id: int | None, subject: Subject +) -> str: + """Take an entry out of the dictionary, if nothing teaches it any more. + + Deleting a subject the timetable still uses used to be allowed, and it left + the lessons alone - but the name is still in the template, so the next read + adopted it back, stripped of its colour and its teacher, and the admin was + left believing they had deleted something. So the order is stated instead: + out of the timetable first, out of the dictionary second. + + @return the name it had, for the shell to say. + @raises SubjectInUse while the weekly template still teaches it. + """ + in_use = await dictionary.lessons_using(session, class_id, subject) + if in_use: + raise SubjectInUse(in_use) + name = subject.name + await session.delete(subject) + await audit.record(session, class_id, actor_id, "subject.delete", f"удалён предмет «{name}»") + return name diff --git a/server/app/services/manage/terms.py b/server/app/services/manage/terms.py new file mode 100644 index 00000000..7eff2287 --- /dev/null +++ b/server/app/services/manage/terms.py @@ -0,0 +1,80 @@ +"""«🗓 Четверти» and ``/manage/terms``: quarters and half-years, edited. + +The rules - which dates a term may span, what overlaps - are +:mod:`app.services.terms`. This is the year both shells edit and the line each +edit leaves in the log. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import datetime + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import SchoolClass, Term, TermKind +from app.services import audit +from app.services import terms as terms_service + + +def current_year(school_class: SchoolClass) -> int: + """The school year in force *for this class*, in the class's own zone. + + Not the server's: a class in Kamchatka turns the page on 1 September nine + hours before a class in Kaliningrad, and the server is in neither. + """ + return terms_service.opening_year_of(datetime.now(school_class.tz).date()) + + +async def current(session: AsyncSession, school_class: SchoolClass) -> tuple[int, list[Term]]: + """This year's terms, seeding the conventional set if the class has none. + + The seeding writes, and the caller commits it. + """ + year = current_year(school_class) + return year, await terms_service.ensure(session, school_class, year) + + +async def change_scheme( + session: AsyncSession, school_class: SchoolClass, actor_id: int | None, wanted: TermKind +) -> list[Term]: + """Switch between quarters and half-years, reseeding the year. + + A replacement rather than an edit: four quarters and two halves do not map + onto each other. + """ + rows = await terms_service.set_scheme(session, school_class, wanted, current_year(school_class)) + await audit.record( + session, + school_class.id, + actor_id, + "class.term_kind", + f"схема: {'полугодия' if wanted is TermKind.SEMESTER else 'четверти'}", + ) + return rows + + +async def move_term( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + index: int, + starts_on: Date, + ends_on: Date, +) -> int: + """Move one term's edges within this year. + + @return the year it was moved in. + @raises terms_service.TermError with the rule, in Russian, when the dates + do not fit the year or overlap a neighbour. Nothing is logged then. + """ + year, _ = await current(session, school_class) + await terms_service.set_bounds(session, school_class, year, index, starts_on, ends_on) + await audit.record( + session, + school_class.id, + actor_id, + "class.term", + f"период {index}: {starts_on:%d.%m.%Y} — {ends_on:%d.%m.%Y}", + ) + return year diff --git a/server/app/services/manage/timetable.py b/server/app/services/manage/timetable.py new file mode 100644 index 00000000..a5f4b89b --- /dev/null +++ b/server/app/services/manage/timetable.py @@ -0,0 +1,68 @@ +"""«📤 Экспорт», «📥 Импорт» and ``/manage/timetable``: the weekly template as text. + +The same format in both directions, which is what makes it a backup: a text +saved out of the bot goes back in through the app, and the other way round. +The grammar is :mod:`app.services.timetable_io` and the write is +:func:`app.services.structure.apply_timetable`; this is what the two shells +did around them. +""" + +from __future__ import annotations + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import BellPeriod, BellSchedule, SchoolClass, TimetableEntry +from app.services import audit, structure, timetable_io +from app.services.structure import BellRow, TimetableImport + + +async def export(session: AsyncSession, school_class: SchoolClass) -> tuple[str, int]: + """The whole template in the paste format, and how many lessons are in it. + + An empty template is an empty string: there is nothing wrong with a class + that has not filled one in yet. + """ + entries = list( + await session.scalars( + select(TimetableEntry) + .where(TimetableEntry.class_id == school_class.id) + .order_by(TimetableEntry.weekday, TimetableEntry.index) + ) + ) + periods: list[BellPeriod] = [] + if school_class.bell_schedule_id: + schedule = await session.get(BellSchedule, school_class.bell_schedule_id) + if schedule is not None: + periods = list(schedule.periods) + return timetable_io.export_timetable(entries, periods), len(entries) + + +async def apply( + session: AsyncSession, + school_class: SchoolClass, + actor_id: int | None, + days: dict[int, list], + bells: list[BellRow], +) -> TimetableImport: + """Replace exactly the weekdays a paste named, and its bells if it had any. + + Days the paste does not mention are left alone, so importing one day's + block is a legitimate thing to do, and a day named with nothing under it is + emptied - that is how a paste says «в четверг уроков нет». + + The log line counts rows, not numbers, in both directions: «8. Алгебра» + under Monday and under Tuesday is two lessons nobody will see, and so is a + stored lesson the new bells no longer ring. The bot's copy of this line + never said the second. + """ + result = await structure.apply_timetable(session, school_class, days, bells) + summary = f"импорт расписания: дней {len(days)}, уроков {result.written}" + if bells: + summary += f", звонков {len(bells)}" + if result.dropped: + summary += f", без звонка пропущено {len(result.dropped)}" + if result.orphaned: + summary += f", перестали звонить {len(result.orphaned)}" + await audit.record(session, school_class.id, actor_id, "timetable.import", summary) + return result From 35b6e841d4b2673ded58af691be725a96fb0b71f Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 19:02:23 +0300 Subject: [PATCH 32/43] Tell the join screen's reader that a kept http address needs https, not that there is none MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The release build refuses a plain http:// server address before the request leaves (#202), with ServerNeedsHttpsException, a kind of ServerAddressMissingException. The join screen classified by the parent, so a phone that kept an http:// address from an older version and sent a class code read «Не указан адрес сервера» directly above the row showing that address. JoinError.NeedsHttps is asked first and says the same sentence the address sheet, a sync and the diary sign-in say (server_needs_https, which already has its English twin). JoinErrorTest pins the classification, bare and wrapped; it failed before the change (NoServer), and JoinErrorTextTest pins the sentence. Also, from reviewing #202's commit: the debug network configuration's comment is rewrapped, build.md links the emulator section and names the join among the places that say https, and a sentence in the English privacy policy is repaired. Not covered: the first run's school search by name still words the same refusal as «no server is set» (DirectoryProblem.ServerMissing → onboarding_region_school_no_server). Its advice, to pick the region from the list, is still the right one, and only an address kept from an older version reaches it; it is left for the owner of the onboarding screens. Refs #202 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../debug/res/xml/network_security_config.xml | 5 ++-- .../lessons/ui/join/JoinScreen.kt | 1 + .../lessons/ui/join/JoinViewModel.kt | 23 ++++++++++++++----- .../lessons/ui/join/JoinErrorTest.kt | 18 +++++++++++++++ .../lessons/ui/join/JoinErrorTextTest.kt | 9 ++++++++ docs/build.md | 17 +++++++------- docs/legal/privacy.en.md | 2 +- docs/legal/privacy.ru.md | 5 ++-- 8 files changed, 61 insertions(+), 19 deletions(-) diff --git a/android/app/src/debug/res/xml/network_security_config.xml b/android/app/src/debug/res/xml/network_security_config.xml index 5832e936..9dfcd045 100644 --- a/android/app/src/debug/res/xml/network_security_config.xml +++ b/android/app/src/debug/res/xml/network_security_config.xml @@ -5,8 +5,9 @@ It overrides src/main/res/xml/network_security_config.xml, which is the release build's and refuses plain http:// except to the phone itself (#202), because a debug build is what runs against uvicorn on the developer's own - machine, reached by its LAN address or by the emulator's 10.0.2.2. The app's refusal of an http:// address reads this same answer, so - a debug build neither refuses one nor calls it refused. + machine, reached by its LAN address or by the emulator's 10.0.2.2. The app's + refusal of an http:// address reads this same answer, so a debug build + neither refuses one nor calls it refused. Only the cleartext rule differs. Trust stays what it is in release - system CAs only - so a debug build is not the one that learns to trust a proxy's diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt index 7801f57b..54e297a9 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt @@ -354,6 +354,7 @@ internal fun JoinError?.asText(): String? = when (this) { JoinError.InvalidCode -> correctedString(R.string.join_error_invalid_code, ClassCodeLengths.first, ClassCodeLengths.last) JoinError.UnknownCode -> correctedString(R.string.join_error_unknown_code) JoinError.NoServer -> correctedString(R.string.join_error_no_server) + JoinError.NeedsHttps -> correctedString(R.string.server_needs_https) JoinError.InviteOnly -> correctedString(R.string.join_error_invite_only) is JoinError.TooManyAttempts -> minutes ?.let { pluralStringResource(R.plurals.join_error_too_many_wait, it, it) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt index 08cc3798..ae92089f 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt @@ -8,6 +8,7 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.repository.JoinFailure import com.lumenpearson.lessons.core.data.repository.SessionRepository import com.lumenpearson.lessons.core.data.repository.SettingsRepository @@ -68,6 +69,16 @@ sealed interface JoinError { */ data object NoServer : JoinError + /** + * The address is plain `http://`, which a release build does not send to + * (#202); nothing was asked. Not [NoServer], whose kind it is to the + * interceptor: the address is right there under the button, and «Не + * указан адрес сервера» sent the reader looking for a field they had + * filled. Only an address kept from an older version gets this far — the + * sheet that takes a new one refuses it where it is typed. + */ + data object NeedsHttps : JoinError + /** * The server refused the code some other way, or was unreachable. * @@ -101,12 +112,12 @@ sealed interface JoinError { // «Не удалось подключиться: failed to connect to /10.0.2.2 (port // 8000) from /10.0.2.16 …» (#177). The screen's own sentence is // the answer to a server that cannot be reached. - is JoinFailure.Offline -> - if (classified.reason.causes().any { it is ServerAddressMissingException }) { - NoServer - } else { - Rejected(null) - } + // The https refusal is asked first: it is a kind of missing address. + is JoinFailure.Offline -> when { + classified.reason.causes().any { it is ServerNeedsHttpsException } -> NeedsHttps + classified.reason.causes().any { it is ServerAddressMissingException } -> NoServer + else -> Rejected(null) + } is JoinFailure.Rejected -> Rejected(classified.reason?.message?.takeIf { it.isNotBlank() }) } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt index 32e576f9..6b57ab4c 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt @@ -1,6 +1,7 @@ package com.lumenpearson.lessons.ui.join import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.ServerNeedsHttpsException import com.lumenpearson.lessons.core.data.repository.JoinFailure import java.io.IOException import org.junit.Assert.assertEquals @@ -108,4 +109,21 @@ class JoinErrorTest { ) assertEquals(JoinError.NoServer, wrapped) } + + /** + * #202: an http:// address kept from an older version, refused before the + * request left. It is a kind of missing address to the interceptor, and + * «Не указан адрес сервера» was what the screen said about it — above the + * row that shows the address. + */ + @Test + fun `an http address this build refuses is not a missing one`() { + val refused = JoinError.of(JoinFailure.Offline(ServerNeedsHttpsException("192.168.1.50"))) + assertEquals(JoinError.NeedsHttps, refused) + + val wrapped = JoinError.of( + JoinFailure.Offline(IOException("call failed", ServerNeedsHttpsException("192.168.1.50"))), + ) + assertEquals(JoinError.NeedsHttps, wrapped) + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt index 07dc4823..89f03c26 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt @@ -95,4 +95,13 @@ class JoinErrorTextTest { compose.onNodeWithText("Не указан адрес сервера", substring = true).assertIsDisplayed() compose.onNodeWithText("«Адрес сервера»", substring = true).assertIsDisplayed() } + + /** #202: the address is there, and the sentence is about what it starts with. */ + @Test + fun `a refused http address asks for the https one`() { + show(JoinError.NeedsHttps) + + compose.onNodeWithText("начинается с https://", substring = true).assertIsDisplayed() + compose.onNodeWithText("Не указан адрес сервера", substring = true).assertDoesNotExist() + } } diff --git a/docs/build.md b/docs/build.md index eb2b2665..de15b2b0 100644 --- a/docs/build.md +++ b/docs/build.md @@ -730,10 +730,11 @@ The app needs an address the **phone** can reach, not the computer. `localhost` `127.0.0.1` do not work in the app: to a phone, those are the phone. **This is the debug build's route.** A release build speaks `https://` to its server and -nothing else, except to the phone itself (#202, and [below](#why-a-debug-build-speaks-http-and-a-release-build-does-not)): -it refuses the `http://<address>:8000/` of step 4 where it is typed, with a sentence about -https. With a release build, go through the `adb` tunnel described under «On the -emulator» — it works for a phone on a cable too — or put the server behind TLS. +nothing else, except to the phone itself (#202, and +[below](#why-a-debug-build-speaks-http-and-a-release-build-does-not)): it refuses the +`http://<address>:8000/` of step 4 where it is typed, with a sentence about https. With a +release build, go through the `adb` tunnel described [on the emulator](#on-the-emulator) — +it works for a phone on a cable too — or put the server behind TLS. 1. Start the server so that it listens on more than the loopback: @@ -817,10 +818,10 @@ below) is not worth that case (#202), so there are now two files: The app asks that configuration before it sends anything (`CleartextPolicy` in `:core:data`, through `NetworkSecurityPolicy` — the question OkHttp asks too). The address -sheet refuses a refused `http://` address where it is typed; one kept from an older version -is refused by the base-URL interceptor before the request leaves, and a sync, the server -badge and the diary sign-in each say it needs `https://` rather than showing a network -error. `NetworkSecurityConfigTest` holds both files to the rule. +sheet refuses such an address where it is typed and holds «Сохранить»; one kept from an +older version is refused by the base-URL interceptor before the request leaves, and a sync, +the server badge, a join and the diary sign-in each say it needs `https://` rather than +showing a network error. `NetworkSecurityConfigTest` holds both files to the rule. What travels over a plain `http://` wire is **not** harmless, and this page used to say it was — «only a class code and a timetable: no passwords, no personal data». The diary diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index 232cb9c8..4560fb17 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -195,7 +195,7 @@ A parent who wants the server to delete their child's data can write to the oper - The server encrypts the diary session (Fernet: AES-128-CBC with HMAC) with a key the operator sets. Without that key the diary does not run on the server at all, rather than keeping sessions unencrypted. - On the phone the app encrypts only the class and diary access keys (AES-256-GCM, with a key from the Android Keystore). If the phone's key store does not work, it keeps them unencrypted, as it used to, and tries again to encrypt them at every start. Everything else — the copies of the timetable and the diary, the login, the settings — is protected only by whatever protects the phone itself. The encryption of the keys has not yet been checked on a device. -**The app talks to the server over HTTPS only.** It does not accept an address that starts with `http://`, and sends nothing to one: at such an address everything between the phone and the server — the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in — would travel in the clear, and anybody on the same network could intercept it and open your diary. The exception is a server on the phone itself (`localhost`, `127.0.0.1`), which requests to never leave the phone. A debug build of the app, made for development, does accept `http://` addresses, and sends everything to them in the clear. +**The app talks to the server over HTTPS only.** It does not accept an address that starts with `http://`, and sends nothing to one: at such an address everything between the phone and the server — the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in — would travel in the clear, and anybody on the same network could intercept it and open your diary. The exception is a server on the phone itself (`localhost`, `127.0.0.1`): requests to it never leave the phone. A debug build of the app, made for development, does accept `http://` addresses, and sends everything to them in the clear. In the app, whatever the server's address, the diary password goes only to the diary's system, and only over HTTPS. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index 1babe682..942c84ed 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -22,8 +22,9 @@ not in Russia; the operator holds the key and can read the diary; leaving a class deletes nothing on the server; the phone encrypts the two access keys and nothing else, and keeps them bare where its Keystore does not work; a debug build still sends everything in the - clear to an http:// server address, and a release build to one on the phone itself; the keep-alive runs for up to 30 days after the last - use, not only while somebody is active; a correction to the diary is the child's rather + clear to an http:// server address, and a release build to one on the phone itself; the + keep-alive runs for up to 30 days after the last use, not only while somebody is active; a + correction to the diary is the child's rather than the account's, so every account whose diary lists that pupil reads, changes and resets it, and no row says who wrote it, so the operator cannot pick out one adult's corrections: a request to delete "mine" is met for the whole child, or for the particular From 23e25694c99b9080c1a096fee4e4fe19e16ad284 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 19:40:07 +0300 Subject: [PATCH 33/43] =?UTF-8?q?Gate=20every=20=C2=AB=E2=9A=99=EF=B8=8F?= =?UTF-8?q?=20=D0=9A=D0=BB=D0=B0=D1=81=D1=81=C2=BB=20handler=20with=20one?= =?UTF-8?q?=20decorator,=20and=20move=20its=20queries=20into=20services?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The role check was written out at the top of seventy-two handlers - sixty-seven calls to `_allowed` and five inline copies of it - each followed by its own refusal, while the API answered the same question with one dependency per level. Now a handler says what it needs where it is registered, `@needs(Role.ADMIN)` under its `@router…` line, and `handlers/manage/_common.py` holds the check and the three shapes a refusal takes, each exactly what the handlers did by hand: a press is answered with an alert, a command with a sentence, and a step of a form (`step=True`) drops the form without an answer (a press in one is still answered). The sentence is `_refusal`'s unless the handler names one - the diary binding's «Только для администраторов» and the delete prompt's «Только для владельца класса» are said to everybody, as before. `_refusal` now says «нет доступа» for a screen every member may open, which is what all seven such handlers wrote by hand. A decorator rather than an aiogram filter or a flag read by a middleware, because the check has to travel with the function. A filter that fails does not refuse - aiogram offers the update to the next handler and in the end to `unknown` - and a flag is read only on the way in through the dispatcher, while the tests that press every step as a наблюдатель and demand a refusal call the handlers directly. aiogram reads what to inject off the unwrapped function, so every handler still receives what it declares, and `functools.wraps` keeps the names: the dumped handler order (names, filters, flags) is identical before and after. A handler that cannot show its role, class or form to the decorator is a `TypeError` at import. The handlers' own SQL went into the services: the special days' list, the mark on a day and marking one or a period (`services/manage/special_days`), the homework search behind /find (`services/manage/search`), «Собрать из расписания» (`subjects.collect`), raising an access request and finding the admins to tell (`requests.submit`, `requests.admins`), whether a bell schedule rings anything (`bells.rings_anything`), and the classes behind a person's memberships (`classes.classes_of`, `classes.class_of`). No `select(` is left in `bot/handlers/manage/`. Every callback-data guard (`_int_or_none`, `_date_or_none`, `_day_kind_or_none`) stays where the value is picked. One handler keeps its check in its body: the diary binding's last step binds the class the form started in, carried in the state, and it is that class which must exist; it says so above the check. Tests: the reader in `test_the_role_check_above_reaches_every_handler_that_has_one` learns the decorator spelling (the other two stay); new tests drive a manage press and a form step through the real dispatcher as a наблюдатель and as an admin, and hold the import-time refusal. Not covered: the role checks in the other handler modules (`content.py`, `access.py`, `start.py`, …) are written their own ways and were not part of #207, which is about the management handlers. Closes #207 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/app/bot/handlers/manage/__init__.py | 8 +- server/app/bot/handlers/manage/_common.py | 98 ++++++++- server/app/bot/handlers/manage/audit_log.py | 19 +- server/app/bot/handlers/manage/bells.py | 80 +++---- .../app/bot/handlers/manage/calendar_feed.py | 27 +-- server/app/bot/handlers/manage/class_card.py | 85 +++----- server/app/bot/handlers/manage/devices.py | 36 ++-- .../app/bot/handlers/manage/diary_binding.py | 57 +++-- server/app/bot/handlers/manage/holidays.py | 196 +++++------------- .../app/bot/handlers/manage/import_export.py | 44 ++-- server/app/bot/handlers/manage/requests.py | 91 +++----- server/app/bot/handlers/manage/stats.py | 47 ++--- server/app/bot/handlers/manage/subjects.py | 148 ++++--------- server/app/bot/handlers/manage/terms.py | 37 ++-- server/app/services/manage/bells.py | 12 +- server/app/services/manage/classes.py | 19 ++ server/app/services/manage/requests.py | 52 ++++- server/app/services/manage/search.py | 37 ++++ server/app/services/manage/special_days.py | 86 ++++++++ server/app/services/manage/subjects.py | 37 +++- server/tests/test_bot_commands.py | 55 ++++- server/tests/test_bot_manage.py | 45 +++- 22 files changed, 706 insertions(+), 610 deletions(-) create mode 100644 server/app/services/manage/search.py create mode 100644 server/app/services/manage/special_days.py diff --git a/server/app/bot/handlers/manage/__init__.py b/server/app/bot/handlers/manage/__init__.py index b8e6c6ae..a5236e51 100644 --- a/server/app/bot/handlers/manage/__init__.py +++ b/server/app/bot/handlers/manage/__init__.py @@ -6,14 +6,16 @@ Three rules hold everywhere in this package, and each of them is the answer to a way the previous shape of this code could be abused: -* **A role check at the top of every handler, including every FSM step.** - FSM state is per-user and therefore attacker-controlled: a client can set +* **A role check on every handler, including every FSM step** - the + ``@needs(Role.X)`` under its ``@router…`` line (``_common.needs``). FSM + state is per-user and therefore attacker-controlled: a client can set itself into ``EditSubject.name`` and send a message, so a step that trusted the step before it would be a rename with no permission check at all. * **Every id arrives as text and is re-scoped by the query that reads it.** Callback data is user-supplied. A subject is never fetched by id alone but by ``(id, class_id)``, so a crafted payload naming another class's row finds - nothing rather than editing it. + nothing rather than editing it. The queries are ``app.services.manage``'s; + no handler here runs SQL of its own. * **No state in the process.** Every Vercel invocation is a fresh Python process, so anything that has to survive a step lives in FSM storage (the database) or in the callback payload - never in a module-level dict. diff --git a/server/app/bot/handlers/manage/_common.py b/server/app/bot/handlers/manage/_common.py index ca5f7d79..ac07c72f 100644 --- a/server/app/bot/handlers/manage/_common.py +++ b/server/app/bot/handlers/manage/_common.py @@ -1,14 +1,19 @@ """What every screen of :mod:`app.bot.handlers.manage` shares. -The refusal sentences, the one permission check, and the small parsers that -turn a value the client sent into one the handlers can trust or ``None``. +The refusal sentences, the one role check every handler is gated by +(:func:`needs`), and the small parsers that turn a value the client sent into +one the handlers can trust or ``None``. """ from __future__ import annotations +import functools +import inspect import re +from collections.abc import Awaitable, Callable from datetime import date as Date from datetime import datetime +from typing import ParamSpec from aiogram.types import CallbackQuery, Message from sqlalchemy.ext.asyncio import AsyncSession @@ -35,13 +40,100 @@ def _allowed(school_class: SchoolClass | None, role: Role | None, minimum: Role) def _refusal(role: Role | None, minimum: Role) -> str: - if role is None: + """The sentence a refusal says. A screen every member may open refuses + only somebody who is not one, so it is «нет доступа» whatever else.""" + if role is None or minimum is Role.VIEWER: return NO_ACCESS if minimum is Role.OWNER: return NEED_OWNER return NEED_ADMIN if minimum is Role.ADMIN else NEED_EDITOR +_P = ParamSpec("_P") + + +def needs( + minimum: Role, *, step: bool = False, refusal: str | None = None +) -> Callable[[Callable[_P, Awaitable[None]]], Callable[_P, Awaitable[None]]]: + """The role a handler demands, checked before its body runs. + + The one role check of «⚙️ Класс». The rule is :func:`_allowed` - the class + is known and the member's role is at least ``minimum`` - and it used to be + written out at the top of seventy-two handlers, each copy with its own + refusal after it. A handler now says what it demands where it is + registered:: + + @router.callback_query(SubjectAction.filter(F.action == "open")) + @needs(Role.ADMIN) + async def subject_open(...): ... + + A refusal has three shapes, decided here, and each is what the handlers + did by hand: + + * a press is answered with the refusal in an alert - one left unanswered + keeps its spinner until Telegram gives up; + * a command is answered with the refusal as a message - whoever typed + «/bells» is owed a sentence saying why not; + * a ``step`` of a form drops the form. FSM state is per-user and therefore + attacker-controlled - a client can put itself into any step and send a + message - so a step that trusted the step before it would be a write + with no check at all. Text typed into a form nobody had the right to + open is answered with nothing; a press on one is still answered. + + The sentence is :func:`_refusal`'s unless ``refusal`` names one: a screen + that has always said «Только для администраторов» to everybody keeps + saying it. + + **A decorator, and not an aiogram filter or a flag a middleware reads**, + because the check has to travel with the function. A filter that fails + does not refuse: aiogram offers the update to the next handler and in the + end to ``unknown``, so a refused press would be answered by whatever else + matched, or not at all. A flag is read only on the way in through the + dispatcher, and every handler here is also called directly - by the tests + that press each step as a наблюдатель and demand a refusal, which are the + only proof the check exists at all. Wrapped, a handler cannot be reached + without its check, whichever way it is called. aiogram reads the arguments + it injects off the unwrapped function (``inspect.unwrap``), so the handler + still receives exactly what it declares, and ``functools.wraps`` keeps the + name the handler-order tests compare. + + The handler must take its event first, as ``callback`` or ``message``, and + declare ``school_class`` and ``role`` - and ``state``, for a step. Anything + else is a ``TypeError`` at import: a gate that cannot see the role is not + one. + """ + + def decorate(handler: Callable[_P, Awaitable[None]]) -> Callable[_P, Awaitable[None]]: + signature = inspect.signature(handler) + names = list(signature.parameters) + event = names[0] if names else "" + wanted = {"school_class", "role"} | ({"state"} if step else set()) + if event not in {"callback", "message"} or not wanted <= set(names): + raise TypeError( + f"{handler.__qualname__} cannot be gated: it must take `callback` or " + f"`message` first and declare {sorted(wanted)}" + ) + + @functools.wraps(handler) + async def gated(*args: _P.args, **kwargs: _P.kwargs) -> None: + arguments = signature.bind_partial(*args, **kwargs).arguments + role = arguments.get("role") + if _allowed(arguments.get("school_class"), role, minimum): + await handler(*args, **kwargs) + return + if step: + await arguments["state"].clear() + text = refusal or _refusal(role, minimum) + if event == "callback": + await arguments["callback"].answer(text, show_alert=True) + elif not step: + await arguments["message"].answer(text) + + return gated + + return decorate + + def _int_or_none(raw: str) -> int | None: """An id out of callback data, or ``None`` for anything a crafted one carries.""" try: diff --git a/server/app/bot/handlers/manage/audit_log.py b/server/app/bot/handlers/manage/audit_log.py index 87363fcb..b425070d 100644 --- a/server/app/bot/handlers/manage/audit_log.py +++ b/server/app/bot/handlers/manage/audit_log.py @@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal +from app.bot.handlers.manage._common import _int_or_none, _member_names, needs from app.bot.manage_keyboards import AuditAction, audit_keyboard from app.models import Role, SchoolClass from app.services.manage import journal as journal_service @@ -38,34 +38,29 @@ async def _audit_view(session: AsyncSession, school_class: SchoolClass, offset: @router.message(Command("log")) +@needs(Role.ADMIN) async def cmd_log( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.clear() text, keyboard = await _audit_view(session, school_class, 0) await message.answer(text, reply_markup=keyboard) @router.callback_query(AuditAction.filter(F.action == "page")) +@needs(Role.ADMIN) async def audit_page( callback: CallbackQuery, callback_data: AuditAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - offset = _int_or_none(callback_data.value) or 0 # A negative offset is not a page; SQL would take it as "no offset" and # quietly show page one under a heading that says otherwise. diff --git a/server/app/bot/handlers/manage/bells.py b/server/app/bot/handlers/manage/bells.py index a4da8544..2e48365d 100644 --- a/server/app/bot/handlers/manage/bells.py +++ b/server/app/bot/handlers/manage/bells.py @@ -16,7 +16,7 @@ from app.bot import manage_render as mr from app.bot import render -from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.handlers.manage._common import _int_or_none, needs from app.bot.handlers.timetable import REJECTED_MAX from app.bot.keyboards import back_to_menu, cancel_keyboard from app.bot.manage_keyboards import BellsAction, bells_list_keyboard @@ -75,32 +75,28 @@ async def _bells_view(session: AsyncSession, school_class: SchoolClass): @router.message(Command("bells")) +@needs(Role.ADMIN) async def cmd_bells( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.clear() text, keyboard = await _bells_view(session, school_class) await message.answer(text, reply_markup=keyboard) @router.callback_query(BellsAction.filter(F.action == "list")) +@needs(Role.ADMIN) async def bells_list( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.clear() text, keyboard = await _bells_view(session, school_class) await callback.message.edit_text(text, reply_markup=keyboard) @@ -108,18 +104,15 @@ async def bells_list( @router.callback_query(BellsAction.filter(F.action == "edit")) +@needs(Role.ADMIN) async def bells_edit( callback: CallbackQuery, callback_data: BellsAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - schedule = await _schedule_by_id(session, school_class, callback_data.value) if schedule is None: await callback.answer("Расписание не найдено", show_alert=True) @@ -136,17 +129,14 @@ async def bells_edit( @router.message(EditBellRows.rows) +@needs(Role.ADMIN, step=True) async def bells_rows_apply( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - data = await state.get_data() schedule = await _schedule_by_id(session, school_class, str(data.get("schedule_id", ""))) if schedule is None: @@ -191,15 +181,13 @@ async def bells_rows_apply( @router.callback_query(BellsAction.filter(F.action == "create")) +@needs(Role.ADMIN) async def bells_create( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.set_state(NewBellSchedule.name) await callback.message.edit_text( "Название нового расписания звонков, например <code>Сокращённое</code>:", @@ -209,16 +197,13 @@ async def bells_create( @router.message(NewBellSchedule.name) +@needs(Role.ADMIN, step=True) async def bells_new_name( message: Message, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - name = " ".join((message.text or "").split()) if not 1 <= len(name) <= 64: await message.answer("Название от 1 до 64 символов. Ещё раз:") @@ -232,17 +217,14 @@ async def bells_new_name( @router.message(NewBellSchedule.rows) +@needs(Role.ADMIN, step=True) async def bells_new_rows( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - data = await state.get_data() name = str(data.get("name", "")).strip() if not name: @@ -289,17 +271,14 @@ async def bells_new_rows( @router.callback_query(BellsAction.filter(F.action == "default")) +@needs(Role.ADMIN) async def bells_make_default( callback: CallbackQuery, callback_data: BellsAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - schedule = await _schedule_by_id(session, school_class, callback_data.value) if schedule is None: await callback.answer("Расписание не найдено", show_alert=True) @@ -338,12 +317,13 @@ async def bells_make_default( @router.callback_query(BellsAction.filter(F.action == "delete")) +@needs(Role.ADMIN) async def bells_delete( callback: CallbackQuery, callback_data: BellsAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Refused for the class default and for anything a day still points at. @@ -351,10 +331,6 @@ async def bells_delete( those days onto the default schedule — a change nobody asked for, on dates an admin is not looking at. """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - schedule = await _schedule_by_id(session, school_class, callback_data.value) if schedule is None: await callback.answer("Расписание не найдено", show_alert=True) diff --git a/server/app/bot/handlers/manage/calendar_feed.py b/server/app/bot/handlers/manage/calendar_feed.py index 659db94c..b0f8232f 100644 --- a/server/app/bot/handlers/manage/calendar_feed.py +++ b/server/app/bot/handlers/manage/calendar_feed.py @@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _refusal +from app.bot.handlers.manage._common import needs from app.bot.keyboards import back_to_menu from app.bot.manage_keyboards import ManageAction, back_to from app.config import get_settings @@ -56,18 +56,16 @@ def _calendar_keyboard(role: Role): @router.message(Command("calendar")) +@needs(Role.VIEWER) async def cmd_calendar( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Any member may subscribe: the feed is read-only and its secret is not the join code, so a calendar URL cannot be turned into write access.""" - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return await state.clear() await message.answer( await _calendar_text(session, school_class, rotated=False), @@ -76,15 +74,13 @@ async def cmd_calendar( @router.callback_query(ManageAction.filter(F.action == "calendar")) +@needs(Role.VIEWER) async def calendar_card( callback: CallbackQuery, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await callback.answer(NO_ACCESS, show_alert=True) - return await callback.message.edit_text( await _calendar_text(session, school_class, rotated=False), reply_markup=_calendar_keyboard(role), @@ -93,17 +89,14 @@ async def calendar_card( @router.callback_query(ManageAction.filter(F.action == "rotate_feed")) +@needs(Role.ADMIN) async def calendar_rotate( callback: CallbackQuery, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Every existing subscription stops updating — that is the point.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - text = await _calendar_text(session, school_class, rotated=True) await audit.record( session, school_class.id, callback.from_user.id, "calendar.rotate", diff --git a/server/app/bot/handlers/manage/class_card.py b/server/app/bot/handlers/manage/class_card.py index 65e94a10..548d4d8a 100644 --- a/server/app/bot/handlers/manage/class_card.py +++ b/server/app/bot/handlers/manage/class_card.py @@ -17,10 +17,8 @@ from app.bot import manage_render as mr from app.bot.handlers.manage._common import ( NEED_OWNER, - NO_ACCESS, - _allowed, _int_or_none, - _refusal, + needs, ) from app.bot.keyboards import Menu, back_to_menu, cancel_keyboard from app.bot.manage_keyboards import ManageAction, class_menu, switch_keyboard @@ -89,16 +87,14 @@ def _diary_label(school_class: SchoolClass) -> str: @router.message(Command("class")) +@needs(Role.ADMIN) async def cmd_class( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.clear() text, keyboard = await _class_card(session, school_class, role, message.from_user.id) await message.answer(text, reply_markup=keyboard) @@ -109,16 +105,14 @@ async def cmd_class( # were on whichever card you had not opened. @router.callback_query(Menu.filter(F.action == "class")) @router.callback_query(ManageAction.filter(F.action == "root")) +@needs(Role.ADMIN) async def class_root( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.clear() text, keyboard = await _class_card(session, school_class, role, callback.from_user.id) await callback.message.edit_text(text, reply_markup=keyboard) @@ -135,17 +129,14 @@ async def class_root( @router.callback_query(ManageAction.filter(F.action.in_({"rename", "school", "city"}))) +@needs(Role.ADMIN) async def class_field_prompt( callback: CallbackQuery, callback_data: ManageAction, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - target = _CLASS_FIELDS.get(callback_data.action) if target is None: # pragma: no cover - the filter already narrowed it await callback.answer("Неизвестное поле", show_alert=True) @@ -159,17 +150,14 @@ async def class_field_prompt( @router.message(EditClassField.value) +@needs(Role.ADMIN, step=True) async def class_field_apply( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - data = await state.get_data() target = _CLASS_FIELDS.get(str(data.get("field", ""))) if target is None: @@ -203,22 +191,16 @@ async def class_field_apply( @router.callback_query(ManageAction.filter(F.action == "switch")) +@needs(Role.VIEWER) async def class_switch( callback: CallbackQuery, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await callback.answer(NO_ACCESS, show_alert=True) - return - - memberships = await list_memberships(session, callback.from_user.id) - classes: list[SchoolClass] = [] - for member in memberships: - found = await session.get(SchoolClass, member.class_id) - if found is not None: - classes.append(found) + classes = await classes_service.classes_of( + session, await list_memberships(session, callback.from_user.id) + ) if len(classes) < 2: await callback.answer("Вы состоите только в одном классе", show_alert=True) return @@ -231,13 +213,14 @@ async def class_switch( @router.callback_query(ManageAction.filter(F.action == "switch_to")) +@needs(Role.VIEWER) async def class_switch_to( callback: CallbackQuery, callback_data: ManageAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Remember which class this person is working in. @@ -249,17 +232,13 @@ async def class_switch_to( time it reads the preference, so a class somebody is later removed from stops being their default by itself. """ - if school_class is None or role is None: - await callback.answer(NO_ACCESS, show_alert=True) - return - class_id = _int_or_none(callback_data.value) memberships = await list_memberships(session, callback.from_user.id) if class_id is None or not any(member.class_id == class_id for member in memberships): await callback.answer("Вы не состоите в этом классе", show_alert=True) return - target = await session.get(SchoolClass, class_id) + target = await classes_service.class_of(session, class_id) if target is None: await callback.answer("Класс не найден", show_alert=True) return @@ -282,16 +261,13 @@ async def class_switch_to( @router.callback_query(ManageAction.filter(F.action == "delete")) +@needs(Role.OWNER, refusal=NEED_OWNER) async def class_delete_prompt( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.OWNER): - await callback.answer(NEED_OWNER, show_alert=True) - return - await state.set_state(DeleteClass.confirm) await callback.message.edit_text( f"🗑 <b>Удалить класс {escape(school_class.name)}?</b>\n\n" @@ -305,12 +281,13 @@ async def class_delete_prompt( @router.message(DeleteClass.confirm) +@needs(Role.OWNER, step=True) async def class_delete_apply( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Typing the name back is the confirmation, and the only one. @@ -318,10 +295,6 @@ async def class_delete_apply( before it. Nothing here writes an audit line: the log lives in the class and goes with it. """ - if not _allowed(school_class, role, Role.OWNER): - await state.clear() - return - name = school_class.name try: await classes_service.delete(session, school_class, message.text or "") diff --git a/server/app/bot/handlers/manage/devices.py b/server/app/bot/handlers/manage/devices.py index ceb0b582..d0a33c5e 100644 --- a/server/app/bot/handlers/manage/devices.py +++ b/server/app/bot/handlers/manage/devices.py @@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import _allowed, _int_or_none, _member_names, _refusal +from app.bot.handlers.manage._common import _int_or_none, _member_names, needs from app.bot.manage_keyboards import DeviceAction, device_keyboard from app.models import DeviceToken, Role, SchoolClass from app.services import linking @@ -55,32 +55,28 @@ async def _device_by_id( @router.message(Command("devices")) +@needs(Role.ADMIN) async def cmd_devices( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.clear() text, keyboard = await _device_view(session, school_class) await message.answer(text, reply_markup=keyboard) @router.callback_query(DeviceAction.filter(F.action == "list")) +@needs(Role.ADMIN) async def devices_list( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.clear() text, keyboard = await _device_view(session, school_class) await callback.message.edit_text(text, reply_markup=keyboard) @@ -88,19 +84,16 @@ async def devices_list( @router.callback_query(DeviceAction.filter(F.action == "revoke")) +@needs(Role.ADMIN) async def device_revoke( callback: CallbackQuery, callback_data: DeviceAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Revoked, not deleted: the row is what the API checks a token against, and keeping it is what makes the refusal instant and permanent.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - device = await _device_by_id(session, school_class, callback_data.value) if device is None: await callback.answer("Устройство не найдено", show_alert=True) @@ -117,18 +110,15 @@ async def device_revoke( @router.callback_query(DeviceAction.filter(F.action == "unlink")) +@needs(Role.ADMIN) async def device_unlink( callback: CallbackQuery, callback_data: DeviceAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Back to read-only without taking the phone off the class.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - device = await _device_by_id(session, school_class, callback_data.value) if device is None: await callback.answer("Устройство не найдено", show_alert=True) diff --git a/server/app/bot/handlers/manage/diary_binding.py b/server/app/bot/handlers/manage/diary_binding.py index 960dfda7..54c2057d 100644 --- a/server/app/bot/handlers/manage/diary_binding.py +++ b/server/app/bot/handlers/manage/diary_binding.py @@ -13,7 +13,7 @@ from aiogram.types import CallbackQuery, Message from sqlalchemy.ext.asyncio import AsyncSession -from app.bot.handlers.manage._common import _allowed +from app.bot.handlers.manage._common import NEED_ADMIN, needs from app.bot.handlers.manage.class_card import _class_card from app.bot.keyboards import DiarySchoolPick from app.bot.manage_keyboards import ( @@ -31,16 +31,18 @@ from app.providers.netschool.client import NetSchoolClient from app.services import audit, diary_link from app.services import diary as diary_service +from app.services.manage import classes as classes_service router = Router(name="manage.diary_binding") @router.callback_query(ManageAction.filter(F.action == "diary_bind")) +@needs(Role.ADMIN, refusal=NEED_ADMIN) async def class_diary_bind( callback: CallbackQuery, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Bind or unbind the class's electronic diary. @@ -49,10 +51,6 @@ async def class_diary_bind( account. Unbinding likewise only removes the door — the sessions people opened stay theirs until they sign out, and are dropped with the class. """ - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return - if school_class.diary_provider: # Bound → unbind. The door goes; the sessions people opened stay theirs # until they sign out or the class is deleted, as three screens promise. @@ -86,17 +84,15 @@ async def class_diary_bind( @router.callback_query(ManageAction.filter(F.action == "diary_prov")) +@needs(Role.ADMIN, refusal=NEED_ADMIN) async def class_diary_provider( callback: CallbackQuery, callback_data: ManageAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Second step of binding: the provider was picked.""" - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return if callback_data.value == PETERSBURG: school_class.diary_provider = PETERSBURG school_class.diary_region = None @@ -126,20 +122,18 @@ async def class_diary_provider( @router.callback_query(ManageAction.filter(F.action == "diary_reg")) +@needs(Role.ADMIN, refusal=NEED_ADMIN) async def class_diary_region( callback: CallbackQuery, callback_data: ManageAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, state: FSMContext, ) -> None: """Third step: the «Сетевой город» region was picked. Check the region accepts a password from us before asking for the school, so the admin learns once rather than every family finding out at sign-in.""" - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await callback.answer("Только для администраторов", show_alert=True) - return region = ns_regions.get(callback_data.value) if region is None or not region.password: await callback.answer("Этот регион недоступен", show_alert=True) @@ -172,12 +166,13 @@ async def _probe_region(region) -> tuple[bool, str]: # noqa: ANN001 @router.message(BindDiary.school) +@needs(Role.ADMIN, step=True) async def class_diary_search( message: Message, session: AsyncSession, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Fourth step: a school-name query. Show what the region's search found. @@ -186,9 +181,6 @@ async def class_diary_search( otherwise turn the class card into an outbound search against a region server. """ - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return data = await state.get_data() region = ns_regions.get(data.get("diary_region")) class_id = data.get("diary_class_id") @@ -216,21 +208,18 @@ async def class_diary_search( await message.answer(caption, reply_markup=diary_school_menu(shown, more=more)) +# A role check like every other step: the callback payload is whatever the +# client sent, and this one redraws the (admin-only) class card, so a +# наблюдатель who pressed it would otherwise be shown it. @router.callback_query(DiarySchoolPick.filter(F.action == "cancel")) +@needs(Role.ADMIN, step=True, refusal=NEED_ADMIN) async def class_diary_cancel( callback: CallbackQuery, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, state: FSMContext, ) -> None: - # A role check like every other step: the callback payload is whatever the - # client sent, and this one redraws the (admin-only) class card, so a - # наблюдатель who pressed it would otherwise be shown it. - if school_class is None or role is None or not role.at_least(Role.ADMIN): - await state.clear() - await callback.answer("Только для администраторов", show_alert=True) - return await state.clear() await _redraw_class(callback, session, school_class, role) await callback.answer("Отменено") @@ -254,7 +243,11 @@ async def class_diary_school( await state.clear() await callback.answer("Список устарел — начните заново.", show_alert=True) return - school_class = await session.get(SchoolClass, class_id) + # Not `@needs`: the class this binds is the one the form started in, + # carried in the state, and it is that class which has to exist. The role + # is the member's in the class they are in now, as for every other step - + # switching class drops the form, so the two are the same class. + school_class = await classes_service.class_of(session, class_id) if school_class is None or role is None or not role.at_least(Role.ADMIN): await state.clear() await callback.answer("Только для администраторов", show_alert=True) diff --git a/server/app/bot/handlers/manage/holidays.py b/server/app/bot/handlers/manage/holidays.py index 7fea1eb9..d561c4af 100644 --- a/server/app/bot/handlers/manage/holidays.py +++ b/server/app/bot/handlers/manage/holidays.py @@ -7,26 +7,23 @@ from __future__ import annotations from datetime import date as Date -from datetime import timedelta from html import escape from aiogram import F, Router from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr from app.bot.handlers.calendar import open_month from app.bot.handlers.manage._common import ( - _allowed, _date_or_none, _day_kind_or_none, _int_or_none, _parse_day, - _refusal, _today, + needs, ) from app.bot.keyboards import back_to_menu, cancel_keyboard from app.bot.manage_keyboards import ( @@ -38,8 +35,10 @@ period_kind_keyboard, ) from app.bot.manage_states import AddHoliday -from app.models import BellPeriod, BellSchedule, DayKind, DayOverride, Role, SchoolClass +from app.models import DayKind, Role, SchoolClass from app.services import audit +from app.services.manage import bells as bells_service +from app.services.manage import special_days router = Router(name="manage.holidays") @@ -103,20 +102,8 @@ async def _holiday_view( Carried in the payload, the card *is* its own filter. """ today = _today(school_class) - query = ( - select(DayOverride) - .where(DayOverride.class_id == school_class.id, DayOverride.date >= today) - .order_by(DayOverride.date) - ) - if only is not None: - query = query.where(DayOverride.kind == only) - overrides = list(await session.scalars(query)) - schedules = { - schedule.id: schedule.name - for schedule in await session.scalars( - select(BellSchedule).where(BellSchedule.class_id == school_class.id) - ) - } + overrides = await special_days.upcoming(session, school_class.id, today, only) + schedules = await special_days.schedule_names(session, school_class.id) return mr.render_holidays(overrides, schedules, today, only), holiday_list_keyboard( overrides, only=only, @@ -125,67 +112,30 @@ async def _holiday_view( ) -async def _override_for( - session: AsyncSession, class_id: int, day: Date -) -> DayOverride | None: - return await session.scalar( - select(DayOverride).where(DayOverride.class_id == class_id, DayOverride.date == day) - ) - - -async def _upsert_override( - session: AsyncSession, school_class: SchoolClass, day: Date, kind: DayKind -) -> DayOverride: - override = await _override_for(session, school_class.id, day) - if override is None: - override = DayOverride(class_id=school_class.id, date=day, kind=kind) - session.add(override) - override.kind = kind - if kind is not DayKind.SHORTENED: - # A bell schedule only means anything on a shortened day; leaving a - # stale one on a holiday would surface in the day view as a - # schedule nobody chose. - override.bell_schedule_id = None - elif override.bell_schedule_id is None: - # Never null on a shortened day. The picker opens next and is where - # the real answer comes from, but the row is committed before it is - # asked — so walking away used to leave «⏱ Сокращённые уроки» over a - # day that names no schedule, which `api/edit.day_put` refuses with a - # 422 and the resolver silently draws as a normal day. The class - # default is the honest starting value: it is what the day would ring - # anyway, and now it says so on the card. - override.bell_schedule_id = school_class.bell_schedule_id - return override - - @router.message(Command("holidays")) +@needs(Role.EDITOR) async def cmd_holidays( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return await state.clear() text, keyboard = await _holiday_view(session, school_class, role) await message.answer(text, reply_markup=keyboard) @router.callback_query(DayKindAction.filter(F.action == "list")) +@needs(Role.EDITOR) async def holidays_list( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return await state.clear() # An unreadable filter narrows to nothing rather than raising: the value is # whatever the client sent, and `DayKind(raw)` out of a callback handler @@ -197,16 +147,13 @@ async def holidays_list( @router.callback_query(DayKindAction.filter(F.action == "add")) +@needs(Role.EDITOR) async def holiday_add( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - await state.set_state(AddHoliday.date) await callback.message.edit_text( f"🏖 <b>Особый день</b>\n\n{HOLIDAY_DATE_HELP}", @@ -223,17 +170,14 @@ async def _ask_kind(editable, day: Date) -> None: @router.callback_query(DayKindAction.filter(F.action == "pick_date")) +@needs(Role.EDITOR) async def holiday_pick_date( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - day = _date_or_none(callback_data.value) if day is None: await callback.answer("Непонятная дата", show_alert=True) @@ -247,16 +191,13 @@ async def holiday_pick_date( @router.message(AddHoliday.date) +@needs(Role.EDITOR, step=True) async def holiday_typed_date( message: Message, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await state.clear() - return - day = _parse_day(message.text or "", _today(school_class)) if day is None: await message.answer(f"Не понял дату. {HOLIDAY_DATE_HELP}") @@ -270,18 +211,15 @@ async def holiday_typed_date( @router.callback_query(DayKindAction.filter(F.action == "kind")) +@needs(Role.EDITOR) async def holiday_kind( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - raw_date, _, tag = callback_data.value.partition(":") day = _date_or_none(raw_date) if day is None: @@ -289,7 +227,7 @@ async def holiday_kind( return if tag == "normal": - override = await _override_for(session, school_class.id, day) + override = await special_days.mark_on(session, school_class.id, day) if override is not None: await session.delete(override) await audit.record( @@ -308,7 +246,7 @@ async def holiday_kind( await callback.answer("Неизвестный тип дня", show_alert=True) return - await _upsert_override(session, school_class, day, kind) + await special_days.mark(session, school_class, day, kind) await audit.record( session, school_class.id, callback.from_user.id, "dayoverride.set", f"{day:%d.%m}: {_KIND_SUMMARY[kind]}", @@ -316,13 +254,7 @@ async def holiday_kind( await session.commit() if kind is DayKind.SHORTENED: - schedules = list( - await session.scalars( - select(BellSchedule) - .where(BellSchedule.class_id == school_class.id) - .order_by(BellSchedule.id) - ) - ) + schedules = await bells_service.schedules_of(session, school_class.id) await state.clear() await callback.message.edit_text( f"<b>{day:%d.%m}</b> — сокращённые уроки.\n\nПо какому расписанию звонков?", @@ -347,36 +279,29 @@ async def _ask_note(editable, state: FSMContext, day: Date, kind: DayKind) -> No @router.callback_query(DayKindAction.filter(F.action == "bells")) +@needs(Role.EDITOR) async def holiday_bells( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - raw_date, _, raw_id = callback_data.value.partition(":") day = _date_or_none(raw_date) if day is None: await callback.answer("Непонятная дата", show_alert=True) return - override = await _override_for(session, school_class.id, day) + override = await special_days.mark_on(session, school_class.id, day) if override is None: await callback.answer("День уже не отмечен", show_alert=True) return schedule_id = _int_or_none(raw_id) if schedule_id: - schedule = await session.scalar( - select(BellSchedule).where( - BellSchedule.id == schedule_id, BellSchedule.class_id == school_class.id - ) - ) + schedule = await bells_service.schedule_of(session, school_class.id, schedule_id) if schedule is None: await callback.answer("Расписание звонков не найдено", show_alert=True) return @@ -387,10 +312,7 @@ async def holiday_bells( # уроки» over an empty day on every phone, in the widget and in the # calendar feed, and nothing would be logged. `api/edit.day_put` refuses # the same thing for the same reason. - rings = await session.scalar( - select(BellPeriod.id).where(BellPeriod.schedule_id == schedule.id).limit(1) - ) - if rings is None: + if not await bells_service.rings_anything(session, schedule): await callback.answer( f"В «{schedule.name}» ещё нет ни одного урока — " "заполните звонки, иначе день будет пустым.", @@ -418,17 +340,14 @@ async def holiday_bells( @router.message(AddHoliday.note) +@needs(Role.EDITOR, step=True) async def holiday_note( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await state.clear() - return - data = await state.get_data() day = _date_or_none(str(data.get("date", ""))) if day is None: @@ -436,7 +355,7 @@ async def holiday_note( await message.answer("Начните заново: /holidays", reply_markup=back_to_menu()) return - override = await _override_for(session, school_class.id, day) + override = await special_days.mark_on(session, school_class.id, day) if override is None: await state.clear() await message.answer("День уже не отмечен.", reply_markup=back_to_menu()) @@ -457,24 +376,21 @@ async def holiday_note( @router.callback_query(DayKindAction.filter(F.action == "delete")) +@needs(Role.EDITOR) async def holiday_delete( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - day = _date_or_none(callback_data.value) if day is None: await callback.answer("Непонятная дата", show_alert=True) return - override = await _override_for(session, school_class.id, day) + override = await special_days.mark_on(session, school_class.id, day) if override is not None: await session.delete(override) await audit.record( @@ -490,18 +406,15 @@ async def holiday_delete( @router.callback_query(DayKindAction.filter(F.action == "period")) +@needs(Role.ADMIN) async def holiday_period_start( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """A whole range of holiday days is admin-only: it rewrites weeks of the class's calendar from one message.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - # Which kind first, dates second. The flow used to mark holidays and # nothing else, so «самоподготовка с 12 по 16» meant marking five days one # at a time — and a week of remote teaching, which is the shape this is @@ -516,19 +429,16 @@ async def holiday_period_start( @router.callback_query(DayKindAction.filter(F.action == "period_kind")) +@needs(Role.ADMIN) async def holiday_period_kind( callback: CallbackQuery, callback_data: DayKindAction, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """The kind is picked, now the dates. Re-checked here, not trusted from the press that got this far: a card can sit on a screen after a role changes.""" - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - kind = _day_kind_or_none(callback_data.value) if kind is None or kind not in {chosen for chosen, _ in PERIOD_KINDS}: # Not an exception. Callback data is whatever the client sent, and a @@ -551,17 +461,14 @@ async def holiday_period_kind( @router.message(AddHoliday.period) +@needs(Role.ADMIN, step=True) async def holiday_period_apply( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - today = _today(school_class) raw = (message.text or "").replace("—", "-").replace("–", "-") parts = [part for part in raw.split("-") if part.strip()] @@ -587,8 +494,7 @@ async def holiday_period_apply( data = await state.get_data() kind = _day_kind_or_none(str(data.get("period_kind", ""))) or DayKind.HOLIDAY - for offset in range(span): - await _upsert_override(session, school_class, first + timedelta(days=offset), kind) + await special_days.mark_period(session, school_class, first, span, kind) await audit.record( session, school_class.id, diff --git a/server/app/bot/handlers/manage/import_export.py b/server/app/bot/handlers/manage/import_export.py index 2855b315..60e85879 100644 --- a/server/app/bot/handlers/manage/import_export.py +++ b/server/app/bot/handlers/manage/import_export.py @@ -15,7 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import _allowed, _refusal +from app.bot.handlers.manage._common import needs from app.bot.keyboards import WEEKDAY_FULL, back_to_menu, cancel_keyboard from app.bot.manage_keyboards import ImportAction, import_keyboard from app.bot.manage_states import ImportTimetable @@ -52,21 +52,19 @@ @router.message(Command("export")) +@needs(Role.ADMIN) async def cmd_export( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """The whole template as text — which doubles as the backup. It is sent in ``<code>`` blocks so Telegram offers a copy button, split at 4000 characters because the limit is 4096 and the header counts. """ - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.clear() body, _lessons = await timetable_service.export(session, school_class) @@ -96,35 +94,30 @@ async def cmd_export( @router.message(Command("import")) +@needs(Role.ADMIN) async def cmd_import( message: Message, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await message.answer(_refusal(role, Role.ADMIN)) - return await state.set_state(ImportTimetable.paste) await message.answer(f"📥 <b>Импорт расписания</b>\n\n{IMPORT_HELP}") @router.message(ImportTimetable.paste) +@needs(Role.ADMIN, step=True) async def import_preview( message: Message, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Parse and show what would happen; nothing is written yet. The paste is kept in FSM storage rather than parsed twice into a process variable: «Применить» may well arrive at a different instance. """ - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - raw = message.text or "" days, rejected = timetable_io.parse_timetable_block(raw) bells, _ = timetable_io.parse_bells_block(raw) @@ -140,27 +133,26 @@ async def import_preview( @router.callback_query(ImportAction.filter(F.action == "cancel")) +@needs(Role.ADMIN) async def import_cancel( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.clear() await callback.message.edit_text("Импорт отменён — ничего не изменилось.") await callback.answer() @router.callback_query(ImportAction.filter(F.action == "apply")) +@needs(Role.ADMIN) async def import_apply( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Replace exactly the weekdays the paste named, in one transaction. @@ -168,10 +160,6 @@ async def import_apply( block is a legitimate thing to do. A day that appears with no lessons under it is emptied — that is how a paste says «в четверг уроков нет». """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - data = await state.get_data() raw = str(data.get("raw", "")) days, _ = timetable_io.parse_timetable_block(raw) diff --git a/server/app/bot/handlers/manage/requests.py b/server/app/bot/handlers/manage/requests.py index 950d2865..a8281ca8 100644 --- a/server/app/bot/handlers/manage/requests.py +++ b/server/app/bot/handlers/manage/requests.py @@ -13,15 +13,18 @@ from aiogram.filters import Command, CommandObject from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _bot_of, _int_or_none, _refusal +from app.bot.handlers.manage._common import ( + _bot_of, + _int_or_none, + needs, +) from app.bot.keyboards import back_to_menu, cancel_keyboard from app.bot.manage_keyboards import RequestAction, request_keyboard from app.bot.manage_states import RequestAccess -from app.models import AccessRequest, BotUser, Role, SchoolClass +from app.models import AccessRequest, Role, SchoolClass from app.services import access as access_service from app.services import audit, linking from app.services.manage import requests as requests_service @@ -37,22 +40,19 @@ @router.message(Command("link")) +@needs(Role.VIEWER) async def cmd_link( message: Message, command: CommandObject, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Attach the phone showing ``code`` to this account. No role check beyond membership: linking gives the phone *this* account's role, whatever it is, so it can never be more than the person already has. """ - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - code = (command.args or "").strip() if not 1 <= len(code) <= 16: await message.answer( @@ -91,35 +91,6 @@ async def cmd_link( await message.answer(f"📱 Устройство «{name}» привязано. {tail}") -async def _create_request( - session: AsyncSession, school_class: SchoolClass, telegram_id: int, text: str | None -) -> AccessRequest: - """One open request per person per class — a second one replaces the first, - so a nervous requester cannot fill an admin's screen.""" - existing = await session.scalar( - select(AccessRequest).where( - AccessRequest.class_id == school_class.id, - AccessRequest.telegram_id == telegram_id, - AccessRequest.status == "pending", - ) - ) - if existing is None: - existing = AccessRequest( - class_id=school_class.id, - telegram_id=telegram_id, - requested_role=Role.EDITOR, - status="pending", - ) - session.add(existing) - existing.requested_role = Role.EDITOR - existing.status = "pending" - existing.message = (text or None) and text[:300] - existing.decided_by = None - existing.decided_at = None - await session.flush() - return existing - - async def _notify_admins( session: AsyncSession, bot, @@ -131,12 +102,7 @@ async def _notify_admins( if bot is None: return - admins = await session.scalars( - select(BotUser).where( - BotUser.class_id == school_class.id, - BotUser.role.in_([Role.ADMIN, Role.OWNER]), - ) - ) + admins = await requests_service.admins(session, school_class.id) body = ( f"🙋 <b>Запрос доступа</b>\n\n" f"{who} просит роль <b>{Role.EDITOR.title_ru}</b> " @@ -155,17 +121,15 @@ async def _notify_admins( @router.message(Command("request")) +@needs(Role.VIEWER) async def cmd_request( message: Message, command: CommandObject, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return if role.at_least(Role.EDITOR): await message.answer( f"У вас уже роль <b>{role.title_ru}</b> — запрашивать нечего." @@ -187,14 +151,15 @@ async def cmd_request( @router.message(RequestAccess.message) +@needs(Role.VIEWER, step=True) async def request_message( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.VIEWER) or role.at_least(Role.EDITOR): + if role.at_least(Role.EDITOR): await state.clear() return raw = " ".join((message.text or "").split()) @@ -210,7 +175,9 @@ async def _submit_request( school_class: SchoolClass, text: str | None, ) -> None: - request = await _create_request(session, school_class, message.from_user.id, text) + request = await requests_service.submit( + session, school_class.id, message.from_user.id, text + ) who = mr.person(message.from_user.full_name, message.from_user.username, message.from_user.id) await audit.record( session, @@ -247,12 +214,13 @@ async def _request_by_id( @router.callback_query(RequestAction.filter(F.action == "approve")) +@needs(Role.ADMIN) async def request_approve( callback: CallbackQuery, callback_data: RequestAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Grant the requested role through the same rules as «👥 Доступ». @@ -261,10 +229,6 @@ async def request_approve( button cannot come to different answers. The refusal it raises carries the Russian sentence this alert shows. """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - request = await _request_by_id(session, school_class, callback_data.value) if request is None: await callback.answer("Запрос уже закрыт", show_alert=True) @@ -299,17 +263,14 @@ async def request_approve( @router.callback_query(RequestAction.filter(F.action == "decline")) +@needs(Role.ADMIN) async def request_decline( callback: CallbackQuery, callback_data: RequestAction, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - request = await _request_by_id(session, school_class, callback_data.value) if request is None: await callback.answer("Запрос уже закрыт", show_alert=True) diff --git a/server/app/bot/handlers/manage/stats.py b/server/app/bot/handlers/manage/stats.py index 1dd3691d..bac8ee83 100644 --- a/server/app/bot/handlers/manage/stats.py +++ b/server/app/bot/handlers/manage/stats.py @@ -12,14 +12,14 @@ from aiogram.filters import Command, CommandObject from aiogram.fsm.context import FSMContext from aiogram.types import Message -from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import NO_ACCESS, _allowed, _refusal, _today +from app.bot.handlers.manage._common import _today, needs from app.bot.keyboards import back_to_menu -from app.models import Homework, Role, SchoolClass +from app.models import Role, SchoolClass from app.services import stats as stats_service +from app.services.manage import search router = Router(name="manage.stats") @@ -37,16 +37,14 @@ @router.message(Command("stats")) +@needs(Role.EDITOR) async def cmd_stats( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return await state.clear() numbers = await stats_service.class_stats(session, school_class) await message.answer( @@ -55,19 +53,16 @@ async def cmd_stats( @router.message(Command("find")) +@needs(Role.VIEWER) async def cmd_find( message: Message, command: CommandObject, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Search this class's homework. Any member may: it is the same text the day view already shows them, only reachable by memory instead of by date.""" - if not _allowed(school_class, role, Role.VIEWER): - await message.answer(NO_ACCESS) - return - needle = (command.args or "").strip() if len(needle) < 2: await message.answer( @@ -79,23 +74,11 @@ async def cmd_find( return today = _today(school_class) - # ``lower().contains()`` rather than ILIKE, which SQLite does not have. - # Both dialects fold Cyrillic: Postgres does it natively, and ``app.db`` - # replaces SQLite's ASCII-only ``lower()`` with Python's on every - # connection, so the search behaves the same for the developer and for the - # class. - pattern = needle.lower() - rows = list( - await session.scalars( - select(Homework) - .where( - Homework.class_id == school_class.id, - Homework.due_date >= today - timedelta(days=SEARCH_BACK_DAYS), - func.lower(Homework.text).contains(pattern) - | func.lower(Homework.subject_name).contains(pattern), - ) - .order_by(Homework.due_date.desc(), Homework.id.desc()) - .limit(SEARCH_MAX) - ) + rows = await search.homework( + session, + school_class.id, + needle, + since=today - timedelta(days=SEARCH_BACK_DAYS), + limit=SEARCH_MAX, ) await message.answer(mr.render_search(needle, rows, today), reply_markup=back_to_menu()) diff --git a/server/app/bot/handlers/manage/subjects.py b/server/app/bot/handlers/manage/subjects.py index 54b139e7..6f5be1c4 100644 --- a/server/app/bot/handlers/manage/subjects.py +++ b/server/app/bot/handlers/manage/subjects.py @@ -13,11 +13,10 @@ from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message -from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot import manage_render as mr -from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.handlers.manage._common import _int_or_none, needs from app.bot.keyboards import back_to_menu, cancel_keyboard from app.bot.manage_keyboards import ( COLOUR_PRESETS, @@ -28,8 +27,7 @@ ) from app.bot.manage_states import EditSubject from app.bot.render import plural -from app.models import Role, SchoolClass, Subject, TimetableEntry -from app.services import audit +from app.models import Role, SchoolClass, Subject from app.services.manage import subjects as subjects_service router = Router(name="manage.subjects") @@ -51,14 +49,6 @@ # old name, in the same transaction - see :func:`_rename_subject`. -async def _subjects_of(session: AsyncSession, class_id: int) -> list[Subject]: - return list( - await session.scalars( - select(Subject).where(Subject.class_id == class_id).order_by(Subject.name) - ) - ) - - async def _subject_view(session: AsyncSession, school_class: SchoolClass, role: Role): # «📚 Предметы» adopts the timetable's names on the way in, so the list # cannot be empty while the class has a full timetable. «Собрать из @@ -84,32 +74,28 @@ async def _subject_by_id( @router.message(Command("subjects")) +@needs(Role.EDITOR) async def cmd_subjects( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await message.answer(_refusal(role, Role.EDITOR)) - return await state.clear() text, keyboard = await _subject_view(session, school_class, role) await message.answer(text, reply_markup=keyboard) @router.callback_query(SubjectAction.filter(F.action == "list")) +@needs(Role.EDITOR) async def subjects_list( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return await state.clear() text, keyboard = await _subject_view(session, school_class, role) await callback.message.edit_text(text, reply_markup=keyboard) @@ -117,18 +103,15 @@ async def subjects_list( @router.callback_query(SubjectAction.filter(F.action == "open")) +@needs(Role.ADMIN) async def subject_open( callback: CallbackQuery, callback_data: SubjectAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - subject = await _subject_by_id(session, school_class, callback_data.value) if subject is None: await callback.answer("Предмет уже удалён", show_alert=True) @@ -154,18 +137,15 @@ async def subject_open( @router.callback_query(SubjectAction.filter(F.action == "field")) +@needs(Role.ADMIN) async def subject_field( callback: CallbackQuery, callback_data: SubjectAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - field, _, raw_id = callback_data.value.partition(":") subject = await _subject_by_id(session, school_class, raw_id) if subject is None: @@ -204,17 +184,14 @@ async def _subject_from_state( @router.message(EditSubject.name) +@needs(Role.ADMIN, step=True) async def subject_rename( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - name = " ".join((message.text or "").split()) if not 1 <= len(name) <= SUBJECT_NAME_MAX: await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") @@ -288,30 +265,26 @@ async def _save_subject_text( @router.message(EditSubject.short_name) +@needs(Role.ADMIN, step=True) async def subject_short_name( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return await _save_subject_text(message, state, session, school_class, "short_name", SHORT_NAME_MAX) @router.message(EditSubject.teacher) +@needs(Role.ADMIN, step=True) async def subject_teacher( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return await _save_subject_text(message, state, session, school_class, "teacher", TEACHER_MAX) @@ -329,18 +302,15 @@ async def _apply_colour( @router.callback_query(SubjectAction.filter(F.action == "colour")) +@needs(Role.ADMIN) async def subject_colour_pick( callback: CallbackQuery, callback_data: SubjectAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - raw_id, _, raw_colour = callback_data.value.partition(":") subject = await _subject_by_id(session, school_class, raw_id) if subject is None: @@ -365,17 +335,14 @@ async def subject_colour_pick( @router.message(EditSubject.colour) +@needs(Role.ADMIN, step=True) async def subject_colour_typed( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - raw = (message.text or "").strip() subject = await _subject_from_state(state, session, school_class) if subject is None: @@ -404,15 +371,13 @@ async def subject_colour_typed( @router.callback_query(SubjectAction.filter(F.action == "add")) +@needs(Role.ADMIN) async def subject_add( callback: CallbackQuery, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.set_state(EditSubject.create) await callback.message.edit_text( "Название нового предмета:", reply_markup=cancel_keyboard() @@ -421,17 +386,14 @@ async def subject_add( @router.message(EditSubject.create) +@needs(Role.ADMIN, step=True) async def subject_create( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - name = " ".join((message.text or "").split()) if not 1 <= len(name) <= SUBJECT_NAME_MAX: await message.answer(f"Название от 1 до {SUBJECT_NAME_MAX} символов. Ещё раз:") @@ -458,13 +420,14 @@ async def subject_create( @router.callback_query(SubjectAction.filter(F.action == "delete")) +@needs(Role.ADMIN) async def subject_delete( callback: CallbackQuery, callback_data: SubjectAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Deleting a subject the timetable still uses is refused. @@ -478,10 +441,6 @@ async def subject_delete( The order is now stated instead: out of the timetable first, out of the dictionary second. A subject nothing teaches still goes in one tap. """ - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - subject = await _subject_by_id(session, school_class, callback_data.value) if subject is None: await callback.answer("Предмет уже удалён", show_alert=True) @@ -510,47 +469,26 @@ async def subject_delete( @router.callback_query(SubjectAction.filter(F.action == "collect")) +@needs(Role.EDITOR) async def subjects_collect( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: """Create a Subject row for every name the timetable already uses. An editor may run this: it invents nothing, it only writes down the names that are already in the class's timetable. """ - if not _allowed(school_class, role, Role.EDITOR): - await callback.answer(_refusal(role, Role.EDITOR), show_alert=True) - return - - names = list( - await session.scalars( - select(TimetableEntry.subject_name) - .where(TimetableEntry.class_id == school_class.id) - .distinct() - ) - ) - known = {subject.name for subject in await _subjects_of(session, school_class.id)} - created = [name for name in sorted(names) if name and name not in known] - for name in created: - session.add(Subject(class_id=school_class.id, name=name[:SUBJECT_NAME_MAX])) - + created = await subjects_service.collect(session, school_class.id, callback.from_user.id) if created: - await audit.record( - session, - school_class.id, - callback.from_user.id, - "subject.collect", - f"собрано предметов из расписания: {len(created)}", - ) await session.commit() await state.clear() text, keyboard = await _subject_view(session, school_class, role) await callback.message.edit_text(text, reply_markup=keyboard) await callback.answer( - f"Добавлено: {len(created)}" if created else "Все предметы расписания уже в списке" + f"Добавлено: {created}" if created else "Все предметы расписания уже в списке" ) diff --git a/server/app/bot/handlers/manage/terms.py b/server/app/bot/handlers/manage/terms.py index 99317d2b..1c656282 100644 --- a/server/app/bot/handlers/manage/terms.py +++ b/server/app/bot/handlers/manage/terms.py @@ -14,7 +14,7 @@ from aiogram.types import CallbackQuery, Message from sqlalchemy.ext.asyncio import AsyncSession -from app.bot.handlers.manage._common import _allowed, _int_or_none, _refusal +from app.bot.handlers.manage._common import _int_or_none, needs from app.bot.keyboards import back_to_menu, cancel_keyboard from app.bot.manage_keyboards import TermAction, terms_menu from app.bot.manage_states import EditTerm @@ -66,16 +66,14 @@ async def _terms_card(session: AsyncSession, school_class: SchoolClass): @router.callback_query(TermAction.filter(F.action == "list")) +@needs(Role.ADMIN) async def terms_list( callback: CallbackQuery, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return await state.clear() text, keyboard = await _terms_card(session, school_class) await callback.message.edit_text(text, reply_markup=keyboard) @@ -83,18 +81,15 @@ async def terms_list( @router.callback_query(TermAction.filter(F.action == "scheme")) +@needs(Role.ADMIN) async def terms_scheme( callback: CallbackQuery, callback_data: TermAction, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - wanted = TermKind.SEMESTER if callback_data.value == "semester" else TermKind.QUARTER await terms_manage.change_scheme(session, school_class, callback.from_user.id, wanted) await session.commit() @@ -106,17 +101,14 @@ async def terms_scheme( @router.callback_query(TermAction.filter(F.action == "edit")) +@needs(Role.ADMIN) async def term_edit_prompt( callback: CallbackQuery, callback_data: TermAction, state: FSMContext, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await callback.answer(_refusal(role, Role.ADMIN), show_alert=True) - return - # ``_int_or_none``, not ``isdigit`` and ``int``: those two do not ask the # same question, so «²» passed the check and raised inside the conversion # — out of the handler, before ``callback.answer`` was ever reached. @@ -136,17 +128,14 @@ async def term_edit_prompt( @router.message(EditTerm.span) +@needs(Role.ADMIN, step=True) async def term_edit_apply( message: Message, state: FSMContext, session: AsyncSession, - school_class: SchoolClass | None, - role: Role | None, + school_class: SchoolClass, + role: Role, ) -> None: - if not _allowed(school_class, role, Role.ADMIN): - await state.clear() - return - data = await state.get_data() index = int(data.get("term_index", 0)) if index < 1: diff --git a/server/app/services/manage/bells.py b/server/app/services/manage/bells.py index 7a698c24..fa1b1f0c 100644 --- a/server/app/services/manage/bells.py +++ b/server/app/services/manage/bells.py @@ -12,7 +12,7 @@ from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from app.models import BellSchedule, DayOverride, SchoolClass +from app.models import BellPeriod, BellSchedule, DayOverride, SchoolClass from app.services import audit, structure from app.services.structure import BellRow @@ -64,6 +64,16 @@ async def schedule_of( ) +async def rings_anything(session: AsyncSession, schedule: BellSchedule) -> bool: + """Whether the schedule has one row at all - one row, not the count.""" + return ( + await session.scalar( + select(BellPeriod.id).where(BellPeriod.schedule_id == schedule.id).limit(1) + ) + is not None + ) + + async def rung_by_default(session: AsyncSession, school_class: SchoolClass) -> set[int]: """The lesson numbers the class rings today, before anything is changed. diff --git a/server/app/services/manage/classes.py b/server/app/services/manage/classes.py index 83bc0482..95695c43 100644 --- a/server/app/services/manage/classes.py +++ b/server/app/services/manage/classes.py @@ -66,6 +66,25 @@ async def counts(session: AsyncSession, class_id: int) -> Counts: ) +async def class_of(session: AsyncSession, class_id: int) -> SchoolClass | None: + """A class by id, for a screen that already knows the person is in it.""" + return await session.get(SchoolClass, class_id) + + +async def classes_of(session: AsyncSession, memberships: list[BotUser]) -> list[SchoolClass]: + """The classes behind a person's memberships, in the memberships' order. + + The order is the one «🔀 Сменить класс» draws its buttons in; a membership + whose class has gone is skipped rather than drawn as a dead button. + """ + found: list[SchoolClass] = [] + for member in memberships: + school_class = await session.get(SchoolClass, member.class_id) + if school_class is not None: + found.append(school_class) + return found + + async def members(session: AsyncSession, class_id: int) -> list[BotUser]: """Everybody with a role in the class, for a shell to put names to ids.""" return list(await session.scalars(select(BotUser).where(BotUser.class_id == class_id))) diff --git a/server/app/services/manage/requests.py b/server/app/services/manage/requests.py index 9ebfb410..53ecc832 100644 --- a/server/app/services/manage/requests.py +++ b/server/app/services/manage/requests.py @@ -2,7 +2,8 @@ Granting is :func:`app.services.access.approve_request`, which both shells already shared; this is the rest of what they wrote twice - finding a request -that is still open, and saying no. +that is still open, and saying no - and what only the bot does, because only +Telegram can be asked in: raising a request, and finding who to tell. """ from __future__ import annotations @@ -13,9 +14,56 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from app.models import AccessRequest, SchoolClass +from app.models import AccessRequest, BotUser, Role, SchoolClass from app.services import audit +#: The note a requester may leave, in characters; the column is as wide. +NOTE_MAX = 300 + + +async def submit( + session: AsyncSession, class_id: int, telegram_id: int, note: str | None +) -> AccessRequest: + """Ask for the editor's role. + + One open request per person per class - a second one replaces the first, + so a nervous requester cannot fill an admin's screen. + """ + request = await session.scalar( + select(AccessRequest).where( + AccessRequest.class_id == class_id, + AccessRequest.telegram_id == telegram_id, + AccessRequest.status == "pending", + ) + ) + if request is None: + request = AccessRequest( + class_id=class_id, + telegram_id=telegram_id, + requested_role=Role.EDITOR, + status="pending", + ) + session.add(request) + request.requested_role = Role.EDITOR + request.status = "pending" + request.message = (note or None) and note[:NOTE_MAX] + request.decided_by = None + request.decided_at = None + await session.flush() + return request + + +async def admins(session: AsyncSession, class_id: int) -> list[BotUser]: + """Everybody who may answer a request: the admins and the owner.""" + return list( + await session.scalars( + select(BotUser).where( + BotUser.class_id == class_id, + BotUser.role.in_([Role.ADMIN, Role.OWNER]), + ) + ) + ) + async def pending(session: AsyncSession, class_id: int) -> list[AccessRequest]: """Everybody waiting for a role, oldest first.""" diff --git a/server/app/services/manage/search.py b/server/app/services/manage/search.py new file mode 100644 index 00000000..6d73c49b --- /dev/null +++ b/server/app/services/manage/search.py @@ -0,0 +1,37 @@ +"""«🔎 /find»: a class's homework, reachable by memory instead of by date.""" + +from __future__ import annotations + +from datetime import date as Date + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import Homework + + +async def homework( + session: AsyncSession, class_id: int, needle: str, *, since: Date, limit: int +) -> list[Homework]: + """Assignments due from ``since`` on whose text or subject contains ``needle``. + + Newest first, at most ``limit``. ``lower().contains()`` rather than ILIKE, + which SQLite does not have. Both dialects fold Cyrillic: Postgres does it + natively, and ``app.db`` replaces SQLite's ASCII-only ``lower()`` with + Python's on every connection, so the search behaves the same for the + developer and for the class. + """ + pattern = needle.lower() + return list( + await session.scalars( + select(Homework) + .where( + Homework.class_id == class_id, + Homework.due_date >= since, + func.lower(Homework.text).contains(pattern) + | func.lower(Homework.subject_name).contains(pattern), + ) + .order_by(Homework.due_date.desc(), Homework.id.desc()) + .limit(limit) + ) + ) diff --git a/server/app/services/manage/special_days.py b/server/app/services/manage/special_days.py new file mode 100644 index 00000000..26fe6f69 --- /dev/null +++ b/server/app/services/manage/special_days.py @@ -0,0 +1,86 @@ +"""«🏖 Особые дни»: the dates a class marks as not an ordinary school day. + +A :class:`DayOverride` is how the class says "this date is not a normal school +day". «Обычный день» is the absence of a row, not a kind of row, so choosing it +deletes the mark instead of storing ``DayKind.NORMAL`` - otherwise the resolver +would have two ways to spell the same thing. + +Only the bot's «⚙️ Класс» edits marks in bulk; the phone marks one day at a time +through ``PUT /api/v1/edit/days``, under the editor's role, with its own rules +about the bells. These are the reads and the one write the bot's screen does. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import timedelta + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import BellSchedule, DayKind, DayOverride, SchoolClass + + +async def upcoming( + session: AsyncSession, class_id: int, today: Date, only: DayKind | None = None +) -> list[DayOverride]: + """The marks from ``today`` on, by date; narrowed to one kind if asked.""" + query = ( + select(DayOverride) + .where(DayOverride.class_id == class_id, DayOverride.date >= today) + .order_by(DayOverride.date) + ) + if only is not None: + query = query.where(DayOverride.kind == only) + return list(await session.scalars(query)) + + +async def schedule_names(session: AsyncSession, class_id: int) -> dict[int, str]: + """Bell schedule id -> name, for the marks that point at one.""" + return { + schedule.id: schedule.name + for schedule in await session.scalars( + select(BellSchedule).where(BellSchedule.class_id == class_id) + ) + } + + +async def mark_on(session: AsyncSession, class_id: int, day: Date) -> DayOverride | None: + """The class's mark on ``day``, if it has one.""" + return await session.scalar( + select(DayOverride).where(DayOverride.class_id == class_id, DayOverride.date == day) + ) + + +async def mark( + session: AsyncSession, school_class: SchoolClass, day: Date, kind: DayKind +) -> DayOverride: + """Mark ``day`` as ``kind``, over whatever mark it had.""" + override = await mark_on(session, school_class.id, day) + if override is None: + override = DayOverride(class_id=school_class.id, date=day, kind=kind) + session.add(override) + override.kind = kind + if kind is not DayKind.SHORTENED: + # A bell schedule only means anything on a shortened day; leaving a + # stale one on a holiday would surface in the day view as a + # schedule nobody chose. + override.bell_schedule_id = None + elif override.bell_schedule_id is None: + # Never null on a shortened day. The picker opens next and is where + # the real answer comes from, but the row is committed before it is + # asked — so walking away used to leave «⏱ Сокращённые уроки» over a + # day that names no schedule, which `api/edit.day_put` refuses with a + # 422 and the resolver silently draws as a normal day. The class + # default is the honest starting value: it is what the day would ring + # anyway, and now it says so on the card. + override.bell_schedule_id = school_class.bell_schedule_id + return override + + +async def mark_period( + session: AsyncSession, school_class: SchoolClass, first: Date, days: int, kind: DayKind +) -> None: + """Mark ``days`` consecutive dates from ``first`` as ``kind``.""" + for offset in range(days): + await mark(session, school_class, first + timedelta(days=offset), kind) diff --git a/server/app/services/manage/subjects.py b/server/app/services/manage/subjects.py index 7b3f8839..62040557 100644 --- a/server/app/services/manage/subjects.py +++ b/server/app/services/manage/subjects.py @@ -14,7 +14,7 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from app.models import Subject +from app.models import Subject, TimetableEntry from app.services import audit, structure from app.services import subjects as dictionary @@ -83,6 +83,41 @@ async def subject_of(session: AsyncSession, class_id: int, subject_id: int) -> S ) +async def collect(session: AsyncSession, class_id: int, actor_id: int | None) -> int: + """Write down every name the timetable uses that the dictionary lacks. + + «Собрать из расписания» in the bot. It invents nothing, which is why an + editor may press it. Exact spellings, unlike :func:`listing`'s adoption: + this is the button for "I have just pasted a day and want to see its + subjects", and it was written before the adoption folded case. + + @return how many entries it added; nothing is logged when that is none. + """ + names = list( + await session.scalars( + select(TimetableEntry.subject_name) + .where(TimetableEntry.class_id == class_id) + .distinct() + ) + ) + known = { + subject.name + for subject in await session.scalars(select(Subject).where(Subject.class_id == class_id)) + } + created = [name for name in sorted(names) if name and name not in known] + for name in created: + session.add(Subject(class_id=class_id, name=name[: dictionary.MAX_NAME])) + if created: + await audit.record( + session, + class_id, + actor_id, + "subject.collect", + f"собрано предметов из расписания: {len(created)}", + ) + return len(created) + + async def create( session: AsyncSession, class_id: int, diff --git a/server/tests/test_bot_commands.py b/server/tests/test_bot_commands.py index 1488cfde..f66573b9 100644 --- a/server/tests/test_bot_commands.py +++ b/server/tests/test_bot_commands.py @@ -28,13 +28,15 @@ from app.bot import states from app.bot.bot import COMMANDS, build_dispatcher +from app.bot.handlers.manage import NEED_ADMIN from app.bot.handlers.unknown import STALE_CARD, UNKNOWN_COMMAND from app.bot.keyboards import WeekNav +from app.bot.manage_keyboards import BellsAction from app.bot.manage_states import EditSubject from app.bot.middlewares import FORM_DROPPED from app.db import SessionLocal from app.fsm_storage import DatabaseStorage -from app.models import BotUser, DayEvent, Homework, Role, SchoolClass +from app.models import AuditEntry, BotUser, DayEvent, Homework, Role, SchoolClass USER_ID = 4242 @@ -397,3 +399,54 @@ async def test_a_press_a_handler_owns_never_reaches_the_catch_all(bot, sent): answers = [m for m in sent.sent if type(m).__name__ == "AnswerCallbackQuery"] assert answers, "the press was not answered at all" assert STALE_CARD not in [a.text for a in answers] + + +@pytest.mark.parametrize( + ("role", "drawn"), [(Role.VIEWER, False), (Role.ADMIN, True)], ids=["viewer", "admin"] +) +async def test_the_role_decorator_answers_through_the_dispatcher( + bot, sent, session, school_class, role, drawn +): + """«⚙️ Класс» checks roles with `@needs` on each handler (#207), and the + handler tests call the handlers directly, so this is the half they cannot + see: aiogram reads what to inject off the function the decorator wraps, + and a refusal has to be answered by the handler that matched rather than + handed on to the catch-all. An admin gets the page, which is proof the + wrapped handler received its session, class, role and state; a наблюдатель + gets the refusal as an alert, and nothing drawn. + """ + session.add(BotUser(telegram_id=USER_ID, class_id=school_class.id, role=role)) + await session.commit() + + result = await dispatcher().feed_update(bot, _press(BellsAction(action="list").pack())) + + assert result is not UNHANDLED + answers = [m for m in sent.sent if type(m).__name__ == "AnswerCallbackQuery"] + assert len(answers) == 1, "the press was answered more than once, or not at all" + edits = [m for m in sent.sent if type(m).__name__ == "EditMessageText"] + if drawn: + assert edits and "Расписания звонков" in edits[0].text + assert not answers[0].show_alert + else: + assert edits == [] + assert answers[0].text == NEED_ADMIN + assert answers[0].show_alert is True + + +async def test_a_refused_form_step_through_the_dispatcher_drops_the_form_quietly( + bot, sent, session, school_class +): + """The other shape of the same refusal: text typed into a form this person + has no right to have open. FSM state is per-user, so a client can put + itself into «Новое название предмета» - and the answer is to drop the form + and say nothing, exactly as the check at the top of the step did by hand.""" + session.add(BotUser(telegram_id=USER_ID, class_id=school_class.id, role=Role.VIEWER)) + await session.commit() + await _set_state(bot, EditSubject.create) + + await dispatcher().feed_update(bot, _message("Физика")) + + assert await _state_of(bot) is None + assert sent.texts == [] + async with SessionLocal() as db: + assert (await db.scalars(select(AuditEntry))).all() == [] diff --git a/server/tests/test_bot_manage.py b/server/tests/test_bot_manage.py index 264ed4af..29ac9c9f 100644 --- a/server/tests/test_bot_manage.py +++ b/server/tests/test_bot_manage.py @@ -4224,13 +4224,16 @@ async def command(name, call): def _minimum_role_of(source: str) -> dict[str, Role | None]: - """What each function in ``handlers/manage`` demands, read off its own body. - - Two spellings, because the module uses two. ``_allowed(school_class, role, - Role.X)`` is the shared check — its own docstring says it exists so that no - handler invents a version of its own — and ``role.at_least(Role.X)`` is the - one place that checks inline. Reading them beats keeping a second copy of - the table in this file, which is the mistake that made the list above + """What each function in ``handlers/manage`` demands, read off its own source. + + Three spellings, because the package uses three. ``@needs(Role.X)`` over + the handler is the one role check (#207): the decorator that runs + ``_allowed`` before the body. ``_allowed(school_class, role, Role.X)`` is + that check called by hand, and ``role.at_least(Role.X)`` is the one place + that checks inline - the diary binding's last step, whose class comes out + of the form's state. The decorator is part of the function's node, so it + is read with the body. Reading them beats keeping a second copy of the + table in this file, which is the mistake that made the list above fifty-seven names long and nine names short. The *weakest* role mentioned wins, not the first one found: a guard reading @@ -4250,6 +4253,8 @@ def _minimum_role_of(source: str) -> dict[str, Role | None]: argument: ast.expr | None = None if getattr(call.func, "id", "") == "_allowed" and len(call.args) == 3: argument = call.args[2] + elif getattr(call.func, "id", "") == "needs" and call.args: + argument = call.args[0] elif getattr(call.func, "attr", "") == "at_least" and len(call.args) == 1: argument = call.args[0] if isinstance(argument, ast.Attribute) and argument.attr in Role.__members__: @@ -4258,6 +4263,30 @@ def _minimum_role_of(source: str) -> dict[str, Role | None]: return found +def test_a_handler_that_cannot_show_its_role_cannot_be_gated(): + """`@needs` reads the role and the class off the handler's own arguments, + and a step's form off its state. A handler that declares none of them + would be gated by nothing, so it is refused when the module is imported + rather than on the first press.""" + from app.bot.handlers.manage._common import needs + + async def no_role(callback, school_class) -> None: # pragma: no cover - never called + return None + + async def step_without_state(message, school_class, role) -> None: # pragma: no cover + return None + + async def event_not_first(session, callback, school_class, role) -> None: # pragma: no cover + return None + + with pytest.raises(TypeError): + needs(Role.ADMIN)(no_role) + with pytest.raises(TypeError): + needs(Role.ADMIN, step=True)(step_without_state) + with pytest.raises(TypeError): + needs(Role.ADMIN)(event_not_first) + + def test_the_role_check_above_reaches_every_handler_that_has_one(): """The list of steps pressed above, derived instead of remembered. @@ -4305,7 +4334,7 @@ def routers(router): if minimums.get(name) is None and name not in NOT_A_ROLE_GATE ) assert not ungated, ( - "these are registered on the management router and never call `_allowed`; " + "these are registered on the management router and demand no role; " f"decide what they demand before exempting them: {ungated}" ) From 7de2c01de611df1b0823e80cc35525d726081bdf Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 19:40:46 +0300 Subject: [PATCH 34/43] Describe the two shells that write, instead of an API that only reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CLAUDE.md, `app/main.py`'s docstring and docs/architecture.md said «the bot writes, the API reads», while `/api/v1/edit` and `/api/v1/manage` write the class from a linked phone and `public.py` and `/api/v1/diary` write an account's and a family's own rows. A reader planning against that sentence planned against the wrong model. They now say what is true: two shells write, over one set of services, and docs/architecture.md carries a table of every API family that writes, what it writes and on whose authority - the device token with the linked account's role (`linking.effective_role`, per request) for edit and manage, the device token for an account's own tasks and ticks, the diary token for the diary, and the one-time link, the cron secret and the webhook secret for the rest. The same sections now describe the layout #208, #206 and #207 left: the three `manage` packages (`bot/handlers/manage/`, `api/manage/`, `services/manage/`, one module per screen, named alike), refusals as exceptions carrying facts so each shell keeps its own words, the `@needs(Role.X)` decorator and why it is a decorator rather than a filter or a middleware flag, and the layer rule that nothing under `services/` may import `app.bot`, directly or through another module - naming `services/roles.py` and `app/wording.py` as where the role ladder and the shared wording live. Those two files, and `tests/test_service_layering.py` which holds the rule, come from #205 on another branch (agents/audit-server-architecture); on this branch alone `services/access.py`, `linking.py`, `reminders.py` and `timetable_io.py` still import `app.bot.roles` / `app.bot.render`, so the documents describe the tree as it stands once both are merged. In CLAUDE.md only the Architecture section changed; in `app/main.py` only the module docstring. `di.py`'s docstring, AGENTS.md, docs/bot.md and the server-api agent repeated the old sentence or named `manage.py` and were brought level. `.github/copilot-instructions.md` still says «The bot writes, the API reads» - `.github/` is outside this batch's reach. Closes #204 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/agents/server-api.md | 5 +-- AGENTS.md | 10 +++--- CLAUDE.md | 49 ++++++++++++++++++++----- docs/architecture.md | 69 +++++++++++++++++++++++++++++++++--- docs/bot.md | 7 ++-- server/app/di.py | 6 ++-- server/app/main.py | 14 +++++--- 7 files changed, 130 insertions(+), 30 deletions(-) diff --git a/.claude/agents/server-api.md b/.claude/agents/server-api.md index d9af4495..28724566 100644 --- a/.claude/agents/server-api.md +++ b/.claude/agents/server-api.md @@ -1,6 +1,6 @@ --- name: server-api -description: FastAPI surface of the server — public.py, edit.py, manage.py, diary.py, diary_web.py, cron.py, telegram.py and deps.py. Use when an endpoint is added, its auth changes, or a response shape moves. Knows which of the two bearer tokens an endpoint family depends on. +description: FastAPI surface of the server — public.py, edit.py, manage/, diary.py, diary_web.py, cron.py, telegram.py and deps.py. Use when an endpoint is added, its auth changes, or a response shape moves. Knows which of the two bearer tokens an endpoint family depends on. tools: Read, Glob, Grep, Bash, Edit, Write --- @@ -9,7 +9,8 @@ every caller before you change a signature. ## What is actually here -- `public.py` reads, `edit.py` and `manage.py` write, `diary.py` is the electronic diary, +- `public.py` reads (and writes an account's own tasks and ticks), `edit.py` and `manage/` write — the + latter one module per resource over `services/manage/` — `diary.py` is the electronic diary, `diary_web.py` is the one server-rendered page in the project, `cron.py` is the clock the server does not have, `telegram.py` is the webhook, `deps.py` is device-token auth. - The write endpoints are a thin shell over `app/services/`. The bot handlers are the other diff --git a/AGENTS.md b/AGENTS.md index 546a7299..90c96f7c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,13 +8,15 @@ minimum, not a second copy: **`CLAUDE.md` at the root is the source of truth**, «Дневник» (`lessons`): a school diary for Russian schools. Three deliverables in one tree — an Android app with a resizable home-screen widget (`android/`, five Gradle modules), a -FastAPI read API with an aiogram bot in the same process (`server/`), and a thin Vercel entry +FastAPI client API with an aiogram bot in the same process (`server/`), and a thin Vercel entry point (`api/`). Documentation is `docs/`, indexed by `docs/README.md`. There is no npm and no web frontend. -**The bot writes, the API reads.** Telegram already solved identity, so there is no admin web -panel. `server/app/services/` holds the rules the bot handlers and the `/api/v1/manage` -endpoints share — two thin shells over one implementation. +**Two shells write, over one set of services.** Telegram already solved identity, so there is +no admin web panel: the bot is the admin panel, and a phone linked to a Telegram account writes +through `/api/v1/edit` and `/api/v1/manage` with that account's role. `server/app/services/` +holds the rules both shells call — two thin shells over one implementation — and nothing under +it may import `app.bot`. ## Language diff --git a/CLAUDE.md b/CLAUDE.md index c2ddd6b5..898a3db1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -104,11 +104,26 @@ quoting the number that had been asked for. Read `docs/architecture.md` before any cross-cutting change; it is current and it explains the decisions, not just the layout. -**The bot writes, the API reads.** Telegram already solved identity, so there is no admin -web panel, no session cookies and no password reset. The cost is real and deliberate: -anything the bot cannot express does not exist. `server/app/services/` holds the rules -shared by the bot handlers and the `/api/v1/manage` endpoints — two thin shells over one -implementation, because two implementations of "rename a subject" disagree within a month. +**Two shells write, over one set of services.** The bot is the admin panel, and a linked +phone runs the same class through the API: `/api/v1/edit` (homework, substitutions, events, +special days — editor and above) and `/api/v1/manage` (subjects, bells, the timetable, +devices, access requests, terms, the class itself — admin, and owner to delete it). Both +take the **device token** and ask `linking.effective_role` for the linked account's role on +every request, so an unlinked phone changes nothing of the class's. The rest of what the +API writes is personal (`public.py`: the linked account's own tasks and ticked-off +homework, whatever its role, and a phone unlinking itself; `/join` mints the device token) +and a family's diary (`/api/v1/diary`, with the **diary token**); `docs/architecture.md` has +the table. +Telegram already solved identity, so there is still no admin web panel, no session cookies +and no password reset — a phone has no rights of its own, only its account's — and the cost +is still real: anything the bot cannot express does not exist. `server/app/services/` holds +the rules both shells call — two thin shells over one implementation, because two +implementations of "rename a subject" disagree within a month — and **nothing under +`services/` may import `app.bot`**, directly or through another `app/` module: a rule that +lives in the bot is a rule the phone does not get, and a service that pulls aiogram in puts +it on the API's cold start. The role ladder lives in `services/roles.py` (`bot/roles.py` +re-exports it) and the wording both shells print in `app/wording.py`; +`tests/test_service_layering.py` holds the rule. Server modules: @@ -128,15 +143,33 @@ Server modules: shadowing. Do **not** import `dishka.integrations.aiogram` from it — that pulls aiogram onto the cold-start path of every request, which is the thing `main.py` and `api/telegram.py` already go out of their way to defer -- `api/` — `public.py` (read), `edit.py` and `manage.py` (write), `diary.py`, `cron.py`, +- `services/` — the rules, as async functions over a session. Nothing there commits (the + caller commits the change together with its audit line), and nothing may import `app.bot`. + `services/manage/` is running a class, one module per screen named like the shells' + (`subjects`, `bells`, `devices`, `classes`, `requests`, `journal`, `terms`, `timetable`, + `special_days`, `search`): each does the check, the write and the audit line with its + Russian wording, and a refusal is an exception carrying facts, never a sentence, so each + shell keeps its own words — «Предмет … уже есть» in a chat, a `409` on the wire +- `api/` — `public.py` (the phone's reads and its own writes), `edit.py` (the day-to-day + writes), `manage/` (running the class, one module per resource over + `services/manage/`, with `_common.py` holding `Actor` and the one role dependency per + level), `diary.py`, `cron.py`, `telegram.py` (webhook), `deps.py` (device-token auth), `routing.py` (the route class every router here is built with: dishka's wrapper carries its own globals, so under `from __future__ import annotations` FastAPI could not resolve an endpoint's `-> Response` and took the name for a response model — a 204 route made that an `AssertionError` at import, and every route without an explicit `response_model=` would have had a schema built from a string) -- `bot/` — aiogram routers, roles, keyboards, renderers. The weekly template has **two** - editors and both are wanted: `handlers/timetable.py` pastes a whole weekday (fastest way +- `bot/` — aiogram routers, roles, keyboards, renderers. «⚙️ Класс» is `handlers/manage/`, + one module per screen, each with a router of its own included in one written-down order + by the package's `__init__`. Every handler there says what it needs with + `@needs(Role.X)` (`handlers/manage/_common.py`) under its `@router…` line — one decorator + instead of seventy-two copies of the check, and a decorator rather than a filter or a + middleware flag because the check has to travel with the function: a failed filter hands + the update on instead of refusing it, and the tests that press every step as a + наблюдатель call the handlers directly. A refusal is an alert for a press, a sentence for + a command, and a dropped form with no answer for a step (`step=True`). + The weekly template has **two** editors and both are wanted: `handlers/timetable.py` pastes a whole weekday (fastest way to enter a term), `handlers/editor.py` changes one lesson with buttons. They share one grammar (`services/timetable_io.py`) and one set of mutations (`services/timetable_edit.py`) — the editor's ‹ › pager and «⏱ Перемены» switch live in diff --git a/docs/architecture.md b/docs/architecture.md index ea46c885..89f19e0f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,7 +4,7 @@ Three deliverables, one repository: ``` lessons/ -├── server/ FastAPI read API + aiogram admin bot, one process, one database +├── server/ FastAPI client API + aiogram admin bot, one process, one database ├── android/ Kotlin / Compose app, five Gradle modules └── docs/ ``` @@ -12,8 +12,8 @@ lessons/ ## Why the bot is the backend The requirement was "admin panel in Telegram". Rather than build a web panel and -bolt a bot onto it, the bot writes directly to the database and the HTTP API only -reads. That collapses a whole tier: no admin auth, no session cookies, no CSRF, +bolt a bot onto it, the bot is the admin panel, and it writes straight to the +database. That collapses a whole tier: no admin auth, no session cookies, no CSRF, no password reset, no second deployment unit. Telegram already knows who someone is, and the phone-invite flow uses that identity as proof. @@ -21,6 +21,26 @@ The cost is that anything the bot cannot express does not exist. That is a real constraint and it is the reason the timetable editor takes a pasted block of text instead of a grid. +**The HTTP API is not read-only, and has not been for a long time.** It began as +the phone's read side and grew a second way into the same class, so that an admin +can run it from the app as well as from the chat. What writes, and on whose +authority: + +| Family | Writes | Authority | +|---|---|---| +| `/api/v1/edit` | homework, substitutions, events, special days | the device token; the linked account's role, editor or above | +| `/api/v1/manage` | subjects, bells, the timetable, devices, access requests, terms, the class itself | the device token; the linked account's role — admin, and owner to delete the class | +| `/api/v1` (`public.py`) | the account's own tasks and ticked-off homework, a phone unlinking itself; `POST /join` mints the token | the device token — linked, any role, for the account's own rows; `/join` takes a code | +| `/api/v1/diary` | a diary session, a family's corrections over the diary | the diary token; `/login` and `/session` take the diary's own credentials | +| `/diary/signin`, `/api/v1/cron/tick`, `/api/v1/telegram/webhook` | a sign-in through the web form; the digests' marks and the sweeps; the bot's updates | a one-time link; `X-Cron-Secret`; the webhook secret | + +A phone still has no rights of its own: the two families that change the class take +the role of the Telegram account the device is linked to, looked up per request +(see [the service layer](#the-service-layer-and-why-the-phone-does-not-log-in)). +So the rule that replaced «the bot writes, the API reads» is that **two shells +write, over one set of services**: whatever a class admin can do from a phone, the +bot can do, by the same function. + ## The server ``` @@ -31,7 +51,8 @@ app/ ├── security.py tokens, join codes, phone normalisation ├── di.py the container both shells take a session from ├── catalog/ the region catalog — generated data, never edited by hand -├── api/ read-only client endpoints +├── services/ the rules both shells call — pure async functions over a session +├── api/ the client API: reads, and the writes in the table above ├── bot/ aiogram routers, roles, keyboards, renderers └── main.py FastAPI app; its lifespan owns the bot's polling task ``` @@ -134,6 +155,7 @@ without dragging the app's entire UI graph into its process. ``` Telegram bot ──writes──▶ Postgres/SQLite ──/api/v1/bundle──▶ Room ──▶ UI +linked phone ──writes──▶ (/api/v1/edit, /api/v1/manage) │ └──▶ Glance widget ``` @@ -394,7 +416,7 @@ can swap wholesale. ## The service layer, and why the phone does not log in -`server/app/services/` is twenty-two modules of pure async functions over a session, and +`server/app/services/` is thirty-two modules of pure async functions over a session, and they exist for exactly one reason: every feature of the product now has two entrances, the bot and the app. Homework is added by a command in a chat and by a button on a phone; so are a substitution, an event and a special day. Two implementations of one rule would have @@ -404,6 +426,43 @@ reminders and their idempotence, the broadcast to subscribers, the calendar feed statistics, the timetable export and import, and granting the role somebody asked for, which was forty lines of permission rules carried in both shells until it was not. +**Running a class has one module per screen, three times over.** «⚙️ Класс» in the bot is +`bot/handlers/manage/`, `/api/v1/manage` is `api/manage/`, and what both of them do is +`services/manage/` — `subjects`, `bells`, `devices`, `classes`, `requests`, `journal`, +`terms`, `timetable`, `special_days`, `search` — so the twin of `bot/handlers/manage/bells.py` +and of `api/manage/bells.py` is `services/manage/bells.py`. Each service function does the +check, the write and the audit line with its Russian wording; the two shells only translate +— a callback or a paste in, a message or an alert out; a payload in, JSON out. A refusal +is an exception carrying facts (how many lessons, which days), never a sentence, so each +shell keeps its own words for it: «Предмет … уже есть» in a chat, a `409` with an English +`detail` on the wire. Before the split the shells had each kept a copy of every one of +these operations, and several copies had drifted — the bot never logged a change of time +zone, a colour taken off a subject was «убран» in one log and «убрано» in the other, the +bot logged a second line for a phone that was already switched off, and a bot import never +said which stored lessons stopped ringing. + +**Nothing under `services/` may import `app.bot`**, directly or through another `app/` +module. A service that needed the bot would be one the API could not call without dragging +aiogram onto its cold start, and a rule that lives in `bot/` is a rule the phone does not +get. So the role ladder — who may grant what, a member's role in a class — lives in +`services/roles.py`, with `bot/roles.py` a shim that re-exports it, and the wording both +shells print (month and weekday names, `plural`, the message budget, a day rendered as +text) in `app/wording.py`. `tests/test_service_layering.py` holds the rule by walking the +imports. + +**The bot checks roles with one decorator.** Every handler of «⚙️ Класс» says what it needs +where it is registered — `@needs(Role.ADMIN)` under `@router.callback_query(...)`, from +`bot/handlers/manage/_common.py` — instead of opening with its own copy of the check and +the refusal after it, as seventy-two of them used to. The refusal has three shapes, +decided in one place: a press is answered with an alert (an unanswered one keeps spinning), +a command with a sentence, and a step of a form drops the form and says nothing. It is a +decorator rather than an aiogram filter or a middleware flag because the check has to +travel with the function: a filter that fails hands the update to the next handler instead +of refusing it, and a flag is read only on the way in through the dispatcher — while the +tests that press every step as a наблюдатель call the handlers directly, and are the only +proof the check exists. The API answers the same question with one dependency per role +(`api/manage/_common.py`), which is the same rule on the other side of the wire. + **A phone has no rights of its own**, and that is the central decision of this layer. The device gets a six-character code from the server, the person sends it to the bot, and from that moment the device token is bound to a Telegram account. A class that lets phones in diff --git a/docs/bot.md b/docs/bot.md index e79b6dc0..01a1d96c 100644 --- a/docs/bot.md +++ b/docs/bot.md @@ -5,9 +5,10 @@ Telegram already solved identity, and a class timetable does not deserve its own password reset flow. Everything below is what the code in `server/app/bot/` actually does. Handlers -live in `handlers/`, the structural half of them in `handlers/manage.py`; the -wording lives in `render.py` and `manage_render.py`; the buttons in -`keyboards.py`, `manage_keyboards.py` and `calendar_keyboard.py`. +live in `handlers/`, the structural half of them in `handlers/manage/` — one +module per screen of «⚙️ Класс», over `services/manage/`, each handler gated by +`@needs(Role.X)`; the wording lives in `render.py` and `manage_render.py`; the +buttons in `keyboards.py`, `manage_keyboards.py` and `calendar_keyboard.py`. ## Button colours diff --git a/server/app/di.py b/server/app/di.py index ef15a9a4..fccdfc4f 100644 --- a/server/app/di.py +++ b/server/app/di.py @@ -1,9 +1,9 @@ """The container: what has a lifetime, and who ends it. This project is deliberately two thin shells over one implementation — the bot -writes and the API reads, and ``app/services/`` holds the rules both of them -call, because two implementations of "rename a subject" disagree within a -month. The shells had no such agreement about the things that are *built* per +and the phone-facing API both write, and ``app/services/`` holds the rules both +of them call, because two implementations of "rename a subject" disagree within +a month. The shells had no such agreement about the things that are *built* per unit of work. A session came from :func:`app.db.get_session` in an endpoint, from ``SessionLocal()`` in the bot's middleware and from :func:`app.db.session_scope` in ``scripts/seed_demo``: three answers to one diff --git a/server/app/main.py b/server/app/main.py index 2d04349b..355a4b66 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -1,8 +1,12 @@ -"""Entry point: the read-only client API and the Telegram admin bot in one process. - -Keeping them together means the bot writes and the API reads the same database -with no extra deployment moving parts. If the bot ever needs to scale -separately, split it at ``run_polling`` — nothing else is shared. +"""Entry point: the client API and the Telegram admin bot in one process. + +Both write the same database, over the same ``app/services/``: the bot is the +admin panel, and a phone linked to a Telegram account writes through +``/api/v1/edit`` and ``/api/v1/manage`` with that account's role, while the +rest of the API reads, or writes only an account's or a family's own rows. +Keeping them together means one database and no extra deployment moving parts. +If the bot ever needs to scale separately, split it at ``run_polling`` — +nothing else is shared. """ from __future__ import annotations From febaae9d599aaa9719b4384bb08e75f53c5d0565 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 20:38:09 +0300 Subject: [PATCH 35/43] Check the documents of this checkout for the head, and not those of the agents working beside it test_every_document_that_names_the_head_names_this_one collected the Markdown under .claude/ with an rglob, and that walk also descends into .claude/worktrees/, where Claude Code keeps the untracked git worktrees of parallel agents. Each of them is another branch's whole checkout, HANDOVER.md and docs/history.md included, which are the two documents the test excludes on purpose because they hold every head there has been. With nine agents based on 938e59f beside it, the main checkout's run named `0013` from nine copies of an older HANDOVER.md and failed. CI never saw it: a fresh checkout has no worktrees. The walk now skips .claude/worktrees/, and _documents() takes the repository as an argument so a test can plant a stale document there and show it is left out. That test fails without the filter. Not covered: nothing stops a future walk elsewhere in the suite from reading the worktrees the same way; this was the only test that walks the repository root today. Closes #213 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- server/tests/test_schema_version.py | 41 +++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/server/tests/test_schema_version.py b/server/tests/test_schema_version.py index 02269018..ee63378c 100644 --- a/server/tests/test_schema_version.py +++ b/server/tests/test_schema_version.py @@ -97,18 +97,43 @@ def test_the_constant_the_app_ships_is_the_real_migration_head(): #: The record of past batches, moved verbatim out of HANDOVER.md: it quotes the #: head of every commit it describes, true of that commit, and is never #: brought up to date. -_HISTORY = REPOSITORY / "docs" / "history.md" +_HISTORY = Path("docs") / "history.md" -def _documents() -> list[Path]: +def _documents(repository: Path = REPOSITORY) -> list[Path]: """Everything a person or an agent reads to learn the head — not HANDOVER.md or docs/history.md, which between them hold every head - there has been.""" - found = [REPOSITORY / name for name in ("README.md", "CLAUDE.md", "AGENTS.md")] - found.append(REPOSITORY / ".github" / "copilot-instructions.md") - found += sorted((REPOSITORY / "docs").rglob("*.md")) - found += sorted((REPOSITORY / ".claude").rglob("*.md")) - return [document for document in found if document.is_file() and document != _HISTORY] + there has been, and not `.claude/worktrees/`, which holds other + branches' checkouts rather than this one's.""" + found = [repository / name for name in ("README.md", "CLAUDE.md", "AGENTS.md")] + found.append(repository / ".github" / "copilot-instructions.md") + found += sorted((repository / "docs").rglob("*.md")) + worktrees = repository / ".claude" / "worktrees" + found += sorted(document for document in (repository / ".claude").rglob("*.md") + if not document.is_relative_to(worktrees)) + return [document for document in found + if document.is_file() and document != repository / _HISTORY] + + +def test_the_documents_are_this_checkouts_and_not_an_agents_worktree(tmp_path): + """Claude Code keeps parallel agents' git worktrees under + `.claude/worktrees/`, untracked, each with its own branch's HANDOVER.md + and docs. Read as part of this checkout, nine of them named a head four + revisions old and failed every local run beside them (#213).""" + (tmp_path / "docs").mkdir() + (tmp_path / "docs" / "deploy.md").write_text("expects `0017`", "utf-8") + skill = tmp_path / ".claude" / "skills" / "migration" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("the head is `0017`", "utf-8") + elsewhere = tmp_path / ".claude" / "worktrees" / "agent-a1" / "docs" / "deploy.md" + elsewhere.parent.mkdir(parents=True) + elsewhere.write_text("expects `0013`", "utf-8") + + found = _documents(tmp_path) + + assert skill in found + assert tmp_path / "docs" / "deploy.md" in found + assert elsewhere not in found def test_every_document_that_names_the_head_names_this_one(): From 8883eaa1a2a65d736c843edeb5a7f46d449aa8b3 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 20:41:34 +0300 Subject: [PATCH 36/43] Say what the audit's server split left behind: the package, the wording, and two shells that write MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/architecture.md's tree still showed `schemas.py` as one file after #208 made it a package, and it did not name `app/wording.py`, which #205 added beneath both shells. The Copilot instructions, read on every request, still said «the bot writes, the API reads» after #204 rewrote that everywhere else, and gave `python -m pytest` as the test command, which CLAUDE.md explains hides a broken import that fails on CI. The two API modules that still took `human_date` and `WEEKDAYS` from `app.bot.render` now take them from `app.wording`, where #205 moved them. Nothing forbade the old import — the layer rule binds services, and the API is a shell — but the words both shells print now have one home, and the API no longer reaches into the bot package for them. Not covered: Android KDoc comments that still point at server/app/schemas.py are repointed separately, after the Android branches land. Refs #204 Refs #205 Refs #208 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/copilot-instructions.md | 9 +++++---- docs/architecture.md | 3 ++- server/app/api/edit.py | 2 +- server/app/api/manage/timetable.py | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5bbc9244..a0d0f9fb 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -4,9 +4,10 @@ Short on purpose: this file is read on every request. The full picture is in `AG `CLAUDE.md` at the repository root. «Дневник» (`lessons`) is a school diary: an Android app (`android/`, five Gradle modules), a -FastAPI read API with an aiogram bot in one process (`server/`), and a thin Vercel entry -point (`api/`). No npm, no web frontend. **The bot writes, the API reads**, and the rules -they share live in `server/app/services/` so the two shells cannot disagree. +FastAPI API with an aiogram bot in one process (`server/`), and a thin Vercel entry point +(`api/`). No npm, no web frontend. **Two shells write** — the bot, and a linked phone +through `/api/v1/edit` and `/api/v1/manage` — over one set of rules in +`server/app/services/`, so they cannot disagree; nothing there may import `app.bot`. **Language.** The product speaks Russian: user-facing strings live in `values/` with an English twin in the same module's `values-en/`, or `ResourceTranslationTest` fails. @@ -15,7 +16,7 @@ request descriptions — is English, and a quotation of product text keeps its R guillemets. **Checks.** From `server/`: `ruff check app tests scripts migrations`, `python -m mypy`, -`python -m pytest -q -n auto`. From `android/`: `./gradlew test`, `./gradlew assembleDebug`, +`pytest -q -n auto` (not `python -m pytest`, which hides a broken import on CI). From `android/`: `./gradlew test`, `./gradlew assembleDebug`, `./gradlew assembleRelease`. CI is exactly those; `./gradlew lint` is not a gate. **Do not suggest:** diff --git a/docs/architecture.md b/docs/architecture.md index 89f19e0f..89fda12e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,9 +47,10 @@ bot can do, by the same function. app/ ├── models.py SQLAlchemy 2.0 ORM — the whole domain in one file ├── schedule.py template + overrides -> concrete days (no FastAPI, no aiogram) -├── schemas.py the wire contract +├── schemas/ the wire contract, one module per area, all re-exported by the package ├── security.py tokens, join codes, phone normalisation ├── di.py the container both shells take a session from +├── wording.py the words both shells print: dates, plurals, a day's card ├── catalog/ the region catalog — generated data, never edited by hand ├── services/ the rules both shells call — pure async functions over a session ├── api/ the client API: reads, and the writes in the table above diff --git a/server/app/api/edit.py b/server/app/api/edit.py index 3a448a6a..4ca3239a 100644 --- a/server/app/api/edit.py +++ b/server/app/api/edit.py @@ -28,7 +28,6 @@ from app.api.deps import current_class, current_device from app.api.public import MAX_BUNDLE_START, MIN_BUNDLE_START, _homework_out, _today from app.api.routing import DishkaAnnotatedRoute -from app.bot.render import human_date from app.config import get_settings from app.models import ( BellPeriod, @@ -58,6 +57,7 @@ from app.services import audit, linking, notify, subjects, timetable_edit from app.services import homework as homework_service from app.services import tasks as task_service +from app.wording import human_date log = logging.getLogger(__name__) diff --git a/server/app/api/manage/timetable.py b/server/app/api/manage/timetable.py index 02db2374..142e4b1f 100644 --- a/server/app/api/manage/timetable.py +++ b/server/app/api/manage/timetable.py @@ -13,11 +13,11 @@ from app.api.deps import current_class from app.api.manage._common import Actor, admin_actor from app.api.routing import DishkaAnnotatedRoute -from app.bot.render import WEEKDAYS from app.models import SchoolClass from app.schemas import ImportConflictOut, TimetableExportOut, TimetableImportIn, TimetableImportOut from app.services import structure, timetable_io from app.services.manage import timetable as timetable_service +from app.wording import WEEKDAYS router = APIRouter(route_class=DishkaAnnotatedRoute) From 1c40e1e1e4560408730972ce6d5f022dab50f716 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 20:42:55 +0300 Subject: [PATCH 37/43] Point the Android comments that mirror the wire format at the module each model now lives in Fourteen KDoc comments and test headers named `server/app/schemas.py` as the file a DTO, a form limit or a serial name is copied from. #208 made it a package, so a reader following one of them found no such file. Each now names the module that holds the model it mirrors, or the package where it mirrors several. Comments only; no code changes. Refs #208 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../com/lumenpearson/lessons/ui/admin/ManagementForms.kt | 6 +++--- .../com/lumenpearson/lessons/core/data/database/Entities.kt | 2 +- .../lumenpearson/lessons/core/data/network/DirectoryApi.kt | 2 +- .../lumenpearson/lessons/core/data/network/dto/BundleDto.kt | 2 +- .../lumenpearson/lessons/core/data/network/dto/DiaryDto.kt | 2 +- .../lumenpearson/lessons/core/data/network/dto/JoinDto.kt | 4 ++-- .../lumenpearson/lessons/core/data/network/dto/ManageDto.kt | 2 +- .../lumenpearson/lessons/core/data/repository/DiaryLogin.kt | 2 +- .../lessons/core/data/repository/DiarySignInImpl.kt | 5 ++++- .../lessons/core/data/network/dto/BundleJsonTest.kt | 2 +- .../lessons/core/data/network/dto/DiaryJsonTest.kt | 2 +- 11 files changed, 17 insertions(+), 14 deletions(-) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementForms.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementForms.kt index 67301b4d..66c52534 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementForms.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementForms.kt @@ -87,7 +87,7 @@ fun zoneOptions(current: String?): List<ManagedTimeZone> { * Why a form cannot be sent yet. * * An enum rather than a sentence so that the rule and its wording stay apart: - * the rule is a mirror of `server/app/schemas.py` and belongs next to the + * the rule is a mirror of `server/app/schemas/` and belongs next to the * limits it copies, the wording belongs in `strings_admin.xml` in two * languages. */ @@ -109,7 +109,7 @@ enum class FormProblem { NAME_DOES_NOT_MATCH, } -/** `Field(max_length=…)` in `server/app/schemas.py`, in one place. */ +/** `Field(max_length=…)` in `server/app/schemas/`, in one place. */ private object Limits { const val CLASS_NAME = 64 const val SCHOOL = 200 @@ -149,7 +149,7 @@ private fun isColourReadable(raw: String?): Boolean { return ColourDigits.matches(text.removePrefix("#")) } -/** `_COLOUR_RE` in `server/app/schemas.py`, without its anchors. */ +/** `_COLOUR_RE` in `server/app/schemas/subjects.py`, without its anchors. */ private val ColourDigits = Regex("[0-9a-fA-F]{6}") /** The class card's four boxes, as the server would judge them. */ diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/Entities.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/Entities.kt index 27509591..d98a3886 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/Entities.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/Entities.kt @@ -13,7 +13,7 @@ import java.time.LocalTime * these tables, and the network's only job is to replace their contents. * * Column names are snake_case to match the wire format, which makes the exported - * schema JSON readable next to `server/app/schemas.py` during a migration. + * schema JSON readable next to `server/app/schemas/` during a migration. */ /** diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt index 900500cd..2e18525d 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt @@ -36,7 +36,7 @@ internal interface DirectoryApi { } } -/** `SchoolRegionsOut` in `server/app/schemas.py`. */ +/** `SchoolRegionsOut` in `server/app/schemas/directory.py`. */ @Serializable internal data class SchoolRegionsDto( @SerialName("query") val query: String = "", diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleDto.kt index 647e5627..1f1e1323 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleDto.kt @@ -6,7 +6,7 @@ import kotlinx.serialization.Serializable /** * The whole offline payload: `GET /api/v1/bundle`. * - * Mirrors `BundleOut` in `server/app/schemas.py`. Every collection has a default + * Mirrors `BundleOut` in `server/app/schemas/bundle.py`. Every collection has a default * so that a server which drops an empty list still decodes, and every date/time * stays a [String] here - parsing happens in the mappers, where a malformed * value can be dropped instead of failing the entire sync. diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt index 5d4764c5..d0cd83ad 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt @@ -6,7 +6,7 @@ import kotlinx.serialization.json.JsonObject /** * The wire shapes of `/api/v1/diary`, mirroring every `Diary*` model in - * `server/app/schemas.py`. + * `server/app/schemas/`. * * Same rules as [BundleDto]: an explicit `@SerialName` on every field so a * rename on either side of the repository is a test failure rather than a diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt index fc75daaa..dc479634 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt @@ -8,7 +8,7 @@ import kotlinx.serialization.Serializable /** * Body of `POST /api/v1/join`. * - * Mirrors `JoinRequest` in `server/app/schemas.py`; the field names are the + * Mirrors `JoinRequest` in `server/app/schemas/join.py`; the field names are the * contract, so every property carries an explicit [SerialName] even where the * Kotlin name happens to match. */ @@ -35,7 +35,7 @@ internal data class JoinResponseDto( ) /** - * `DiaryBindingOut` in `server/app/schemas.py`: which diary the class reads. + * `DiaryBindingOut` in `server/app/schemas/join.py`: which diary the class reads. * * Every field defaults, so a binding a newer server shapes differently costs * the binding and never the join — [toDomain] turns anything it cannot stand diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/ManageDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/ManageDto.kt index 9d3c8c22..3239c3bd 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/ManageDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/ManageDto.kt @@ -6,7 +6,7 @@ import kotlinx.serialization.json.JsonElement /** * The wire shapes of `/api/v1/manage`, mirroring every management model in - * `server/app/schemas.py`. + * `server/app/schemas/`. * * Same rules as [BundleDto] and [DiaryLessonDto]: an explicit `@SerialName` on * every field, a default wherever the server may leave one out, and dates and diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt index 401e39e4..5d7cc16d 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt @@ -2,7 +2,7 @@ package com.lumenpearson.lessons.core.data.repository /** * A diary login as the server cleans it — `_clean_login_value` in - * `server/app/schemas.py`, held to it by the `login` cases of the shared + * `server/app/schemas/diary_session.py`, held to it by the `login` cases of the shared * vectors. * * One cleaning, used everywhere a login leaves the phone: the diary's own diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt index fce5b403..7d3e2118 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt @@ -322,7 +322,10 @@ internal class DiarySignInImpl( val DEFAULT_MAX_AGE: Duration = Duration.ofMinutes(10) const val MIN_DECLARED_TIMEOUT_MILLIS = 60_000L - /** `PetersburgCredentialIn` in `server/app/schemas.py`: a JWT that can be one cookie. */ + /** + * `PetersburgCredentialIn` in `server/app/schemas/diary_session.py`: a JWT that can be + * one cookie. + */ val JWT = Regex("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*") const val MIN_JWT_LENGTH = 16 diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleJsonTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleJsonTest.kt index f33c5eef..0c843e63 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleJsonTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/BundleJsonTest.kt @@ -16,7 +16,7 @@ import java.time.LocalTime * * This is the test that fails when someone renames a field on one side of the * repo only: the `@SerialName` values here are copied from - * `server/app/schemas.py`, not from the Kotlin property names. + * `server/app/schemas/bundle.py`, not from the Kotlin property names. */ class BundleJsonTest { diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt index 1333141f..b880c216 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt @@ -16,7 +16,7 @@ import org.junit.Test * production [NetworkModule.json] configuration. * * The `@SerialName` values asserted here are copied from the `Diary*` models in - * `server/app/schemas.py` rather than from the Kotlin property names, which is + * `server/app/schemas/` rather than from the Kotlin property names, which is * what makes this the test that fails when a field is renamed on one side of * the repository only. Every payload carries at least one explicit `null` and * one field the client has never heard of, because both are things the server From 44d49e28a5ef0c49e086d60e12c6098dffc454b4 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 20:43:09 +0300 Subject: [PATCH 38/43] Measure detekt through Gradle, now that a Gradle build has run it 9181796 was committed without a single Gradle build having run detekt: the crash had zero-filled the plugin's files in the shared module cache, so it checked the rules with detekt's command line instead and said so. With the cache cleared, the build now has run it, and every claim that commit left open holds: - `./gradlew detekt` passes on the tree: all five modules, zero findings outside the baselines, and each report counts exactly the .kt files the module's src/ holds (app 199, core/data 178, core/designsystem 76 with its androidTest, core/model 21, widget 38). - It fails on a finding the code did not already have: a scratch `minutes * 37` in :core:model went red on that MagicNumber alone, and the tree was clean once the file was removed. - `./gradlew detektBaseline` recomputes exactly the committed baselines. detekt writes the file only when the set of findings differs, and it left all five untouched, so the command docs/build.md hands the next merge writes what the command line wrote. - The configuration cache stores and reuses the detekt tasks' entry without a problem. - `test` (1459 tests, none failing) and `assembleDebug assembleRelease` build with the plugin applied, and neither graph holds a detekt task. What changes here is the one number that came from the command line: the cost in docs/build.md is now the one Gradle measured. Still read from the plugin's source rather than observed: that `check` and `build` run detekt. Neither was invoked. Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/build.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/build.md b/docs/build.md index da80ca3e..90264ea8 100644 --- a/docs/build.md +++ b/docs/build.md @@ -675,9 +675,10 @@ what it would cost on the runner. `detekt` on `check` and on nothing else, so `./gradlew check` and `./gradlew build` run it too. In CI it is a step of its own after the build, not a fourth task in the one invocation — that invocation has no `--continue`, detekt's tasks depend on nothing and would run -first, and a single finding would stop Gradle from scheduling the tests. Measured with -detekt's own command line and the task's arguments, the five modules take 3 to 8 seconds -each, about 25 in all, a JVM start included in each. +first, and a single finding would stop Gradle from scheduling the tests. Measured through +Gradle on a laptop, with no daemon and three workers: `detektBaseline`, the same analysis +of all five modules, took 15 seconds with the configuration computed from scratch, and the +first `detekt`, which also downloaded the plugin and detekt's own jars, took 47. ## The bundled typeface is two files From 9bc992fa38c02d46e44a14256809be613534bc82 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 20:44:10 +0300 Subject: [PATCH 39/43] Name mypy and detekt where CLAUDE.md and the gates skill say what CI runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two branches of the audit each added a CI step: mypy in the server job (#210, with #192's lock) and detekt at the end of the Android job (#210). Each kept its own edit to the description of CI out of the other's way, so after the merge CLAUDE.md's «CI is» line still named neither, and the gates skill named detekt but not mypy. Both now list what ci.yml runs, in its order. Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/skills/gates/SKILL.md | 4 ++-- CLAUDE.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index b9704521..e8f536ba 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -49,8 +49,8 @@ gate.** ## What CI is -`.github/workflows/ci.yml`: ruff, pytest `-n auto`, `./gradlew test`, both assembles, and -`./gradlew detekt` as a step of its own after them. Nothing else. +`.github/workflows/ci.yml`: ruff, `python -m mypy`, pytest `-n auto`, `./gradlew test`, both +assembles, and `./gradlew detekt` as a step of its own after them. Nothing else. ## Two rules about evidence diff --git a/CLAUDE.md b/CLAUDE.md index f3be4172..c9c115e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -98,8 +98,8 @@ the second file exists: while it was alone, every Russian word came from the dev fallback beside digits from the bundle. `FontAxisTest` holds all three halves — the pair draws Russian, neither carries an axis nothing varies, and no file is bundled unnamed. -CI (`.github/workflows/ci.yml`) is: ruff, pytest (`-n auto`), `./gradlew test`, both -assembles. Nothing else. `apk.yml` builds an installable APK on demand or on a `v*` tag; +CI (`.github/workflows/ci.yml`) is: ruff, mypy, pytest (`-n auto`), `./gradlew test`, both +assembles, and `./gradlew detekt` after them. Nothing else. `apk.yml` builds an installable APK on demand or on a `v*` tag; `reminders.yml` is a fallback clock, not the clock (see below). The workflows work — do not edit them casually. The repository is public, so standard runners cost nothing; what the workflows still carry from the months it was private is in `docs/build.md`, "Actions From 05fc5cf27d57aad75032a81be557edd2300a811b Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 21:10:47 +0300 Subject: [PATCH 40/43] Answer detekt where the audit's new Kotlin stands, rather than in the baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the nine branches merged, detekt found twelve things in code this batch wrote — the Keystore seal (#201), the https-only release (#202) and the class-full answer (#199) — that no baseline held, because the baselines were made at 938e59f. docs/build.md says what to do with a new finding: fix it, or suppress it where it stands with the reason, and never grow the baseline with it. So: - fixed: the key size and the GCM tag's byte length are named (`KEY_BITS`, `Byte.SIZE_BITS`); `cleartextVerdict` is one `when` instead of three returns; the https refusal in the sync is caught as `_`, since the result it maps to is the whole of what it says; two lines over the limit are wrapped. - suppressed, with the reason on the annotation: `JoinFailure.ofStatus` (an HTTP status is its own name, and 403, 404 and 429 were already forgiven only by the baseline), `TokenVault.seal` and `open` (each early return is one of the cases the class describes) and the cipher's `open` (one refusal per way a value can fail to be sealed), which were mutation-tested as written and are not rewritten for a count; and `Memberships.kt`, one storage format in fourteen small functions. No behaviour changes. Against the baselines as they were, detekt now fails only on findings #209 moved from one file to another, which the next commit regenerates; `./gradlew test assembleDebug assembleRelease` passes. Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../lumenpearson/lessons/ui/diary/DiarySignInScreen.kt | 6 +++++- .../lumenpearson/lessons/NetworkSecurityConfigTest.kt | 6 +++++- .../lessons/core/data/datastore/AndroidKeystoreKeys.kt | 3 ++- .../lessons/core/data/datastore/Memberships.kt | 4 ++++ .../lessons/core/data/datastore/TokenVault.kt | 5 ++++- .../lessons/core/data/network/CleartextPolicy.kt | 9 ++++++--- .../lessons/core/data/repository/JoinFailure.kt | 1 + .../core/data/repository/TimetableRepositoryImpl.kt | 2 +- 8 files changed, 28 insertions(+), 8 deletions(-) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt index 5371ebdd..a94ebff8 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt @@ -135,7 +135,11 @@ fun DiarySignInScreen( GroupRow { Text( text = correctedString( - if (cleartextLeavesThePhone()) R.string.diary_insecure_server else R.string.server_needs_https, + if (cleartextLeavesThePhone()) { + R.string.diary_insecure_server + } else { + R.string.server_needs_https + }, ), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt index 5fad26c7..de583b49 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/NetworkSecurityConfigTest.kt @@ -60,7 +60,11 @@ class NetworkSecurityConfigTest { fun `neither build trusts a certificate the user installed`() { for ((name, config) in listOf("release" to release, "debug" to debug)) { val anchors = config.single("base-config").children("trust-anchors").single().children("certificates") - assertEquals("$name trusts the system's CAs and nothing else", listOf("system"), anchors.map { it.getAttribute("src") }) + assertEquals( + "$name trusts the system's CAs and nothing else", + listOf("system"), + anchors.map { it.getAttribute("src") }, + ) } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt index 2cd5bd80..7a3a2438 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/AndroidKeystoreKeys.kt @@ -51,7 +51,7 @@ internal class AndroidKeystoreKeys(private val alias: String) : AesGcmTokenCiphe KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) - .setKeySize(256) + .setKeySize(KEY_BITS) .build(), ) return generator.generateKey() @@ -59,5 +59,6 @@ internal class AndroidKeystoreKeys(private val alias: String) : AesGcmTokenCiphe private companion object { const val PROVIDER = "AndroidKeyStore" + const val KEY_BITS = 256 } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt index 614cfba6..811b23b0 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt @@ -1,3 +1,7 @@ +// One concern — how the memberships are written down — in small functions over the +// stored keys; splitting them by count would scatter one format across files. +@file:Suppress("TooManyFunctions") + package com.lumenpearson.lessons.core.data.datastore import androidx.datastore.preferences.core.MutablePreferences diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt index d1ea1b75..7177d815 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/TokenVault.kt @@ -56,6 +56,7 @@ internal class TokenVault(private val cipher: TokenCipher) { * what every install held before this existed, and [TokenSealing] tries * again on the next start. It is the one plaintext this class ever writes. */ + @Suppress("ReturnCount") // Each early answer is a case the paragraph above names. fun seal(token: String): String { if (isSealed(token)) return token val sealed = try { @@ -76,6 +77,7 @@ internal class TokenVault(private val cipher: TokenCipher) { * way it reads a token that was never written, which is what makes a lost * key a sign-in rather than a crash. */ + @Suppress("ReturnCount") // A bare value, one opened before, and the first of two racing readers. fun open(stored: String): String? { if (!isSealed(stored)) return stored opened[stored]?.let { return it.token } @@ -162,10 +164,11 @@ internal class AesGcmTokenCipher(private val keys: Keys) : TokenCipher { return byteArrayOf(iv.size.toByte()) + iv + cipher.doFinal(plaintext) } + @Suppress("ThrowsCount") // One refusal per way a value can fail to be sealed; each reads as «no token». override fun open(sealed: ByteArray): ByteArray { val key = keys.existing() ?: throw GeneralSecurityException("No key to open a sealed token with") val ivSize = sealed.firstOrNull()?.toInt() ?: throw GeneralSecurityException("Empty sealed token") - if (ivSize !in IV_SIZES || sealed.size < 1 + ivSize + TAG_BITS / 8) { + if (ivSize !in IV_SIZES || sealed.size < 1 + ivSize + TAG_BITS / Byte.SIZE_BITS) { throw GeneralSecurityException("Not a sealed token") } val cipher = Cipher.getInstance(TRANSFORMATION) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt index 4c0eb8a7..b5991e2c 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/CleartextPolicy.kt @@ -61,7 +61,10 @@ enum class CleartextVerdict { * is left to the «no address» answer that interceptor already gives. */ fun cleartextVerdict(address: String, policy: CleartextPolicy = CleartextPolicy.Platform): CleartextVerdict { - val url = address.trim().toHttpUrlOrNull() ?: return CleartextVerdict.NOT_CLEARTEXT - if (url.isHttps) return CleartextVerdict.NOT_CLEARTEXT - return if (policy.permits(url.host)) CleartextVerdict.PERMITTED else CleartextVerdict.REFUSED + val url = address.trim().toHttpUrlOrNull() + return when { + url == null || url.isHttps -> CleartextVerdict.NOT_CLEARTEXT + policy.permits(url.host) -> CleartextVerdict.PERMITTED + else -> CleartextVerdict.REFUSED + } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt index d6dbaa40..9a14ab54 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/JoinFailure.kt @@ -100,6 +100,7 @@ sealed class JoinFailure(message: String, cause: Throwable? = null) : * `429`, so the status is the whole answer, and a message we would have * to match on is a Russian sentence somebody will reword. */ + @Suppress("MagicNumber") // A status is its own name; a constant would only rename it. fun ofStatus(code: Int, reason: Throwable? = null): JoinFailure = when (code) { 403 -> InviteOnly 404 -> UnknownCode diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt index cefc9802..19843e17 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/TimetableRepositoryImpl.kt @@ -361,7 +361,7 @@ internal class TimetableRepositoryImpl( } else { SyncResult.Failed("Server returned HTTP ${http.code()}") } - } catch (cleartext: ServerNeedsHttpsException) { + } catch (_: ServerNeedsHttpsException) { // Before the «no address» catch, whose kind this is. SyncResult.NeedsHttps } catch (missing: ServerAddressMissingException) { From 1b0ed1c96e0a7723d0fe91529d14f589ef4246d4 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 21:11:09 +0300 Subject: [PATCH 41/43] Regenerate the detekt baselines after #209 moved code between files A baseline entry names the file, so the findings #209's split carried out of SettingsScreen.kt, WeekScreen.kt and LessonsApp.kt came back as new ones in AboutRows.kt, AppearanceRows.kt, ContentRows.kt, FeelRows.kt, SyncRows.kt, SettingsSection.kt, CalendarGrids.kt, DayPanel.kt and HomeShell.kt. This is `./gradlew detektBaseline` run after the merge with nothing else in the diff, as docs/build.md asks, so every added entry is a removed one under its new file. Four entries go without a successor: SettingsScreen.kt's MatchingDeclarationName, which the split answered, and JoinFailure's 403, 404 and 429, which the previous commit's suppression on `ofStatus` now covers. Refs #209 Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- android/app/detekt-baseline.xml | 41 ++++++++++++++++----------- android/core/data/detekt-baseline.xml | 3 -- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/android/app/detekt-baseline.xml b/android/app/detekt-baseline.xml index 575c72ec..86db1319 100644 --- a/android/app/detekt-baseline.xml +++ b/android/app/detekt-baseline.xml @@ -2,17 +2,18 @@ <SmellBaseline> <ManuallySuppressedIssues/> <CurrentIssues> + <ID>ComplexCondition:DayPanel.kt:!isToday && kind == null && note == null && holiday == null</ID> <ID>ComplexCondition:SignInPage.kt:!retry && !server && !code && handoff == null</ID> - <ID>ComplexCondition:WeekScreen.kt:!isToday && kind == null && note == null && holiday == null</ID> + <ID>CyclomaticComplexMethod:CalendarGrids.kt:@Composable private fun MonthCell</ID> <ID>CyclomaticComplexMethod:ClassCardSheet.kt:@Composable private fun SchoolSearchPanel</ID> <ID>CyclomaticComplexMethod:DayRibbonView.kt:@Composable internal fun DayRibbonView</ID> <ID>CyclomaticComplexMethod:DiaryAccountPage.kt:@Composable fun DiaryAccountPage</ID> <ID>CyclomaticComplexMethod:DiaryEditSheet.kt:@Composable internal fun DiaryEditSheet</ID> <ID>CyclomaticComplexMethod:DiaryProblemText.kt:fun diaryProblemMessage: DiaryProblemMessage</ID> <ID>CyclomaticComplexMethod:DiaryScreen.kt:@Composable fun DiaryScreen</ID> + <ID>CyclomaticComplexMethod:HomeShell.kt:@Composable internal fun HomeShell</ID> <ID>CyclomaticComplexMethod:ImportPage.kt:@Composable internal fun ImportPage</ID> <ID>CyclomaticComplexMethod:ImportPage.kt:@Composable private fun StageRow</ID> - <ID>CyclomaticComplexMethod:LessonsApp.kt:@Composable private fun HomeShell</ID> <ID>CyclomaticComplexMethod:ManagementSheets.kt:@Composable fun FormProblem.asText: String</ID> <ID>CyclomaticComplexMethod:ManagementSheets.kt:@Composable fun ManagementNotice.asText: String</ID> <ID>CyclomaticComplexMethod:OnboardingScreen.kt:@Composable fun OnboardingScreen</ID> @@ -26,22 +27,28 @@ <ID>CyclomaticComplexMethod:SettingsScreen.kt:@Composable fun SettingsSectionScreen</ID> <ID>CyclomaticComplexMethod:SignInPage.kt:@Composable internal fun SignInPage</ID> <ID>CyclomaticComplexMethod:TranslationXml.kt:TranslationXml$fun escape: String</ID> - <ID>CyclomaticComplexMethod:WeekScreen.kt:@Composable private fun MonthCell</ID> + <ID>LongMethod:AppearanceRows.kt:internal fun LazyListScope.appearanceRows</ID> <ID>LongMethod:ClassRows.kt:internal fun LazyListScope.classRows</ID> + <ID>LongMethod:ContentRows.kt:internal fun LazyListScope.contentRows</ID> + <ID>LongMethod:FeelRows.kt:internal fun LazyListScope.feelRows</ID> <ID>LongMethod:NotificationRows.kt:internal fun LazyListScope.notificationRows</ID> - <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.appearanceRows</ID> - <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.contentRows</ID> - <ID>LongMethod:SettingsScreen.kt:private fun LazyListScope.feelRows</ID> <ID>LongMethod:UpdateRows.kt:internal fun LazyListScope.updateRows</ID> <ID>LoopWithTooManyJumpStatements:OnboardingFlow.kt:OnboardingFlow$for</ID> <ID>LoopWithTooManyJumpStatements:ReleaseNotes.kt:for</ID> <ID>LoopWithTooManyJumpStatements:ResourceTranslationTest.kt:ResourceTranslationTest.Companion$for</ID> + <ID>MagicNumber:AboutRows.kt:4</ID> + <ID>MagicNumber:AppearanceRows.kt:3</ID> + <ID>MagicNumber:AppearanceRows.kt:4</ID> + <ID>MagicNumber:AppearanceRows.kt:5</ID> <ID>MagicNumber:BellsSheet.kt:24</ID> <ID>MagicNumber:BellsSheet.kt:4</ID> <ID>MagicNumber:BellsSheet.kt:60</ID> <ID>MagicNumber:ClassCardSheet.kt:3</ID> <ID>MagicNumber:ClassCardSheet.kt:4</ID> <ID>MagicNumber:ClassCardSheet.kt:5</ID> + <ID>MagicNumber:ContentRows.kt:3</ID> + <ID>MagicNumber:ContentRows.kt:4</ID> + <ID>MagicNumber:ContentRows.kt:5</ID> <ID>MagicNumber:DayRibbonView.kt:0.25f</ID> <ID>MagicNumber:DayRibbonView.kt:0.35f</ID> <ID>MagicNumber:DayRibbonView.kt:0.5f</ID> @@ -62,6 +69,9 @@ <ID>MagicNumber:DiarySignInScreen.kt:4</ID> <ID>MagicNumber:DocsBlocks.kt:5</ID> <ID>MagicNumber:DocsScreen.kt:4</ID> + <ID>MagicNumber:FeelRows.kt:3</ID> + <ID>MagicNumber:FeelRows.kt:4</ID> + <ID>MagicNumber:FeelRows.kt:5</ID> <ID>MagicNumber:Formatting.kt:3</ID> <ID>MagicNumber:Formatting.kt:4</ID> <ID>MagicNumber:Formatting.kt:5</ID> @@ -86,18 +96,16 @@ <ID>MagicNumber:RegionFinder.kt:60</ID> <ID>MagicNumber:RegionStep.kt:3</ID> <ID>MagicNumber:RibbonSettingsSheet.kt:4</ID> - <ID>MagicNumber:SettingsScreen.kt:3</ID> - <ID>MagicNumber:SettingsScreen.kt:4</ID> - <ID>MagicNumber:SettingsScreen.kt:5</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.ABOUT$5</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.ALERTS$5</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.APPEARANCE$4</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.CONTENT$3</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.DIARY$4</ID> - <ID>MagicNumber:SettingsScreen.kt:SettingsSection.PERMISSIONS$5</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.ABOUT$5</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.ALERTS$5</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.APPEARANCE$4</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.CONTENT$3</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.DIARY$4</ID> + <ID>MagicNumber:SettingsSection.kt:SettingsSection.PERMISSIONS$5</ID> <ID>MagicNumber:SummaryPage.kt:3</ID> <ID>MagicNumber:SummaryPage.kt:4</ID> <ID>MagicNumber:SummaryPage.kt:5</ID> + <ID>MagicNumber:SyncRows.kt:4</ID> <ID>MagicNumber:TranslationRows.kt:3</ID> <ID>MagicNumber:TranslationRows.kt:4</ID> <ID>MagicNumber:TranslationRows.kt:5</ID> @@ -112,7 +120,6 @@ <ID>MatchingDeclarationName:JoinTestSupport.kt:JoinRig</ID> <ID>MatchingDeclarationName:LegalDocumentSheet.kt:LegalLoad</ID> <ID>MatchingDeclarationName:RootGate.kt:RootScreen</ID> - <ID>MatchingDeclarationName:SettingsScreen.kt:SettingsSection</ID> <ID>MatchingDeclarationName:SupportSheets.kt:SupportSheetState</ID> <ID>MaxLineLength:AppCorrections.kt:StringTable$/** `settings_title` for `R.string.settings_title`, or null for anything that cannot be exported as one `<string>`. */</ID> <ID>MaxLineLength:DiaryPickerViewModelTest.kt:DiaryPickerViewModelTest$private var answer: Result<List<DiarySchool>> = Result.success(listOf(DiarySchool(77, "Школа № 7", "ул. Ленина, 1")))</ID> @@ -177,7 +184,7 @@ <ID>TooManyFunctions:OnboardingViewModel.kt:OnboardingViewModel : ViewModel</ID> <ID>TooManyFunctions:SettingsViewModel.kt:SettingsViewModel : ViewModel</ID> <ID>TooManyFunctions:WeekViewModel.kt:WeekViewModel : ViewModel</ID> - <ID>UnusedParameter:WeekScreen.kt:date: LocalDate</ID> + <ID>UnusedParameter:DayPanel.kt:date: LocalDate</ID> <ID>VariableNaming:CorrectionReachTest.kt:CorrectionReachTest$/** * The imports that draw text without asking about corrections. * * `BasicText` is on the classpath, compiles and draws — nothing uses it * today, and nothing stops the next screen from using it either. */ private val OFFENDING_TEXT_IMPORTS = listOf( "import androidx.compose.material3.Text\n", "import androidx.compose.material3.Text as ", "import androidx.compose.foundation.text.BasicText", )</ID> </CurrentIssues> </SmellBaseline> diff --git a/android/core/data/detekt-baseline.xml b/android/core/data/detekt-baseline.xml index 35807e58..978db6a7 100644 --- a/android/core/data/detekt-baseline.xml +++ b/android/core/data/detekt-baseline.xml @@ -42,9 +42,6 @@ <ID>MagicNumber:EntityMappers.kt:3</ID> <ID>MagicNumber:EntityMappers.kt:4</ID> <ID>MagicNumber:GithubRepositoryImpl.kt:1000L</ID> - <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$403</ID> - <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$404</ID> - <ID>MagicNumber:JoinFailure.kt:JoinFailure.Companion$429</ID> <ID>MagicNumber:LessonsPreferences.kt:LessonsPreferences$7</ID> <ID>MagicNumber:LocaleOverride.kt:33</ID> <ID>MagicNumber:ManageModels.kt:ManageFailure.Companion$401</ID> From 926c7207646b769f3142f29ed8ee46b012bd93bc Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 21:30:56 +0300 Subject: [PATCH 42/43] Say where the work stands after the external audit's twenty-two fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The close-out of this batch, riding in with it. HANDOVER.md's opening names this pull request as the only thing open, what it moves and the twenty-three issues it is meant to close; «What the last session added» describes the audit's fixes, what merging them found (#212, #213, and twelve detekt findings in the batch's own Kotlin), the crashes the machine went through and what was checked after each, the gates, what was left alone and what nothing has verified. #189's section becomes the one before, and #187's moves verbatim to the top of docs/history.md. Section 5 gains what this batch shipped without a device or a Linux install to try it on, and section 6 says that requirements.txt is a lock now. The test counts are taken from runs on this tree and written in their three places: 2063 on the server, 1500 on Android. mypy's module count is 153 after the three splits. The README's table gains detekt, the milestone rows name this pull request and #212–#213, CLAUDE.md's milestone paragraph says what the two open milestones hold, and the pull request template names the head that is and the commands CI runs. The SHA of this close-out's own merge is for the next one to write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .claude/skills/gates/SKILL.md | 2 +- .claude/skills/github-pr/SKILL.md | 2 +- .github/PULL_REQUEST_TEMPLATE.md | 8 +- CLAUDE.md | 13 +- CONTRIBUTING.md | 2 +- HANDOVER.md | 369 ++++++++++++++++++------------ README.md | 7 +- docs/architecture.md | 6 +- docs/history.md | 106 +++++++++ 9 files changed, 348 insertions(+), 167 deletions(-) diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index e8f536ba..8d0dce74 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -15,7 +15,7 @@ the `-r` you test on whatever is newest today, which production does not run. 1. `ruff check app tests scripts migrations` — exactly what CI lints. `ruff check .` from `server/` covers the same tree. -2. `python -m mypy` — one question of all 100 modules, in seconds: does anything reach for an +2. `python -m mypy` — one question of all 153 modules, in seconds: does anything reach for an attribute its type does not have? Every other error code is switched off by name in `pyproject.toml`, with its count and its reason. **In CI** since 27 September 2026, right after ruff — the owner asked for it through that day's audit (#210) — and still worth diff --git a/.claude/skills/github-pr/SKILL.md b/.claude/skills/github-pr/SKILL.md index e887f0d5..cb0d6ff9 100644 --- a/.claude/skills/github-pr/SKILL.md +++ b/.claude/skills/github-pr/SKILL.md @@ -78,7 +78,7 @@ matched pull request's body in full. | 7 | `Dependencies — dependabot bumps` | every dependabot bump; deliberately not a version, and open for good | | 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | PRs #75–#85, #128; issues #98, #100, #105–#108 | | 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | PRs #129, #133, #134, #186, #187, #189; issues #109–#117, #130–#132, #167–#185, #188 — **open**, the first whose work needs an emulator or a phone | -| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | PR #140; issues #135–#139, #141, #145–#165, #190–#211 — **open**, the one being worked on | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | PRs #140, #214; issues #135–#139, #141, #145–#165, #190–#213 — **open**, the one being worked on | All ten were renamed on 25 September 2026: every title now names what the version delivered, and each description names its pull requests and issues. A title quoted from diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index db5eac09..65823088 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -25,7 +25,7 @@ Tick what you checked. If something is broken deliberately, say why. - [ ] The rule did not appear in two places: the bot and `/api/v1/manage` call one function from `app/services/`, not two copies of one decision - [ ] A model change comes with an Alembic revision (the head of the chain is - `app/db.py:EXPECTED_REVISION`, currently `0014`; no `create_all` after `0001`) + `app/db.py:EXPECTED_REVISION`, currently `0017`; no `create_all` after `0001`) - [ ] Nothing is scheduled "in process" on the server: nothing runs between requests on Vercel, and everything on a clock goes through `/api/v1/cron/tick` - [ ] "Now" is taken in the class's time zone — `school_class.tz` on the server, @@ -43,8 +43,10 @@ The summary lines with the numbers are enough. ```text cd server && ruff check app tests scripts migrations → -cd server && python -m pytest -q → -cd android && ./gradlew test → +cd server && python -m mypy → +cd server && pytest -q -n auto → +cd android && ./gradlew test → +cd android && ./gradlew detekt → ``` If `android/` changed: diff --git a/CLAUDE.md b/CLAUDE.md index c9c115e8..cac93046 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 2024 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 2063 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at @@ -59,7 +59,7 @@ Server, from `server/`: there. That shipped once. `tests/test_test_imports.py` now refuses a test module that imports another one at all — a shared fixture belongs in `conftest.py`, which pytest loads by path rather than by import -- **`python -m mypy`** — one question, of all 100 modules, in seconds: does anything reach +- **`python -m mypy`** — one question, of all 153 modules, in seconds: does anything reach for an attribute its type does not have? Configured in `pyproject.toml`, where every other error code is switched off by name with its count and its reason. A CI step since 27 September 2026, right after ruff, because the owner asked for it through that day's @@ -268,9 +268,10 @@ points Hilt does not inject cleanly. inventing a version or leaving the pull request bare. The `github-pr` skill has the numbers, the one tool that sets them, and the two ways this was got wrong first. **Two version milestones are open:** the ninth, `v0.8.0 — On-device checks, 89-region e-diary - survey`, holds issues #109–#117, the first work that needs an emulator or a phone; the - tenth, `v0.9.0 — NetSchool e-diary, onboarding via the school's diary`, holds PR #140 and - its issues. All ten were renamed on 25 September 2026, so a title quoted from before then + survey`, holds #109–#117 and what #186's walk on an emulator found, the first work that + needs an emulator or a phone; the tenth, `v0.9.0 — NetSchool e-diary, onboarding via the + school's diary`, holds PR #140 and its issues, and the external audit of 27 September + (#190–#213). All ten were renamed on 25 September 2026, so a title quoted from before then finds nothing when searched. - **A defect that is found gets an issue, always, and before it gets a fix.** The rule is new and it is not optional: the moment an audit, a review, a CI failure or a reader finds @@ -295,7 +296,7 @@ points Hilt does not inject cleanly. - **There are issues now, and until #85 there were none.** Forty-two were opened in one go to give the history and the backlog a shape the milestones alone could not: twenty-three closed, describing what was built and what each bug sweep found, and nineteen open, which - are the whole of what is left. Read the open ones before planning a batch — several say + were then the whole of what was left. Read the open ones before planning a batch — several say what was *deliberately* left and why, so that a later session does not re-discover a decision as if it were an oversight. The labels are `type:` (feature, bug, chore, research, decision, epic), `area:` (android, widget, server, bot, db, ci, docs, design, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8e7a1cb5..0b9d0917 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ cp .env.example .env # BOT_TOKEN and OWNER_IDS are your own | Command | What it does | | --- | --- | | `ruff check app tests scripts migrations` | lints the server — exactly what CI runs | -| `python -m mypy` | one question of all 100 modules: does anything reach for an attribute its type does not have? | +| `python -m mypy` | one question of all 153 modules: does anything reach for an attribute its type does not have? | | `pytest -q -n auto` | the server tests, 1944 of them, in about two minutes — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | | `python -m pytest -q tests/test_schedule.py -k parity` | one file, one test | | `python -m uvicorn app.main:app --reload` | run the server | diff --git a/HANDOVER.md b/HANDOVER.md index 5aaac2d6..572cd1c4 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -7,36 +7,41 @@ What every batch before the last two added is in [docs/history.md](docs/history. newest first. Last updated: **27 September 2026**. **PRs #63 through #85, #128, #129, #133, #134, #140, -#166, #186 and #187 are merged**; `main` is at `2a408d8`, the merge of #187, and `dev` is -level with it. **The only thing open is the pull request carrying this paragraph, #189**, -from `agents/widget-small-sizes`, on milestone 9, `v0.8.0 — On-device checks, 89-region -e-diary survey`. It fixes the last defect #186 filed and left open (#174, the widget's two -smallest sizes) and one found while checking that fix on the emulator (#188, a widget that -did not follow its own settings). The section «What the last session added» below is that -batch. +#166, #186, #187 and #189 are merged**; `main` is at `938e59f`, the merge of #189, and `dev` +is level with it. **The only thing open is the pull request carrying this paragraph, #214**, +from `agents/audit-batch-190-211`, on milestone 10, `v0.9.0 — NetSchool e-diary, onboarding +via the school's diary`. It fixes the twenty-two issues an external audit filed on 27 +September (#190–#211) and one found while merging the nine branches that fixed them (#213). +The section «What the last session added» below is that batch. The SHA of its own merge is for the next close-out to write. -**What #189 moves.** Android, all of it in the widget: -- The next school day's plan keeps its count and its time and shortens the subject: «4 урока - · Алгеб… в 08:30», where a phone's 2×2 read «4 урока · Алгебра в 08:…». -- `SMALL_TALL`, which is what that 2×2 really is, lists three homework subjects after school - instead of two. -- At any font above the default, the 2×1 draws the count as a bare figure, «ДЗ на завтра 3», - where it read «Д… 3 предмета» (#174). -- Changing the language, «Прогресс в виджете» or the teacher switch redraws the widget at - once instead of whenever something else next woke it (#188). - -No server change, no schema change; `EXPECTED_REVISION` is still `0017`. - -**Once #189 merges, two issues are meant to close:** #174 and #188. That leaves no defect -open that a session can fix. Of the device epic **#109**, **#111** and **#113** stay open for -what only a phone can say, and **#112** (a macrobenchmark module) was not started. What a -merge closes is decided by the `Closes` lines in the pull request body and in the commit -messages, not by this paragraph — read them against this list before merging. - -**#187 closed the four issues it named** (#110, #171, #175, #176), read back from GitHub on -27 September, as #186 closed its twenty-one. +**What #214 moves.** +- The server: the compose file and its container (#190, #191, #195), the diary sign-in page + (#193, #196), «Сетевой город»'s «today» (#198), a cap on the phones one class code mints + (#199), no interactive API docs on Vercel (#200), one way to take naive UTC (#197), and a + phone invite that cannot be redeemed twice (#194). +- The server's shape: services below the bot (#205), the three largest files split (#208), + one implementation of every operation both shells perform (#206), one role gate for + «⚙️ Класс» (#207), and documents that say two shells write (#204). +- The build: `requirements.txt` is a lock (#192), and CI runs mypy and detekt (#210). +- Android: requests signed from memory (#203), bearers sealed by the Keystore (#201), https + only in a release build (#202), and four files split with the `Graph` kept out of + composables (#209). +- This file kept to where the work stands, its history in `docs/history.md` (#211). + +No schema change; `EXPECTED_REVISION` is still `0017`. **The first deploy after the merge is +the first install of the lock** on Linux and Python 3.12: if Vercel cannot install it, the +build fails and the deployment before it keeps serving. + +**Once #214 merges, twenty-three issues are meant to close:** #190–#211 and #213. **#212** +stays open: a test that fails at random on Windows and passes on CI. Of the device epic +**#109**, **#111** and **#113** stay open for what only a phone can say, and **#112** (a +macrobenchmark module) was not started. What a merge closes is decided by the `Closes` lines +in the pull request body and in the commit messages, not by this paragraph — read them +against this list before merging. + +**#189 closed the two issues it named** (#174, #188), read back from GitHub on 27 September. **The code expects head `0017`, and production is at `0017` since 26 September 2026 at 12:26 UTC.** `EXPECTED_REVISION` in `app/db.py` is `0017`, pinned to the real head by @@ -132,22 +137,174 @@ section describes, **#118–#122** are the owner's alone, and **#126** collects things carried deliberately, so that a later session does not re-discover a decision as if it were an oversight. -**Seventy-five have been filed since.** #130 was the survey #134 closed, and #131 and #132 +**Seventy-seven have been filed since.** #130 was the survey #134 closed, and #131 and #132 the two defects #133 closed. #135 is the owner's decision about the second diary; #136–#139 and #141 are the work #140 carries; #142–#144 are its deliberate follow-ups, on no milestone; and #145–#165 are the defects found on its branch, each filed before its fix. #167–#185 are what #186's walk on an emulator found and what the owner asked for that night, and #188 what #189 found; all twenty are closed. #190–#211 are the external audit of -27 September 2026, on milestone 10. +27 September 2026, on milestone 10, and #212 and #213 what merging its fixes found. Labels are `type:` (feature, bug, chore, research, decision, epic), `area:`, `status:` (now, next, someday, done) and `needs:` (device, owner). **A session cannot create a GitHub Project board** — Projects v2 is GraphQL-only and the toolset here is REST — so the board is the owner's to make, and these labels are what its views filter on. -## What the last session added: the widget's two smallest sizes, and a widget that did not follow its settings +## What the last session added: the external audit of 27 September, #190–#211 + +Open as #214, from `agents/audit-batch-190-211`, on milestone 10. An external audit of the +repository filed twenty-two issues on 27 September 2026. Nine agents fixed them in parallel, +each on a branch of its own in a worktree of its own, and this branch merges the nine and +adds four commits found while merging them. Every defect was fixed test-first — the new +test run red against the old code, then green — and every refactor changes no behaviour, +with the existing tests as its proof and, for the three server splits, an OpenAPI dump and +the aiogram handler order compared before and after. + +### The server + +- **#190.** `docker-compose.yml` takes the Postgres password from `POSTGRES_PASSWORD` and + refuses to start without one, where it carried the literal `lessons` in a public + repository. `docs/deploy.md` says where the value goes, that it is spliced into a URL + unescaped, and that a volume made under the old password keeps it. +- **#191.** A compose deployment hands the server every setting it reads, so the diary, the + tick and the calendar links work there; before, the list stopped at `TIMEZONE`. +- **#195.** The server container runs as an unprivileged user, and its package is installed + after its code is copied, so it is whole in site-packages rather than found by accident on + the working directory. +- **#196.** `/diary/signin` sends `frame-ancestors 'none'` and `X-Frame-Options: DENY` on all + seven answers it draws, so no other site can frame the one page that takes a password. +- **#193.** Every page after a spent sign-in ticket says the link is spent and names the + bot's buttons that make the next one, where it said «Попробуйте ещё раз». +- **#198.** A «Сетевой город» session that will not open reads «today» in Moscow, not on the + host's clock, which on Vercel was yesterday from midnight to three. +- **#199.** A class code stops minting phones at 300 live devices and answers `409` with a + Russian `detail`, which the join screen words as «class full»; the throttle forgives it, + as it does the invite-only `403`. +- **#200.** `/docs`, `/redoc` and `/openapi.json` are served locally and not on Vercel. +- **#197.** Naive UTC is taken one way everywhere, and never through the deprecated + `datetime.utcnow()`. +- **#194.** A phone invite from the bot is spent with one conditional `UPDATE … WHERE used_at + IS NULL`, so a retried update cannot redeem it twice. +- **#205.** Nothing under `app/services/` imports `app.bot`, directly or through another + module. The role ladder moved to `services/roles.py` and the words both shells print to + `app/wording.py`; `bot/roles.py` and `bot/render.py` re-export them, and + `tests/test_service_layering.py` follows every import chain to hold the rule. +- **#208, #206, #207.** The three server files one reader could no longer hold are + packages: `schemas.py` (1573 lines) is seventeen modules behind the same import; + `bot/handlers/manage.py` (3434) and `api/manage.py` (1516) are one module per screen, over + a new `services/manage/` that holds the one implementation of every operation both shells + perform (#206). Where the two copies had drifted, one rule now answers for both: the bot's + time-zone picker writes its audit line, a removed colour is «убран» from both sides, the + bot no longer logs a second revoke, its import log says «перестали звонить N», and a + switch to the value already in force logs nothing. `@needs(Role.X)` gates the 72 + «⚙️ Класс» handlers that each carried their own copy of the role check (#207), and no + `select(` is left in them. +- **#204.** `CLAUDE.md`, `docs/architecture.md`, `docs/bot.md`, `AGENTS.md` and the Copilot + instructions say that two shells write over one set of services, where they said the API + only reads. +- **#192.** `requirements.txt` is a lock: 34 exact pins, transitive ones included, compiled by + uv for CPython 3.12 on Linux from a new `requirements.in` that mirrors pyproject's runtime + dependencies. CI installs from it, `test_requirements_mirror.py` holds the two level, and + dependabot's root entry is `uv`. +- **#210, the server half.** `python -m mypy` is a CI step between ruff and the tests. + +### Android + +- **#203.** Every request is signed from credentials held in memory and refreshed on IO, so + no interceptor blocks on DataStore and no coroutine calls `runBlocking`. +- **#201.** The class and diary bearers are sealed in the preferences file with an + AES-256-GCM key the Android Keystore holds. A DataStore migration seals what an older + install left in plain text, once; a token that will not open — a restore onto another + phone, a wiped Keystore — reads as no token, and the phone lands on the join screen or the + diary's sign-in form. +- **#202.** A release build talks to the server over https only, except to `localhost` and + `127.0.0.1`; a `src/debug` override keeps cleartext for development. An `http://` address + is refused where it is typed, and one kept from an older version is named as needing https + on the join screen, the sync message and the diary's forms. The packaged release APK was + read back with aapt2 to confirm which file it carries. +- **#209.** The four Android files one reader could no longer hold — the settings pages, the + calendar, the home shell and the diary — are split, and composables no longer reach the + `Graph`: the diary home's first refresh belongs to its view model. +- **#210, the Kotlin half.** detekt 2.0.0-alpha.6 reads all five modules and fails CI on any + finding the module's `detekt-baseline.xml` does not hold. The baselines were regenerated + on this branch after the merge, because #209 moved code between files. + +### The documents + +- **#211.** `HANDOVER.md` went from 337 KB to about 95 KB: what every batch before the last + two added moved verbatim to `docs/history.md`, and a line check found none of the 4,077 + lost. The README and this file stopped contradicting GitHub and #186's walk. + +### Found while merging + +- **#213.** The test that every document names the schema head walked `.claude/` into the + agents' worktrees and read nine stale copies of this file; it failed every local run beside + them, and never on CI. It reads only this checkout's documents now. +- **#212**, filed and **not** fixed: `test_a_parallel_burst_from_one_address_cannot_pass_the_limit` + fails at random on Windows with SQLite's «database is locked», two runs in three when run + alone. It passes on CI's Linux. +- The Android comments that named `server/app/schemas.py` name the module each model lives in + now, the architecture tree shows the package and `app/wording.py`, and the API takes the + shared words from `app.wording` rather than from the bot. + +### The machine crashed under the batch + +The machine running the agents blue-screened five times on 26–27 September. Each crash +zero-filled whatever was being written: a git index, a source file in the middle of a +mutation test, Kotlin incremental caches, fifty-five units of `~/.gradle` (the detekt plugin +among them) and one file of a rebuilt venv. Every worktree was checked before work resumed: +no source file was damaged, the mutated files matched their backups byte for byte, and what +was zero-filled was deleted and rebuilt. Two runs of the suite gave false failures of their +own — every test that spawns `python.exe` exited `0xC0000142` — from a run that outlived the +agent that started it; they were run again from a live shell and passed. + +### Gates + +On `1b0ed1c` with this close-out's documents on top: `pytest -q -n 3` **2063** passed, none +failed — thirty-nine more than `938e59f`'s 2024; `ruff` clean; `python -m mypy` clean over +153 source files, where it was 100 before the three splits. `./gradlew test` **1500** +(`:core:model` 125, `:core:data` 570, `:core:designsystem` 112, `:widget` 123, `:app` 570), +forty-one more than #189's 1459; `assembleDebug` and `assembleRelease` build; `./gradlew +detekt` passes against the regenerated baselines. Every branch ran its own gates before the +merge, and the merge was checked again as a whole. #201, #202 and #203 were also +mutation-tested: every mutation of each fix turned a test red. + +**The baselines hold only what was already there.** Merged, detekt found twelve things in +this batch's own Kotlin that no baseline held; `05fc5cf` fixes or suppresses each where it +stands, with the reason on the annotation, and `1b0ed1c` regenerates the baselines with +nothing else in the diff, so every entry it adds is one it removes under #209's new file. + +### What was deliberately left alone + +- `server/Dockerfile` still runs `pip install .`, so a container gets pyproject's floors, not + the lock. The dev tools, uvicorn, aiosqlite and alembic are not locked either, so a new ruff + or mypy can still turn CI red on its own. +- `/api/v1/edit` and the bot's day-to-day handlers still write different audit actions for the + same change (`day.set` against `dayoverride.set`); #206 was «⚙️ Класс» and `/manage` only. +- The API and `main.py` still import `app.bot.bot` inside functions, to build a bot on demand. + The layer rule binds the services; the API is a shell. +- The first run's school search still words a kept `http://` address as «no server is set», + and the diary's sign-in form in a release build refuses `http://127.0.0.1` although the + request would go through; both sit in screens another branch was splitting. +- `9181796`'s message says detekt was never run through Gradle; `44d49e2` records that it + has been. +- The six drifts #206 unified are named in its commit body and carry no issues of their own. + +### What nobody has verified in this batch + +- #201's Keystore key and #202's network configuration have not run on a device: how the + platform reads the two configuration files is what its documentation says, and the release + APK has not been pointed at a real server. +- The lock has not been installed on Linux or on Python 3.12, only resolved for them; the + first Vercel deploy after the merge is its first install. Dependabot's `uv` entry has not + run, and nothing here runs Docker. +- `./gradlew check` and `build` running detekt is read from the plugin's source. +- Why two background runs could not start child processes (`0xC0000142`) was not found; it + did not happen from a live shell. + +## What the session before it added: the widget's two smallest sizes, and a widget that did not follow its settings -Open as #189, from `agents/widget-small-sizes`, on milestone 9. Two commits, one per issue, +Merged as `938e59f`, #189 from `agents/widget-small-sizes`, on milestone 9. Two commits, one per issue, each checked on the API 37 emulator against a local server seeded with `seed_demo`, on a Sunday, so on the widget's day-off layout. @@ -211,112 +368,6 @@ gates were not run. - At 195 dp the whole «4 урока · Алгебра в 08:30» would fit, and the rung's budget shortens it anyway, because the same rung serves 110 dp. -## What the session before it added: the first instrumented tests, and three defects the walkthrough left - -Merged as `2a408d8`. Four commits from the night of 26–27 September and one from the -session that picked them up. - -- **#110, the first `androidTest`.** `ToolbarOnDeviceTest` in `:core:designsystem` holds a - tab past the device's own long-press timeout and drags it 0.7 and 0.4 of a slot in one - touch, in the device's own pixels: the first moves it exactly one place and is not taken - for a tap, the second puts it back. A third opens the mode, taps the page and checks that - `ArrangingDismissLayer` closes it and passes nothing through. The JVM tests drag ten - thousand pixels so that Robolectric's densities cannot move the answer; this is the half - that asks where half a slot really is. The Compose BOM's `ui-test-junit4` brings Espresso - 3.5.0, which reaches for `InputManager.getInstance` by reflection — API 34 removed it and - every test failed at its first `onIdle` — so Espresso 3.7.0 and runner 1.7.0 are pinned in - the catalog, each the `<release>` in Google Maven's metadata on 27 September. Run with - `./gradlew :core:designsystem:connectedDebugAndroidTest`; **not in CI, on purpose**, since - CI has no device. `CLAUDE.md`, `docs/build.md`, the README and `docs/architecture.md` say so. -- **#175, the sign-in forms said «по HTTPS, прямо в дневник» twice.** With the diary's host - known, the sentence naming it now also says the password goes nowhere else, and the - paragraph under it is only what happens to the session (`diary_password_session`, new, with - its English twin). Without a host the general notice stands alone, as before. One function, - `passwordPrivacyParagraphs`, decides the paragraphs for both forms — the diary's own and - the first run's — so they cannot drift apart again. `PasswordPrivacyTest` counts «HTTPS» - across what is drawn, in both languages. -- **#176, the join screen kept an error about an address it no longer used.** - `JoinViewModel` keeps each error with the server address it was an answer from and shows - it only while that is still the address, which covers a change from the screen's own link - and one made in the settings alike. A code of the wrong length is about the code, not a - server, and stays. `JoinErrorAddressTest` fails on the old behaviour. The defect did not - reproduce the second time on the emulator, so the fix rests on the code path and the test. -- **#171, a join fetched the whole school year twice.** The join screen's own refresh and the - one-off worker the class switch schedules both asked before either had stored an `ETag`. - Syncs of one class's year now go through `SingleFlight`, keyed like the tag by class and - year: a second caller while the first is on the wire takes the first one's answer. Nothing - is remembered after a run, so a later refresh asks again, and a waiter whose owner was - cancelled starts its own instead of inheriting the cancellation. The flight is per - repository object, and that is enough: `LessonsContainer.timetable` is one lazy per - process, and WorkManager runs the worker in the app's process. `ConcurrentSyncTest` holds - all three cases. **One hardening was added at review, before the push:** a run that has - ended is never joined, because a waiter retrying after a cancelled owner could otherwise - find the same finished run under the key, again and again, until the owner took the lock - back. None of the three tests reproduces that window — under the test dispatchers the - owner always finishes its cleanup first — so it is argued from the code, not shown red. - -### The branch was nearly lost - -The session that picked this branch up found `refs/heads/agents/first-android-test` as 41 -NUL bytes, last written in the same second as the fourth commit: `git` printed «ignoring -broken ref», the worktree under `.claude/worktrees/` reported `0000000 (error)`, and the -branch existed on no remote. A file of zeros where a write should be is what a write that -never reached the disk leaves behind, but what interrupted it here is not known. The commits -themselves were intact as dangling objects. The branch's own reflog, -`.git/logs/refs/heads/agents/first-android-test`, still named the tip on its last line, and -writing that SHA back into the ref restored the branch and the worktree whole. **If this -happens again, read the reflog before anything else** — `git fsck --dangling` finds the -commits too, but not which of them was the tip. - -The session's move between machines left a `Teleport auto-stash` on the stack (`stash@{0}`, over `c26eace`), and it -is **deliberately not applied**: it holds what the IDE generated, not work — a -`gradle-daemon-jvm.properties` and the foojay resolver plugin from Studio's «update daemon -JVM», a root `gradle.properties` with a heap setting, a JVM crash log from a Gradle daemon -that died after 27 minutes on 26 September, and the spell checker's American spellings over -five of `models.py`'s comments, which are British on purpose. It is the owner's to drop. - -### Gates - -On `f787357`, this branch's last commit before the close-out: `./gradlew test` **1446** -(`:core:model` 125, `:core:data` 540, `:core:designsystem` 112, `:widget` 113, `:app` 556), -eight more than #186's 1438 — `ConcurrentSyncTest` 3, `JoinErrorAddressTest` 2, -`PasswordPrivacyTest` 3. `assembleDebug` and `assembleRelease` build (JDK 21; the 18 -Kotlin warnings they print are all in files this branch does not touch). -`./gradlew :core:designsystem:connectedDebugAndroidTest` on the API 37 emulator: **3 of 3**, -11.5 s. The server was not touched, so its gates were not run. - -Gradle on this machine needs `JAVA_HOME` pointed at `jdk-21.0.11.10-hotspot` for a command -line: the variable says JDK 17, and `android/.gradle/config.properties`, which names 21, is -read by Studio alone. - -### On the emulator - -This branch's debug build, installed over the old one with its data cleared, walked the -first run in English against a local server seeded with `seed_demo`, and joined «9А» with -`DEMO24`. The server's log for the join: `POST /api/v1/join` 200, then `GET -/api/v1/bundle?start=2026-09-01&days=273` **200**, then the same **304**, one after the other -on one connection. So the year was downloaded once — but the second sync began after the -first had finished and stored its `ETag`, so this join never produced the overlap the fix -coalesces, and on a device that half is still shown only by the test. - -### What was deliberately left alone - -- **#174**, the two small widget sizes, was not started. -- **`createComposeRule` is deprecated** in the Compose version this project builds with, in - favour of `androidx.compose.ui.test.junit4.v2.createComposeRule`, which runs effects on a - `StandardTestDispatcher` rather than an unconfined one. The device test uses the old one, - as every JVM test here does; moving them is one change for all of them, with the clock - rules in `CLAUDE.md` read again first, not something to start in one file. - -### What nobody has verified in this batch - -That two **overlapping** syncs make one request is shown by `ConcurrentSyncTest` against a -fake server, not on a device (above). The arranging gesture's device tests have run on one -emulator, at 480 dpi — a phone at another density is the question they exist to answer and -has not been asked. #176's defect never reproduced on demand. #175's single sentence was not -looked at on a screen: reaching a password form needs a region's diary to answer. Nothing -here changes what #186 could not answer: a thumb, a haptic, a real GPU, a real launcher. - ## The milestones **The milestones as they are now.** The owner renamed all nine on 25 September 2026, so that @@ -337,7 +388,7 @@ maps them. The | 7 | `Dependencies — dependabot bumps` | `Dependencies` | open, for good | every dependabot bump; deliberately not a version | | 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | `v0.7.0 — Оптимизация` | closed | PRs #75–#85, #128; issues #98, #100, #105–#108 | | 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | `v0.8.0 — On a device` | open | PRs #129, #133, #134, #186, #187, #189; issues #109–#117, #130–#132, #167–#185, #188 — the first whose work needs an emulator or a phone, and #186 the first done on one | -| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140 (merged); issues #135–#139, #141, #145–#165, #190–#211 (the external audit of 27 September) | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PRs #140 (merged), #214; issues #135–#139, #141, #145–#165, #190–#211 (the external audit of 27 September), #212, #213 | **#142, #143 and #144 are on no milestone, deliberately**: two follow-ups and a decision that #140 left alone on purpose, which belong to whichever version takes them up. @@ -533,7 +584,22 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i its dependency conditions are what they claim — `service_completed_successfully` before the API starts. Nobody has watched the stack come up, nobody has seen `alembic upgrade head` run inside the image, and nobody has confirmed that the revisions - the Dockerfile now copies are the ones it needs. + the Dockerfile now copies are the ones it needs. #190, #191 and #195 changed the file and + the image again — a password the stack refuses to start without, every setting passed + through, a non-root user — and are read by `test_compose.py` and `test_dockerfile.py`, + not by a container. +- **#201's Keystore seal and #202's https-only release have never run on a device.** The + key is made and used through `AndroidKeystoreKeys`, which `SealedTokensTest` replaces + with a key held in memory under the same `AesGcmTokenCipher`; the migration that seals + an older install's plain-text tokens is tested that way too, and nobody has upgraded a + phone that held one. Which network configuration a + build carries was read out of both packaged APKs with aapt2, and how the platform then + applies it is its documentation's word. The release APK has not been pointed at a + real server. +- **The lock (#192) has been resolved for Linux and Python 3.12, never installed there.** + Every run here was on Windows and Python 3.13. The first install of it on the + deployment's own platform is the first Vercel deploy after #214, and dependabot's `uv` + entry has not opened a pull request yet. - **No Compose test was actually made to hang**, so `MarqueeClockTest` — the guard #83 added for the trap that costs a whole Gradle run — is reasoned from `MarqueeText`'s `Int.MAX_VALUE` iteration count and from the list of files that call `createComposeRule`. @@ -986,13 +1052,17 @@ already shipped twice. The tabs are still removed from the composition rather th ### The dependency mirror -The root `requirements.txt` and `server/pyproject.toml` have to carry the same floors. -Dependabot edits **the root file only** — which is how `main` drifted -(`sqlalchemy>=2.0.52` against `>=2.0.30`, `pydantic-settings>=2.15.0` against `>=2.4`). Tests -hold this now rather than attentiveness: `tests/test_requirements_mirror.py` checks both -directions and the versions themselves, and the three packages deliberately absent from the -bundle (`uvicorn`, `aiosqlite`, `alembic`) are listed there with their reasons. A floor -raised in one file only is green CI and a function that installs the old one. +The root `requirements.txt` is a **lock** since #192: exact pins for the whole tree, +compiled by uv for CPython 3.12 on Linux from the root `requirements.in`, whose header names +the command. `requirements.in` and `server/pyproject.toml` have to carry the same floors. +Dependabot edits **the root files only** — which is how `main` once drifted +(`sqlalchemy>=2.0.52` against `>=2.0.30`, `pydantic-settings>=2.15.0` against `>=2.4`) — and +its `uv` entry raises the floor in `requirements.in` and recompiles the lock, so pyproject is +still raised by hand. Tests hold this rather than attentiveness: +`tests/test_requirements_mirror.py` checks the input against pyproject in both directions, +that every lock line is one pin inside its floor, that the lock was regenerated after the +input changed, and that it is closed on Linux/3.12; the three packages deliberately absent +from the bundle (`uvicorn`, `aiosqlite`, `alembic`) are listed there with their reasons. ### Week parity @@ -1286,8 +1356,9 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 2024 tests, ~4 min on CI, ~10 on Windows -cd server && python -m mypy # clean, 100 modules -cd android && ./gradlew test # 1459 tests across the five modules +cd server && pytest -q -n auto # 2063 tests, ~4 min on CI, ~10 on Windows +cd server && python -m mypy # clean, 153 modules +cd android && ./gradlew test # 1500 tests across the five modules +cd android && ./gradlew detekt # nothing beyond the five baselines cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` diff --git a/README.md b/README.md index 752c1da6..76be6c3a 100644 --- a/README.md +++ b/README.md @@ -205,9 +205,10 @@ Read this before planning a release. | Check | Result | | --- | --- | | `ruff check app tests scripts migrations` | clean | -| `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 2024 tests, green, about four minutes — the command CI runs | -| `./gradlew test` | 1459 tests, green, all five modules | +| `python -m mypy` | clean, 153 modules — asks whether anything reaches for an attribute that does not exist | +| `pytest -q -n auto` | 2063 tests, green, about four minutes — the command CI runs | +| `./gradlew test` | 1500 tests, green, all five modules | +| `./gradlew detekt` | no finding beyond each module's baseline, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | | `./gradlew :core:designsystem:connectedDebugAndroidTest` | 3 tests, green on an API 37 emulator — on demand only, never in CI, which has no device | diff --git a/docs/architecture.md b/docs/architecture.md index 89fda12e..81088208 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -783,9 +783,9 @@ with the host. ## Testing -2024 tests on the server, 1459 on Android; `pytest -q -n auto` and `./gradlew test`, both -offline, both in CI. On Android that is `:core:model` 125, `:core:data` 543, -`:core:designsystem` 112, `:widget` 123, `:app` 556. +2063 tests on the server, 1500 on Android; `pytest -q -n auto` and `./gradlew test`, both +offline, both in CI. On Android that is `:core:model` 125, `:core:data` 570, +`:core:designsystem` 112, `:widget` 123, `:app` 570. The table below is the load-bearing part of that rather than the whole of it: diff --git a/docs/history.md b/docs/history.md index 532cfbf9..37ef51a2 100644 --- a/docs/history.md +++ b/docs/history.md @@ -27,6 +27,112 @@ the conventions of the file it was written in: --- +## What the batch before added: the first instrumented tests, and three defects the walkthrough left + +Merged as `2a408d8`. Four commits from the night of 26–27 September and one from the +session that picked them up. + +- **#110, the first `androidTest`.** `ToolbarOnDeviceTest` in `:core:designsystem` holds a + tab past the device's own long-press timeout and drags it 0.7 and 0.4 of a slot in one + touch, in the device's own pixels: the first moves it exactly one place and is not taken + for a tap, the second puts it back. A third opens the mode, taps the page and checks that + `ArrangingDismissLayer` closes it and passes nothing through. The JVM tests drag ten + thousand pixels so that Robolectric's densities cannot move the answer; this is the half + that asks where half a slot really is. The Compose BOM's `ui-test-junit4` brings Espresso + 3.5.0, which reaches for `InputManager.getInstance` by reflection — API 34 removed it and + every test failed at its first `onIdle` — so Espresso 3.7.0 and runner 1.7.0 are pinned in + the catalog, each the `<release>` in Google Maven's metadata on 27 September. Run with + `./gradlew :core:designsystem:connectedDebugAndroidTest`; **not in CI, on purpose**, since + CI has no device. `CLAUDE.md`, `docs/build.md`, the README and `docs/architecture.md` say so. +- **#175, the sign-in forms said «по HTTPS, прямо в дневник» twice.** With the diary's host + known, the sentence naming it now also says the password goes nowhere else, and the + paragraph under it is only what happens to the session (`diary_password_session`, new, with + its English twin). Without a host the general notice stands alone, as before. One function, + `passwordPrivacyParagraphs`, decides the paragraphs for both forms — the diary's own and + the first run's — so they cannot drift apart again. `PasswordPrivacyTest` counts «HTTPS» + across what is drawn, in both languages. +- **#176, the join screen kept an error about an address it no longer used.** + `JoinViewModel` keeps each error with the server address it was an answer from and shows + it only while that is still the address, which covers a change from the screen's own link + and one made in the settings alike. A code of the wrong length is about the code, not a + server, and stays. `JoinErrorAddressTest` fails on the old behaviour. The defect did not + reproduce the second time on the emulator, so the fix rests on the code path and the test. +- **#171, a join fetched the whole school year twice.** The join screen's own refresh and the + one-off worker the class switch schedules both asked before either had stored an `ETag`. + Syncs of one class's year now go through `SingleFlight`, keyed like the tag by class and + year: a second caller while the first is on the wire takes the first one's answer. Nothing + is remembered after a run, so a later refresh asks again, and a waiter whose owner was + cancelled starts its own instead of inheriting the cancellation. The flight is per + repository object, and that is enough: `LessonsContainer.timetable` is one lazy per + process, and WorkManager runs the worker in the app's process. `ConcurrentSyncTest` holds + all three cases. **One hardening was added at review, before the push:** a run that has + ended is never joined, because a waiter retrying after a cancelled owner could otherwise + find the same finished run under the key, again and again, until the owner took the lock + back. None of the three tests reproduces that window — under the test dispatchers the + owner always finishes its cleanup first — so it is argued from the code, not shown red. + +### The branch was nearly lost + +The session that picked this branch up found `refs/heads/agents/first-android-test` as 41 +NUL bytes, last written in the same second as the fourth commit: `git` printed «ignoring +broken ref», the worktree under `.claude/worktrees/` reported `0000000 (error)`, and the +branch existed on no remote. A file of zeros where a write should be is what a write that +never reached the disk leaves behind, but what interrupted it here is not known. The commits +themselves were intact as dangling objects. The branch's own reflog, +`.git/logs/refs/heads/agents/first-android-test`, still named the tip on its last line, and +writing that SHA back into the ref restored the branch and the worktree whole. **If this +happens again, read the reflog before anything else** — `git fsck --dangling` finds the +commits too, but not which of them was the tip. + +The session's move between machines left a `Teleport auto-stash` on the stack (`stash@{0}`, over `c26eace`), and it +is **deliberately not applied**: it holds what the IDE generated, not work — a +`gradle-daemon-jvm.properties` and the foojay resolver plugin from Studio's «update daemon +JVM», a root `gradle.properties` with a heap setting, a JVM crash log from a Gradle daemon +that died after 27 minutes on 26 September, and the spell checker's American spellings over +five of `models.py`'s comments, which are British on purpose. It is the owner's to drop. + +### Gates + +On `f787357`, this branch's last commit before the close-out: `./gradlew test` **1446** +(`:core:model` 125, `:core:data` 540, `:core:designsystem` 112, `:widget` 113, `:app` 556), +eight more than #186's 1438 — `ConcurrentSyncTest` 3, `JoinErrorAddressTest` 2, +`PasswordPrivacyTest` 3. `assembleDebug` and `assembleRelease` build (JDK 21; the 18 +Kotlin warnings they print are all in files this branch does not touch). +`./gradlew :core:designsystem:connectedDebugAndroidTest` on the API 37 emulator: **3 of 3**, +11.5 s. The server was not touched, so its gates were not run. + +Gradle on this machine needs `JAVA_HOME` pointed at `jdk-21.0.11.10-hotspot` for a command +line: the variable says JDK 17, and `android/.gradle/config.properties`, which names 21, is +read by Studio alone. + +### On the emulator + +This branch's debug build, installed over the old one with its data cleared, walked the +first run in English against a local server seeded with `seed_demo`, and joined «9А» with +`DEMO24`. The server's log for the join: `POST /api/v1/join` 200, then `GET +/api/v1/bundle?start=2026-09-01&days=273` **200**, then the same **304**, one after the other +on one connection. So the year was downloaded once — but the second sync began after the +first had finished and stored its `ETag`, so this join never produced the overlap the fix +coalesces, and on a device that half is still shown only by the test. + +### What was deliberately left alone + +- **#174**, the two small widget sizes, was not started. +- **`createComposeRule` is deprecated** in the Compose version this project builds with, in + favour of `androidx.compose.ui.test.junit4.v2.createComposeRule`, which runs effects on a + `StandardTestDispatcher` rather than an unconfined one. The device test uses the old one, + as every JVM test here does; moving them is one change for all of them, with the clock + rules in `CLAUDE.md` read again first, not something to start in one file. + +### What nobody has verified in this batch + +That two **overlapping** syncs make one request is shown by `ConcurrentSyncTest` against a +fake server, not on a device (above). The arranging gesture's device tests have run on one +emulator, at 480 dpi — a phone at another density is the question they exist to answer and +has not been asked. #176's defect never reproduced on demand. #175's single sentence was not +looked at on a screen: reaching a password form needs a region's diary to answer. Nothing +here changes what #186 could not answer: a thumb, a haptic, a real GPU, a real launcher. + ## What the batch before added: the first walk of the app on a device, and the twelve defects it found Merged as `c26eace`. **What #186 moved.** Android: the widget picker's preview draws again From 5050e78523cff1b99b54dc141284ed484f7467d5 Mon Sep 17 00:00:00 2001 From: leather147 <is.my.gym.is.my@gmail.com> Date: Sun, 27 Sep 2026 21:41:22 +0300 Subject: [PATCH 43/43] Say that the lock has been installed where it runs, now that #214's CI and preview did MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The close-out said the lock had been resolved for Linux and Python 3.12 but never installed there, and that the first Vercel deploy after the merge would be its first install. #214's own checks then did both: the server job installed it with `pip install -r ../requirements.txt` on Python 3.12 and passed 2063 tests, none skipped — so the test that the lock is closed on that platform ran rather than skipped — and Vercel built the pull request's preview from it. The new `Type check` and `Detekt` steps ran green too. The opening, the batch's unverified list and section 5 say so; what stays unseen is dependabot's `uv` entry. Refs #192 Refs #210 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- HANDOVER.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index 572cd1c4..f831616c 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -30,9 +30,10 @@ The SHA of its own merge is for the next close-out to write. composables (#209). - This file kept to where the work stands, its history in `docs/history.md` (#211). -No schema change; `EXPECTED_REVISION` is still `0017`. **The first deploy after the merge is -the first install of the lock** on Linux and Python 3.12: if Vercel cannot install it, the -build fails and the deployment before it keeps serving. +No schema change; `EXPECTED_REVISION` is still `0017`. **The lock has been installed where it +runs:** #214's CI installed it on Linux and Python 3.12 and passed 2063 tests on it, none +skipped — so the test that the lock is closed there ran — and Vercel built #214's preview +from it. Production takes it at the merge. **Once #214 merges, twenty-three issues are meant to close:** #190–#211 and #213. **#212** stays open: a test that fails at random on Windows and passes on CI. Of the device epic @@ -267,7 +268,9 @@ failed — thirty-nine more than `938e59f`'s 2024; `ruff` clean; `python -m mypy forty-one more than #189's 1459; `assembleDebug` and `assembleRelease` build; `./gradlew detekt` passes against the regenerated baselines. Every branch ran its own gates before the merge, and the merge was checked again as a whole. #201, #202 and #203 were also -mutation-tested: every mutation of each fix turned a test red. +mutation-tested: every mutation of each fix turned a test red. On GitHub, #214's CI ran both +new steps, `Type check` and `Detekt`, green, and its server job passed 2063 on Python 3.12 +in under three minutes. **The baselines hold only what was already there.** Merged, detekt found twelve things in this batch's own Kotlin that no baseline held; `05fc5cf` fixes or suppresses each where it @@ -295,9 +298,8 @@ nothing else in the diff, so every entry it adds is one it removes under #209's - #201's Keystore key and #202's network configuration have not run on a device: how the platform reads the two configuration files is what its documentation says, and the release APK has not been pointed at a real server. -- The lock has not been installed on Linux or on Python 3.12, only resolved for them; the - first Vercel deploy after the merge is its first install. Dependabot's `uv` entry has not - run, and nothing here runs Docker. +- Dependabot's `uv` entry has not opened a pull request, and nothing here runs Docker. The + lock itself was installed on Linux and Python 3.12 by #214's CI and its Vercel preview. - `./gradlew check` and `build` running detekt is read from the plugin's source. - Why two background runs could not start child processes (`0xC0000142`) was not found; it did not happen from a live shell. @@ -596,10 +598,10 @@ cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — i build carries was read out of both packaged APKs with aapt2, and how the platform then applies it is its documentation's word. The release APK has not been pointed at a real server. -- **The lock (#192) has been resolved for Linux and Python 3.12, never installed there.** - Every run here was on Windows and Python 3.13. The first install of it on the - deployment's own platform is the first Vercel deploy after #214, and dependabot's `uv` - entry has not opened a pull request yet. +- **Dependabot's `uv` entry (#192) has not opened a pull request yet**, so the way a bump + regenerates the lock is read from dependabot-core rather than seen. The lock itself was + installed on Linux and Python 3.12 by #214's CI, which ran the suite on it, and Vercel + built #214's preview from it; the local runs were all Windows and Python 3.13. - **No Compose test was actually made to hang**, so `MarqueeClockTest` — the guard #83 added for the trap that costs a whole Gradle run — is reasoned from `MarqueeText`'s `Int.MAX_VALUE` iteration count and from the list of files that call `createComposeRule`.