This commit is contained in:
Lars committed 2026-08-26 10:42:20 +02:00
1 parent 60f0d2830d
commit 53b1eff833
62 files changed
+6578 -355

No files matched your search

+303 -1
View File
@@ -5,6 +5,7 @@ import json
import re
import uuid
from datetime import datetime, timezone
from pathlib import Path
from dialogue_store import (
StoreError,
@@ -270,7 +271,7 @@ def current_entries(profile_id: str, journal_day_id: str) -> list[dict]:
FROM journal_entries e
LEFT JOIN journal_entry_versions v ON v.id = e.current_version_id
WHERE e.profile_id = ? AND e.journal_day_id = ? AND e.deleted_at IS NULL
ORDER BY e.created
ORDER BY e.created, e.rowid
""",
(profile_id, journal_day_id),
).fetchall()
@@ -472,3 +473,304 @@ def day_payload(profile_id: str, journal_day_id: str) -> dict:
"scratch": _parse_scratch(day.get("scratch_json")),
"consolidation_offer": consolidation_offer(conversations),
}
def _entry_list_row(conn, row) -> dict:
item = row_to_dict(row)
item["title"] = clean_title(item.get("title") or "")
item["version_count"] = int(item.get("version_count") or 0)
return item
def list_space_entries(profile_id: str, space_id: str) -> list[dict]:
"""Chronological journal entries of a space. Deleted entries are excluded."""
get_user_space(profile_id, space_id)
with get_db() as conn:
rows = conn.execute(
"""
SELECT e.id, e.profile_id, e.space_id, e.journal_day_id, e.current_version_id,
e.created, e.updated, e.deleted_at,
d.calendar_date, v.title, v.origin,
(SELECT COUNT(*) FROM journal_entry_versions ver
WHERE ver.entry_id = e.id AND ver.profile_id = e.profile_id) AS version_count,
(SELECT r.source_id FROM journal_entry_version_source_refs r
WHERE r.version_id = e.current_version_id AND r.source_kind = 'conversation'
ORDER BY r.sort_order LIMIT 1) AS source_conversation_id
FROM journal_entries e
JOIN journal_days d ON d.id = e.journal_day_id
LEFT JOIN journal_entry_versions v ON v.id = e.current_version_id
WHERE e.profile_id = ? AND e.space_id = ? AND e.deleted_at IS NULL
ORDER BY d.calendar_date DESC, e.created ASC, e.rowid ASC
""",
(profile_id, space_id),
).fetchall()
return [_entry_list_row(conn, row) for row in rows]
def list_deleted_entries(profile_id: str, space_id: str | None = None) -> list[dict]:
if space_id:
get_user_space(profile_id, space_id)
params: list = [profile_id]
space_sql = ""
if space_id:
space_sql = "AND e.space_id = ?"
params.append(space_id)
with get_db() as conn:
rows = conn.execute(
f"""
SELECT e.id, e.profile_id, e.space_id, e.journal_day_id, e.current_version_id,
e.created, e.updated, e.deleted_at,
d.calendar_date, v.title, v.origin,
(SELECT COUNT(*) FROM journal_entry_versions ver
WHERE ver.entry_id = e.id AND ver.profile_id = e.profile_id) AS version_count,
(SELECT r.source_id FROM journal_entry_version_source_refs r
WHERE r.version_id = e.current_version_id AND r.source_kind = 'conversation'
ORDER BY r.sort_order LIMIT 1) AS source_conversation_id
FROM journal_entries e
JOIN journal_days d ON d.id = e.journal_day_id
LEFT JOIN journal_entry_versions v ON v.id = e.current_version_id
WHERE e.profile_id = ? {space_sql} AND e.deleted_at IS NOT NULL
ORDER BY e.deleted_at DESC, e.id ASC
""",
params,
).fetchall()
return [_entry_list_row(conn, row) for row in rows]
def undelete_entry(profile_id: str, entry_id: str) -> dict:
"""Return a soft-deleted entry to the space list. Not a version restore."""
entry = get_entry(profile_id, entry_id, include_deleted=True)
if not entry.get("deleted_at"):
raise StoreError("not_deleted", "Eintrag ist nicht im Papierkorb.")
with get_db() as conn:
conn.execute(
"""
UPDATE journal_entries
SET deleted_at = NULL, updated = datetime('now')
WHERE id = ? AND profile_id = ?
""",
(entry_id, profile_id),
)
return get_entry(profile_id, entry_id)
def continuable_journal_day(profile_id: str) -> dict | None:
"""Most recently active journal day that already has a stored message."""
with get_db() as conn:
row = row_to_dict(
conn.execute(
"""
SELECT d.id AS journal_day_id, d.space_id, d.calendar_date,
s.title AS space_title, c.id AS conversation_id, m.created AS last_message_at
FROM messages m
JOIN conversations c ON c.id = m.conversation_id AND c.profile_id = m.profile_id
JOIN journal_days d ON d.id = c.journal_day_id AND d.profile_id = m.profile_id
JOIN spaces s ON s.id = d.space_id AND s.profile_id = m.profile_id
WHERE m.profile_id = ? AND s.visibility = 'user'
ORDER BY m.created DESC, m.seq DESC, m.id DESC
LIMIT 1
""",
(profile_id,),
).fetchone()
)
if not row:
return None
return {
"space_id": row["space_id"],
"space_title": row.get("space_title") or "",
"journal_day_id": row["journal_day_id"],
"calendar_date": row["calendar_date"],
"conversation_id": row["conversation_id"],
"last_message_at": row.get("last_message_at"),
"reason": "recent_dialogue",
}
def start_payload(profile_id: str) -> dict:
spaces = list_user_spaces(profile_id)
return {
"continuable": continuable_journal_day(profile_id),
"has_spaces": bool(spaces),
"space_count": len(spaces),
"spaces": [{"id": item["id"], "title": item.get("title") or ""} for item in spaces],
}
def _bodies_referencing_media(conn, profile_id: str, media_id: str, exclude_entry_id: str) -> list[str]:
from journal_body import media_ids
rows = conn.execute(
"""
SELECT v.entry_id, v.body
FROM journal_entry_versions v
WHERE v.profile_id = ? AND v.entry_id != ?
""",
(profile_id, exclude_entry_id),
).fetchall()
owners: list[str] = []
seen: set[str] = set()
for row in rows:
if media_id in media_ids(row["body"] or "") and row["entry_id"] not in seen:
seen.add(row["entry_id"])
owners.append(row["entry_id"])
return owners
def inventory_entry_for_purge(profile_id: str, entry_id: str) -> dict:
entry = get_entry(profile_id, entry_id, include_deleted=True)
with get_db() as conn:
versions = [
row_to_dict(row)
for row in conn.execute(
"SELECT id, origin, created FROM journal_entry_versions WHERE profile_id = ? AND entry_id = ? ORDER BY created",
(profile_id, entry_id),
).fetchall()
]
version_ids = [item["id"] for item in versions]
source_refs = 0
if version_ids:
placeholders = ",".join("?" * len(version_ids))
source_refs = conn.execute(
f"""
SELECT COUNT(*) AS n FROM journal_entry_version_source_refs
WHERE version_id IN ({placeholders}) AND profile_id = ?
""",
(*version_ids, profile_id),
).fetchone()["n"]
writing_sources = [
row_to_dict(row)
for row in conn.execute(
"SELECT id, kind FROM writing_profile_sources WHERE profile_id = ? AND entry_id = ?",
(profile_id, entry_id),
).fetchall()
]
evidence = [
row_to_dict(row)
for row in conn.execute(
"SELECT id FROM writing_profile_evidence WHERE profile_id = ? AND source_id = ?",
(profile_id, entry_id),
).fetchall()
]
media_rows = [
row_to_dict(row)
for row in conn.execute(
"SELECT * FROM media_assets WHERE profile_id = ? AND entry_id = ?",
(profile_id, entry_id),
).fetchall()
]
media = []
from media_store import media_root
root = media_root()
for row in media_rows:
owners = _bodies_referencing_media(conn, profile_id, row["id"], entry_id)
path = root / row["rel_path"]
media.append(
{
"id": row["id"],
"rel_path": row["rel_path"],
"path_exists": path.is_file(),
"referenced_by_entries": owners,
"keep_file": bool(owners),
"reassign_to": owners[0] if owners else None,
}
)
return {
"entry": {"id": entry["id"], "space_id": entry["space_id"], "deleted_at": entry.get("deleted_at")},
"versions": versions,
"source_ref_count": int(source_refs or 0),
"writing_profile_sources": writing_sources,
"writing_profile_evidence": evidence,
"media": media,
"conversations_untouched": True,
}
def purge_entry(profile_id: str, entry_id: str, *, confirm: bool) -> dict:
"""Irreversible delete after explicit confirm. Source dialogues stay."""
if not confirm:
raise StoreError("confirm_required", "Endgültiges Löschen braucht eine ausdrückliche Bestätigung.")
entry = get_entry(profile_id, entry_id, include_deleted=True)
if not entry.get("deleted_at"):
raise StoreError("not_in_trash", "Endgültiges Löschen nur aus dem Papierkorb.")
inventory = inventory_entry_for_purge(profile_id, entry_id)
from media_store import media_root
root = media_root()
files_to_delete: list[Path] = []
try:
with get_db() as conn:
for item in inventory["media"]:
if item.get("keep_file") and item.get("reassign_to"):
other = row_to_dict(
conn.execute(
"SELECT id FROM journal_entries WHERE id = ? AND profile_id = ?",
(item["reassign_to"], profile_id),
).fetchone()
)
if not other:
raise StoreError("purge_conflict", "Geteiltes Medium hat keinen sicheren neuen Träger.")
conn.execute(
"UPDATE media_assets SET entry_id = ? WHERE id = ? AND profile_id = ?",
(item["reassign_to"], item["id"], profile_id),
)
elif not item.get("keep_file"):
files_to_delete.append(root / item["rel_path"])
conn.execute(
"DELETE FROM writing_profile_sources WHERE profile_id = ? AND entry_id = ?",
(profile_id, entry_id),
)
conn.execute(
"DELETE FROM writing_profile_evidence WHERE profile_id = ? AND source_id = ?",
(profile_id, entry_id),
)
conn.execute(
"DELETE FROM journal_entries WHERE id = ? AND profile_id = ?",
(entry_id, profile_id),
)
leftover = conn.execute(
"SELECT id FROM journal_entries WHERE id = ? AND profile_id = ?",
(entry_id, profile_id),
).fetchone()
if leftover:
raise StoreError("purge_failed", "Eintrag konnte nicht vollständig gelöscht werden.", 500)
leftover_media = conn.execute(
"SELECT id FROM media_assets WHERE profile_id = ? AND entry_id = ?",
(profile_id, entry_id),
).fetchone()
if leftover_media:
raise StoreError("purge_failed", "Medienverweise konnten nicht aufgelöst werden.", 500)
leftover_sources = conn.execute(
"SELECT id FROM writing_profile_sources WHERE profile_id = ? AND entry_id = ?",
(profile_id, entry_id),
).fetchone()
if leftover_sources:
raise StoreError("purge_failed", "Writing-Profile-Quellen konnten nicht gelöscht werden.", 500)
except StoreError:
raise
except Exception as exc:
raise StoreError("purge_failed", "Endgültiges Löschen wurde abgebrochen, nichts wurde entfernt.", 500) from exc
removed_files: list[str] = []
missing_files: list[str] = []
for path in files_to_delete:
if not path.is_file():
missing_files.append(str(path))
continue
try:
path.unlink()
removed_files.append(str(path))
except OSError as exc:
raise StoreError(
"purge_failed",
"Datenbank entfernt, Mediendatei konnte nicht gelöscht werden. Vorgang fail-closed gemeldet.",
500,
) from exc
return {
"id": entry_id,
"purged": True,
"inventory": inventory,
"removed_files": len(removed_files),
"missing_files": missing_files,
"conversations_untouched": True,
}