Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Fix speaker page Invalid date and missing sample previews (#319) and datetime picker timezone drift (#320) by standardizing meeting_date on naive UTC, hardening all parseInstant copies, and searching snippet sources beyond the last 10 recordings
Murtaza Nasira51a04af434a
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex b7dd521b..76ab8064 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -17,6 +17,8 @@ import osimport reimport jsonfrom datetime import datetime, date, timedelta++from src.utils.dates import to_utc_naivefrom typing import Optionalfrom flask import Blueprint, jsonify, request, current_app, send_file, redirect@@ -1153,7 +1155,9 @@ def update_recording(recording_id):if 'meeting_date' in data:try:if data['meeting_date']:- recording.meeting_date = datetime.fromisoformat(data['meeting_date'].replace('Z', '+00:00'))+ # meeting_date is stored as naive UTC (like created_at): convert+ # zone-aware input to UTC before storing+ recording.meeting_date = to_utc_naive(datetime.fromisoformat(data['meeting_date'].replace('Z', '+00:00')))else:recording.meeting_date = Nonechanged_fields.append('meeting_date')diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 9476a965..4a120e26 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -11,7 +11,7 @@ import mimetypesimport timeimport threadingimport subprocess-from datetime import datetime, timedelta+from datetime import datetime, timedelta, timezonefrom src.services.job_queue import job_queuefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_responsefrom flask_login import login_required, current_user@@ -73,6 +73,7 @@ def _resolve_transcription_model(value):default = SystemSetting.get_setting('transcription_default_model', None)return default or Nonefrom src.tasks.processing import format_transcription_for_llm, _resolve_timestamp_template_format+from src.utils.dates import to_utc_naivefrom src.utils.ffmpeg_utils import FFmpegError, FFmpegNotFoundErrorfrom src.utils.titles import resolve_upload_titlefrom src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text@@ -2006,9 +2007,11 @@ def save_metadata():try:date_str = data['meeting_date']if date_str:- # Try to parse as full ISO datetime first+ # Try to parse as full ISO datetime first. meeting_date is+ # stored as naive UTC (like created_at), so convert any+ # zone-aware input to UTC before storing.try:- recording.meeting_date = datetime.fromisoformat(date_str.replace('Z', '+00:00'))+ recording.meeting_date = to_utc_naive(datetime.fromisoformat(date_str.replace('Z', '+00:00')))except (ValueError, AttributeError):# Fall back to date-only format, preserve existing time if availableparsed_date = datetime.strptime(date_str, '%Y-%m-%d')@@ -2663,8 +2666,9 @@ def upload_file():if user_meeting_date:try:parsed = datetime.fromisoformat(user_meeting_date.replace('Z', '+00:00'))- # Strip timezone to store as naive datetime, consistent with other date sources- meeting_date = parsed.replace(tzinfo=None)+ # meeting_date is stored as naive UTC: convert zone-aware input+ # to UTC before stripping the timezone+ meeting_date = to_utc_naive(parsed)current_app.logger.info(f"Using user-provided meeting_date: {meeting_date}")except (ValueError, TypeError) as e:current_app.logger.warning(f"Could not parse user meeting_date '{user_meeting_date}': {e}")@@ -2672,16 +2676,19 @@ def upload_file():# Then try client-provided file lastModified (most reliable for uploads)if not meeting_date and file_last_modified:try:- # JavaScript lastModified is in milliseconds since epoch+ # JavaScript lastModified is in milliseconds since epoch; convert+ # to naive UTC (the storage convention) rather than server-local+ # so the viewer's browser renders the file's original local time+ # regardless of the server's timezonetimestamp_ms = int(file_last_modified)- meeting_date = datetime.fromtimestamp(timestamp_ms / 1000)+ meeting_date = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc).replace(tzinfo=None)current_app.logger.info(f"Using client file lastModified: {meeting_date}")except (ValueError, TypeError, OSError) as e:current_app.logger.warning(f"Could not parse file_last_modified '{file_last_modified}': {e}")# Fall back to file metadata (creation_time, date tags, etc.)if not meeting_date:- meeting_date = get_creation_date(filepath, use_file_mtime=False)+ meeting_date = to_utc_naive(get_creation_date(filepath, use_file_mtime=False))if meeting_date:current_app.logger.info(f"Using file metadata creation date: {meeting_date}")diff --git a/src/api/shares.py b/src/api/shares.pyindex d16dcd59..4f1b2725 100644--- a/src/api/shares.py+++ b/src/api/shares.py@@ -141,7 +141,7 @@ def view_shared_recording(public_id):'summary_raw': recording.summary if share.share_summary else None,'notes': md_to_html(recording.notes) if share.share_notes else None,'notes_raw': recording.notes if share.share_notes else None,- 'meeting_date': f"{recording.meeting_date.isoformat()}T00:00:00" if recording.meeting_date else None,+ 'meeting_date': recording.meeting_date.isoformat() if recording.meeting_date else None,'mime_type': recording.mime_type,'audio_deleted_at': recording.audio_deleted_at.isoformat() if recording.audio_deleted_at else None,'audio_duration': recording.get_audio_duration()diff --git a/src/models/user.py b/src/models/user.pyindex 28c6f036..24950de3 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -107,8 +107,8 @@ class Speaker(db.Model):return {'id': self.id,'name': self.name,- 'created_at': self.created_at,- 'last_used': self.last_used,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'last_used': self.last_used.isoformat() if self.last_used else None,'use_count': self.use_count,'embedding_count': self.embedding_count,'confidence_score': self.confidence_scorediff --git a/src/services/speaker_snippets.py b/src/services/speaker_snippets.pyindex 4743132d..43d5f81c 100644--- a/src/services/speaker_snippets.py+++ b/src/services/speaker_snippets.py@@ -154,15 +154,25 @@ def _generate_dynamic_snippets(speaker_id, limit=3):if not speaker:return []- # Find recordings that have this speaker's name in transcription- # We'll look at the last 10 recordings and extract snippets from them- recordings = Recording.query.filter_by(user_id=speaker.user_id)\+ # Find recordings whose transcription mentions this speaker's name.+ # The name appears as a JSON string value in identified transcripts, so+ # match its JSON-encoded form (both ascii-escaped and raw-unicode variants,+ # since either may have been used when the transcript was saved).+ base_query = Recording.query.filter_by(user_id=speaker.user_id)\.filter(Recording.transcription.isnot(None))\.filter(Recording.transcription != '')\- .filter(Recording.audio_deleted_at.is_(None))\+ .filter(Recording.audio_deleted_at.is_(None))++ name_variants = {json.dumps(speaker.name), json.dumps(speaker.name, ensure_ascii=False)}+ recordings = base_query\+ .filter(db.or_(*[Recording.transcription.contains(v) for v in name_variants]))\.order_by(Recording.created_at.desc())\.limit(10).all()+ # Fall back to the most recent recordings if the name match found nothing+ if not recordings:+ recordings = base_query.order_by(Recording.created_at.desc()).limit(10).all()+snippets = []for recording in recordings:diff --git a/src/utils/dates.py b/src/utils/dates.pynew file mode 100644index 00000000..6b87ba7f--- /dev/null+++ b/src/utils/dates.py@@ -0,0 +1,23 @@+"""+Datetime normalization helpers.++Backend timestamps — including meeting_date — are stored as naive UTC and+converted to the viewer's timezone client-side (parseServerInstant). These+helpers normalize incoming values to that convention.+"""++from datetime import datetime, timezone+from typing import Optional+++def to_utc_naive(dt: Optional[datetime]) -> Optional[datetime]:+ """Normalize a datetime to naive UTC.++ Aware datetimes are converted to UTC before the tzinfo is stripped.+ Naive datetimes are returned unchanged (assumed to be UTC already).+ """+ if dt is None:+ return None+ if dt.tzinfo is not None:+ return dt.astimezone(timezone.utc).replace(tzinfo=None)+ return dtdiff --git a/static/js/account-webhooks.js b/static/js/account-webhooks.jsindex ead61605..57d11374 100644--- a/static/js/account-webhooks.js+++ b/static/js/account-webhooks.js@@ -59,7 +59,7 @@// as UTC and rendered in the viewer's timezone, not mis-read as local.function parseServerInstant(s) {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 88236b92..4343d836 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -1789,7 +1789,7 @@ document.addEventListener('DOMContentLoaded', async () => {// must keep their literal value (parse with plain new Date()).const parseServerInstant = (s) => {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/static/js/i18n.js b/static/js/i18n.jsindex 83c7ee91..f7fe3ed1 100644--- a/static/js/i18n.js+++ b/static/js/i18n.js@@ -254,7 +254,7 @@ class I18n {d = date;} else {let s = date;- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}d = new Date(s);diff --git a/static/js/modules/composables/modals.js b/static/js/modules/composables/modals.jsindex ee350822..3b1f71bc 100644--- a/static/js/modules/composables/modals.js+++ b/static/js/modules/composables/modals.js@@ -436,9 +436,23 @@ export function useModals(state, utils) {dateTimePickerTarget.value = target;dateTimePickerCallback.value = callback;- // Parse current value if exists+ // Parse current value if exists. meeting_date is stored as naive UTC+ // (same convention as created_at), so append 'Z' to naive datetime+ // strings so the picker opens showing the viewer's LOCAL time — the+ // same value the date chip displays (#320). Date-only values are+ // parsed as local noon so the calendar date never shifts.if (currentValue) {- const date = new Date(currentValue);+ let date;+ if (typeof currentValue === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(currentValue)) {+ const [y, m, d] = currentValue.split('-').map(Number);+ date = new Date(y, m - 1, d, 12, 0, 0);+ } else if (typeof currentValue === 'string'+ && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(currentValue)+ && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(currentValue)) {+ date = new Date(currentValue.replace(' ', 'T') + 'Z');+ } else {+ date = new Date(currentValue);+ }if (!isNaN(date.getTime())) {pickerSelectedDate.value = date;pickerMonth.value = date.getMonth();@@ -571,7 +585,11 @@ export function useModals(state, utils) {date.setSeconds(0);date.setMilliseconds(0);- // Format as ISO string for storage (YYYY-MM-DDTHH:mm:ss)+ // Convert the picked LOCAL time to a naive UTC ISO string+ // (YYYY-MM-DDTHH:mm:ss) — the backend storage convention shared with+ // created_at. The display side (parseServerInstant) converts it back+ // to the viewer's timezone, so what the user picked is what they see,+ // and repeated edits don't drift (#320).const isoString = date.toISOString().slice(0, 19);// Call the callback with the resultdiff --git a/static/js/modules/composables/sharing.js b/static/js/modules/composables/sharing.jsindex 525742a8..1f3399e1 100644--- a/static/js/modules/composables/sharing.js+++ b/static/js/modules/composables/sharing.js@@ -31,7 +31,7 @@ export function useSharing(state, utils) {// parsed as UTC; the toLocale* calls below then render it in the// viewer's own timezone.let normalized = dateString;- if (typeof normalized === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) {+ if (typeof normalized === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(normalized) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) {normalized = normalized.replace(' ', 'T') + 'Z';}const date = new Date(normalized);diff --git a/static/js/modules/composables/tokens.js b/static/js/modules/composables/tokens.jsindex b4b6001a..ac424054 100644--- a/static/js/modules/composables/tokens.js+++ b/static/js/modules/composables/tokens.js@@ -9,7 +9,7 @@ const { ref, computed } = Vue;// UTC and rendered in the viewer's timezone instead of being mis-parsed as local.const parseServerInstant = (s) => {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex b0b2ebb8..0823b61b 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -296,45 +296,6 @@ export function useUI(state, utils, processedTranscription) {return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];};- // Format display date. (Shadowed by app.modular.js's version; kept correct- // for INSTANT timestamps via parseServerInstant in case it's ever wired.)- const formatDisplayDate = (dateString) => {- if (!dateString) return '';- const date = utils.parseServerInstant(dateString);- return date.toLocaleDateString(undefined, {- year: 'numeric',- month: 'short',- day: 'numeric',- hour: '2-digit',- minute: '2-digit'- });- };-- // Format short date- const formatShortDate = (dateString) => {- if (!dateString) return '';- const date = utils.parseServerInstant(dateString);- const now = new Date();- const diff = now - date;- const oneDay = 24 * 60 * 60 * 1000;-- if (diff < oneDay) {- return date.toLocaleTimeString(undefined, {- hour: '2-digit',- minute: '2-digit'- });- } else if (diff < 7 * oneDay) {- return date.toLocaleDateString(undefined, {- weekday: 'short'- });- } else {- return date.toLocaleDateString(undefined, {- month: 'short',- day: 'numeric'- });- }- };-// Format statusconst formatStatus = (status) => {if (!status || status === 'COMPLETED') return '';@@ -2203,8 +2164,10 @@ export function useUI(state, utils, processedTranscription) {switchToRecordingView,setGlobalError,formatFileSize,- formatDisplayDate,- formatShortDate,+ // formatDisplayDate / formatShortDate intentionally NOT exported: this+ // composable is spread into the app scope AFTER app.modular.js's own+ // versions, so exporting them here shadowed the calendar-aware+ // implementations and made meeting_date render as a UTC instant (#320).formatStatus,getStatusClass,formatTime,diff --git a/templates/account.html b/templates/account.htmlindex 0139327b..9911650c 100644--- a/templates/account.html+++ b/templates/account.html@@ -4264,7 +4264,7 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co// they're read as UTC and rendered/compared in the viewer's local tz.function parseInstant(s) {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/templates/admin.html b/templates/admin.htmlindex b1d71c29..2aa7a4c1 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -2712,7 +2712,7 @@ Summarization Instructions:// read as UTC and rendered in the viewer's local timezone.const parseInstant = (s) => {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/templates/components/detail-view.html b/templates/components/detail-view.htmlindex 44caed08..07b77b4a 100644--- a/templates/components/detail-view.html+++ b/templates/components/detail-view.html@@ -103,7 +103,7 @@<!-- Meeting date --><span class="chip-meta chip-meta--clickable" @click="openMeetingDatePicker"><i class="fas fa-calendar"></i>- <span class="chip-meta__label">${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date, true) : 'No date set'}</span>+ <span class="chip-meta__label">${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}</span></span><!-- File metadata facts -->diff --git a/templates/components/detail/mobile-header.html b/templates/components/detail/mobile-header.htmlindex e2c6f0b1..8e965dc0 100644--- a/templates/components/detail/mobile-header.html+++ b/templates/components/detail/mobile-header.html@@ -129,7 +129,7 @@<div class="flex flex-wrap gap-1.5"><button @click.stop="openMeetingDatePicker" class="chip-meta chip-meta--clickable"><i class="fas fa-calendar"></i>- <span class="chip-meta__label" v-text="selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date, true) : 'No date set'"></span>+ <span class="chip-meta__label" v-text="selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'"></span></button><span v-if="selectedRecording.is_shared" class="chip-meta"><i class="fas fa-user"></i>diff --git a/templates/components/sidebar.html b/templates/components/sidebar.htmlindex d5b30246..7c3b1ca3 100644--- a/templates/components/sidebar.html+++ b/templates/components/sidebar.html@@ -451,7 +451,7 @@<!-- Date --><div class="flex items-center flex-shrink-0"><i class="fas fa-calendar-alt mr-1 text-[var(--text-muted)]" style="font-size: 10px;"></i>- ${formatShortDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at, sortBy === 'meeting_date')}+ ${formatShortDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at)}</div><!-- Participants -->diff --git a/templates/group-admin.html b/templates/group-admin.htmlindex 5d23be89..c8a4cb73 100644--- a/templates/group-admin.html+++ b/templates/group-admin.html@@ -807,7 +807,7 @@// read as UTC and rendered in the viewer's local timezone.const parseInstant = (s) => {if (s == null) return new Date(NaN);- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}return new Date(s);diff --git a/templates/inquire.html b/templates/inquire.htmlindex 277fa513..a3677cac 100644--- a/templates/inquire.html+++ b/templates/inquire.html@@ -885,7 +885,13 @@const formatDate = (dateString) => {if (!dateString) return '';- const date = new Date(dateString);+ // meeting_date is naive UTC — parse via the instant+ // convention so the date renders in the viewer's timezone+ let s = dateString;+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ s = s.replace(' ', 'T') + 'Z';+ }+ const date = new Date(s);return date.toLocaleDateString();};@@ -894,7 +900,7 @@const formatInstant = (dateString) => {if (!dateString) return '';let s = dateString;- if (typeof s === 'string' && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {s = s.replace(' ', 'T') + 'Z';}const date = new Date(s);diff --git a/templates/modals/edit-modal.html b/templates/modals/edit-modal.htmlindex a3390ca0..4ad14f01 100644--- a/templates/modals/edit-modal.html+++ b/templates/modals/edit-modal.html@@ -19,7 +19,7 @@<div @click="openDateTimePicker('edit_modal_meeting_date', editingRecording.meeting_date, (isoString) => { editingRecording.meeting_date = isoString; })"class="field cursor-pointer hover:border-[var(--border-focus)] flex items-center justify-between"><span :class="editingRecording.meeting_date ? 'text-[var(--text-primary)]' : 'text-[var(--text-muted)]'">- ${editingRecording.meeting_date ? formatDisplayDate(editingRecording.meeting_date, true) : 'Select date and time...'}+ ${editingRecording.meeting_date ? formatDisplayDate(editingRecording.meeting_date) : 'Select date and time...'}</span><i class="fas fa-calendar-alt text-[var(--text-muted)]"></i></div>diff --git a/tests/test_datetime_serialization_fixes.py b/tests/test_datetime_serialization_fixes.pynew file mode 100644index 00000000..933b27be--- /dev/null+++ b/tests/test_datetime_serialization_fixes.py@@ -0,0 +1,273 @@+#!/usr/bin/env python3+"""+Regression tests for the datetime bugs reported in #319 and #320.++Covers:+ - Speaker.to_dict() must serialize datetimes as ISO strings, not raw+ datetime objects (raw objects get jsonify'd as RFC-1123 strings, which+ the frontend's parseInstant mangles into "Invalid Date") (#319)+ - src.utils.dates.to_utc_naive normalizes datetimes to the naive-UTC+ storage convention shared by meeting_date and created_at (#320)+ - PATCH /api/v1/recordings/<id> with a zone-aware meeting_date stores a+ naive UTC value (#320)+ - Speaker snippet lookup finds recordings beyond the 10 most recent when+ the speaker's name matches (#319, "samples shown but no preview")++Pattern follows tests/test_api_v1_speakers.py — standalone, no pytest fixtures.+"""++import json+import secrets+import sys+import os+from datetime import datetime, timezone, timedelta++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import User, APIToken, Recording, Speaker+from src.utils.dates import to_utc_naive+from src.utils.token_auth import hash_token+++def _get_or_create_test_user(suffix=""):+ username = f"dtfix_test_user{suffix}"+ user = User.query.filter_by(username=username).first()+ created = False+ if not user:+ user = User(username=username, email=f"{username}@local.test")+ db.session.add(user)+ db.session.commit()+ created = True+ return user, created+++def _create_api_token(user):+ plaintext = f"test-token-{secrets.token_urlsafe(16)}"+ token = APIToken(user_id=user.id, token_hash=hash_token(plaintext), name="dtfix-token")+ db.session.add(token)+ db.session.commit()+ return token, plaintext+++def _cleanup(*objects):+ for obj in reversed(objects):+ try:+ db.session.delete(obj)+ except Exception:+ db.session.rollback()+ try:+ merged = db.session.merge(obj)+ db.session.delete(merged)+ except Exception:+ pass+ db.session.commit()+++# ---------------------------------------------------------------------------+# Speaker.to_dict serialization (#319)+# ---------------------------------------------------------------------------+++def test_speaker_to_dict_serializes_datetimes_as_iso_strings():+ with app.app_context():+ user, cu = _get_or_create_test_user()+ speaker = Speaker(name="ISO Check", user_id=user.id,+ created_at=datetime(2026, 2, 23, 5, 11, 59),+ last_used=datetime(2026, 6, 10, 0, 19, 12))+ db.session.add(speaker)+ db.session.commit()+ try:+ data = speaker.to_dict()+ assert data["created_at"] == "2026-02-23T05:11:59"+ assert data["last_used"] == "2026-06-10T00:19:12"+ # Round-trippable by the frontend parseInstant convention+ datetime.fromisoformat(data["created_at"])+ datetime.fromisoformat(data["last_used"])+ finally:+ _cleanup(speaker)+ if cu:+ _cleanup(user)+++def test_speaker_to_dict_handles_null_dates():+ with app.app_context():+ user, cu = _get_or_create_test_user()+ speaker = Speaker(name="Null Dates", user_id=user.id)+ db.session.add(speaker)+ db.session.commit()+ # Column defaults fill these on insert; null them out afterwards+ speaker.created_at = None+ speaker.last_used = None+ db.session.commit()+ try:+ data = speaker.to_dict()+ assert data["created_at"] is None+ assert data["last_used"] is None+ finally:+ _cleanup(speaker)+ if cu:+ _cleanup(user)+++def test_speakers_endpoint_returns_iso_dates():+ """GET /speakers (the page's own endpoint) must not emit RFC-1123 dates."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ speaker = Speaker(name="Endpoint ISO", user_id=user.id,+ created_at=datetime(2026, 1, 2, 3, 4, 5),+ last_used=datetime(2026, 1, 2, 3, 4, 5))+ db.session.add(speaker)+ db.session.commit()+ client = app.test_client()+ with client.session_transaction() as sess:+ sess["_user_id"] = str(user.id)+ sess["_fresh"] = True+ try:+ resp = client.get("/speakers")+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"+ speakers = resp.get_json()+ ours = [s for s in speakers if s.get("name") == "Endpoint ISO"]+ assert ours, "created speaker missing from /speakers response"+ for field in ("created_at", "last_used"):+ value = ours[0][field]+ assert "GMT" not in value, f"{field} serialized as RFC-1123: {value}"+ datetime.fromisoformat(value)+ finally:+ _cleanup(speaker)+ if cu:+ _cleanup(user)+++# ---------------------------------------------------------------------------+# src.utils.dates helpers (#320)+# ---------------------------------------------------------------------------+++def test_to_utc_naive_none_and_naive_passthrough():+ assert to_utc_naive(None) is None+ naive = datetime(2026, 7, 2, 11, 0, 0)+ assert to_utc_naive(naive) is naive+++def test_to_utc_naive_converts_aware_to_utc_and_strips_tz():+ # UTC input: tzinfo stripped, clock unchanged+ aware_utc = datetime(2026, 7, 2, 16, 0, 0, tzinfo=timezone.utc)+ assert to_utc_naive(aware_utc) == datetime(2026, 7, 2, 16, 0, 0)+ # Offset input: converted to UTC+ aware_offset = datetime(2026, 7, 2, 18, 0, 0, tzinfo=timezone(timedelta(hours=2)))+ result = to_utc_naive(aware_offset)+ assert result.tzinfo is None+ assert result == datetime(2026, 7, 2, 16, 0, 0)+++# ---------------------------------------------------------------------------+# PATCH meeting_date stores naive UTC (#320)+# ---------------------------------------------------------------------------+++def test_patch_meeting_date_offset_converted_to_utc():+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = Recording(user_id=user.id, title="DT Patch", status="COMPLETED")+ db.session.add(rec)+ db.session.commit()+ client = app.test_client()+ try:+ resp = client.patch(f"/api/v1/recordings/{rec.id}",+ headers={"X-API-Token": token},+ json={"meeting_date": "2026-07-02T18:00:00+02:00"})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}: {resp.data}"+ db.session.refresh(rec)+ assert rec.meeting_date is not None+ assert rec.meeting_date.tzinfo is None, "meeting_date stored zone-aware"+ assert rec.meeting_date == datetime(2026, 7, 2, 16, 0, 0)+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++def test_patch_meeting_date_naive_stored_as_utc_literal():+ """A naive UTC string (what the picker sends via toISOString) is stored as-is."""+ with app.app_context():+ user, cu = _get_or_create_test_user()+ token_rec, token = _create_api_token(user)+ rec = Recording(user_id=user.id, title="DT Naive", status="COMPLETED")+ db.session.add(rec)+ db.session.commit()+ client = app.test_client()+ try:+ resp = client.patch(f"/api/v1/recordings/{rec.id}",+ headers={"X-API-Token": token},+ json={"meeting_date": "2026-07-02T11:30:00"})+ assert resp.status_code == 200, f"Expected 200, got {resp.status_code}: {resp.data}"+ db.session.refresh(rec)+ assert rec.meeting_date == datetime(2026, 7, 2, 11, 30, 0)+ finally:+ _cleanup(rec, token_rec)+ if cu:+ _cleanup(user)+++# ---------------------------------------------------------------------------+# Snippet lookup beyond the 10 most recent recordings (#319)+# ---------------------------------------------------------------------------+++def test_snippets_found_when_speaker_only_in_older_recordings():+ from src.services.speaker_snippets import get_speaker_snippets++ with app.app_context():+ user, cu = _get_or_create_test_user("_snip")+ speaker = Speaker(name="Old Timer", user_id=user.id)+ db.session.add(speaker)+ db.session.commit()++ created = []+ base = datetime(2026, 1, 1, 12, 0, 0)+ # Oldest recording is the ONLY one featuring the speaker+ match_transcript = json.dumps([+ {"speaker": "Old Timer", "sentence": "This is a long enough sentence to snippet.",+ "start_time": 5.0, "end_time": 12.0},+ ])+ rec_match = Recording(user_id=user.id, title="Old Match", status="COMPLETED",+ transcription=match_transcript, created_at=base)+ db.session.add(rec_match)+ created.append(rec_match)++ filler_transcript = json.dumps([+ {"speaker": "Somebody Else", "sentence": "Nothing relevant in this one at all.",+ "start_time": 1.0, "end_time": 6.0},+ ])+ for i in range(12):+ rec = Recording(user_id=user.id, title=f"Filler {i}", status="COMPLETED",+ transcription=filler_transcript,+ created_at=base + timedelta(days=i + 1))+ db.session.add(rec)+ created.append(rec)+ db.session.commit()++ try:+ snippets = get_speaker_snippets(speaker.id, limit=3)+ assert snippets, "expected a snippet from the older matching recording"+ assert snippets[0]["recording_id"] == rec_match.id+ assert snippets[0]["start_time"] == 5.0+ finally:+ _cleanup(*created, speaker)+ if cu:+ _cleanup(user)+++if __name__ == "__main__":+ failures = 0+ for name, fn in sorted(globals().items()):+ if name.startswith("test_") and callable(fn):+ try:+ fn()+ print(f"PASS {name}")+ except AssertionError as e:+ failures += 1+ print(f"FAIL {name}: {e}")+ sys.exit(1 if failures else 0)