Multi-user sharing, groups, and in-app notifications

Backend:
- Alembic migration 0025: groups, group_memberships, project_shares,
  note_shares, notifications tables
- models: Group, GroupMembership, ProjectShare, NoteShare, Notification
- services/access.py: permission resolution (viewer/editor/admin/owner)
- services/groups.py + routes/groups.py: full group CRUD + membership
- services/sharing.py + routes/shares.py: project/note sharing API
- services/notifications.py: in-app notification create/list/mark-read
- routes/in_app_notifications.py: GET/POST notification endpoints
- routes/users.py: user search endpoint
- services/projects.py + services/notes.py: *_for_user variants
- routes updated to use *_for_user on get/list; adds permission field
- app.py: register all new blueprints

Frontend:
- api/client.ts: ShareEntry, GroupEntry, NotificationEntry types + helpers
- stores/notifications.ts: Pinia store with polling
- NotificationBell.vue: bell icon + badge + dropdown toggle + 60s poll
- NotificationsPanel.vue: unread notification list with mark-all-read
- ShareDialog.vue: teleport modal for sharing projects/notes with users/groups
- SharedWithMeView.vue: /shared route listing shared projects and notes
- AppHeader: NotificationBell, Shared nav link
- ProjectView, NoteViewerView, TaskViewerView: Share button + ShareDialog
- SettingsView: Groups admin tab with create/delete groups + member mgmt
- router: /shared route

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-11 15:37:00 -04:00
parent 878b149f4d
commit c7ef709633
31 changed files with 3147 additions and 16 deletions
+163
View File
@@ -0,0 +1,163 @@
"""Access control service.
Single source of truth for permission resolution on projects and notes.
All human-facing routes that should honour shares call these functions.
LLM tool routes continue to use owner-scoped service functions directly.
Permission rank: owner > admin > editor > viewer
"""
import logging
from sqlalchemy import select
from fabledassistant.models import async_session
from fabledassistant.models.group import GroupMembership
from fabledassistant.models.note import Note
from fabledassistant.models.project import Project
from fabledassistant.models.share import NoteShare, ProjectShare
logger = logging.getLogger(__name__)
PERMISSION_RANK: dict[str, int] = {
"viewer": 1,
"editor": 2,
"admin": 3,
"owner": 4,
}
def _higher(a: str | None, b: str | None) -> str | None:
"""Return the higher-ranked permission, or None if both are None."""
if a is None:
return b
if b is None:
return a
return a if PERMISSION_RANK[a] >= PERMISSION_RANK[b] else b
async def _user_group_ids(session, user_id: int) -> list[int]:
rows = (
await session.execute(
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
)
).scalars().all()
return list(rows)
# ---------------------------------------------------------------------------
# Project permissions
# ---------------------------------------------------------------------------
async def get_project_permission(user_id: int, project_id: int) -> str | None:
"""Return the effective permission string for user on project, or None."""
async with async_session() as session:
project = await session.get(Project, project_id)
if project is None:
return None
if project.user_id == user_id:
return "owner"
# Direct share
direct = (
await session.execute(
select(ProjectShare).where(
ProjectShare.project_id == project_id,
ProjectShare.shared_with_user_id == user_id,
)
)
).scalar_one_or_none()
# Group shares
group_ids = await _user_group_ids(session, user_id)
group_perm: str | None = None
if group_ids:
group_shares = (
await session.execute(
select(ProjectShare).where(
ProjectShare.project_id == project_id,
ProjectShare.shared_with_group_id.in_(group_ids),
)
)
).scalars().all()
for gs in group_shares:
group_perm = _higher(group_perm, gs.permission)
return _higher(direct.permission if direct else None, group_perm)
async def can_read_project(user_id: int, project_id: int) -> bool:
return (await get_project_permission(user_id, project_id)) is not None
async def can_write_project(user_id: int, project_id: int) -> bool:
perm = await get_project_permission(user_id, project_id)
return perm in ("editor", "admin", "owner")
async def can_admin_project(user_id: int, project_id: int) -> bool:
perm = await get_project_permission(user_id, project_id)
return perm in ("admin", "owner")
# ---------------------------------------------------------------------------
# Note / task permissions
# ---------------------------------------------------------------------------
async def get_note_permission(user_id: int, note_id: int) -> str | None:
"""Return the effective permission for user on a note/task, or None.
Resolution order:
1. Ownership
2. Direct note share
3. Group-based note share
4. Inherited from project share (if note belongs to a project)
Highest rank wins.
"""
async with async_session() as session:
note = await session.get(Note, note_id)
if note is None:
return None
if note.user_id == user_id:
return "owner"
direct = (
await session.execute(
select(NoteShare).where(
NoteShare.note_id == note_id,
NoteShare.shared_with_user_id == user_id,
)
)
).scalar_one_or_none()
group_ids = await _user_group_ids(session, user_id)
group_perm: str | None = None
if group_ids:
group_shares = (
await session.execute(
select(NoteShare).where(
NoteShare.note_id == note_id,
NoteShare.shared_with_group_id.in_(group_ids),
)
)
).scalars().all()
for gs in group_shares:
group_perm = _higher(group_perm, gs.permission)
note_perm = _higher(direct.permission if direct else None, group_perm)
# Inherit from project if note belongs to one
if note.project_id is not None:
project_perm = await get_project_permission(user_id, note.project_id)
note_perm = _higher(note_perm, project_perm)
return note_perm
async def can_read_note(user_id: int, note_id: int) -> bool:
return (await get_note_permission(user_id, note_id)) is not None
async def can_write_note(user_id: int, note_id: int) -> bool:
perm = await get_note_permission(user_id, note_id)
return perm in ("editor", "admin", "owner")
+186
View File
@@ -0,0 +1,186 @@
"""Group management service."""
import logging
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from fabledassistant.models import async_session
from fabledassistant.models.group import Group, GroupMembership
from fabledassistant.models.user import User
logger = logging.getLogger(__name__)
async def create_group(
user_id: int, name: str, description: str | None = None
) -> Group:
async with async_session() as session:
group = Group(name=name, description=description, created_by=user_id)
session.add(group)
await session.flush()
session.add(GroupMembership(group_id=group.id, user_id=user_id, role="owner"))
await session.commit()
await session.refresh(group)
return group
async def list_groups(user_id: int) -> list[dict]:
"""All users see all groups with member count and their own membership status."""
async with async_session() as session:
groups = (await session.execute(select(Group).order_by(Group.name))).scalars().all()
user_group_ids = set(
(await session.execute(
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
)).scalars().all()
)
result = []
for g in groups:
count = len(
(await session.execute(
select(GroupMembership).where(GroupMembership.group_id == g.id)
)).scalars().all()
)
d = g.to_dict()
d["member_count"] = count
d["is_member"] = g.id in user_group_ids
result.append(d)
return result
async def get_group(group_id: int) -> Group | None:
async with async_session() as session:
return await session.get(Group, group_id)
async def _is_group_owner(session, acting_user_id: int, group_id: int) -> bool:
m = (await session.execute(
select(GroupMembership).where(
GroupMembership.group_id == group_id,
GroupMembership.user_id == acting_user_id,
GroupMembership.role == "owner",
)
)).scalar_one_or_none()
return m is not None
async def update_group(
acting_user_id: int, group_id: int, is_site_admin: bool, **fields
) -> Group | None:
async with async_session() as session:
group = await session.get(Group, group_id)
if not group:
return None
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
return None
for k, v in fields.items():
if hasattr(group, k):
setattr(group, k, v)
await session.commit()
await session.refresh(group)
return group
async def delete_group(acting_user_id: int, group_id: int, is_site_admin: bool) -> bool:
async with async_session() as session:
group = await session.get(Group, group_id)
if not group:
return False
if not is_site_admin and group.created_by != acting_user_id:
return False
await session.delete(group)
await session.commit()
return True
async def list_members(group_id: int) -> list[dict]:
async with async_session() as session:
rows = (await session.execute(
select(GroupMembership, User)
.join(User, User.id == GroupMembership.user_id)
.where(GroupMembership.group_id == group_id)
)).all()
return [
{**m.to_dict(), "username": u.username, "email": u.email}
for m, u in rows
]
async def add_member(
acting_user_id: int,
group_id: int,
target_user_id: int,
role: str,
is_site_admin: bool,
) -> GroupMembership | None:
async with async_session() as session:
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
return None
membership = GroupMembership(group_id=group_id, user_id=target_user_id, role=role)
session.add(membership)
try:
await session.commit()
except IntegrityError:
await session.rollback()
return None
await session.refresh(membership)
return membership
async def update_member_role(
acting_user_id: int,
group_id: int,
target_user_id: int,
role: str,
is_site_admin: bool,
) -> GroupMembership | None:
async with async_session() as session:
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
return None
m = (await session.execute(
select(GroupMembership).where(
GroupMembership.group_id == group_id,
GroupMembership.user_id == target_user_id,
)
)).scalar_one_or_none()
if not m:
return None
m.role = role
await session.commit()
await session.refresh(m)
return m
async def remove_member(
acting_user_id: int,
group_id: int,
target_user_id: int,
is_site_admin: bool,
) -> bool:
"""Group owner, site admin, or self-removal are all permitted."""
async with async_session() as session:
is_self = acting_user_id == target_user_id
if not is_site_admin and not is_self:
if not await _is_group_owner(session, acting_user_id, group_id):
return False
m = (await session.execute(
select(GroupMembership).where(
GroupMembership.group_id == group_id,
GroupMembership.user_id == target_user_id,
)
)).scalar_one_or_none()
if not m:
return False
await session.delete(m)
await session.commit()
return True
async def get_user_groups(user_id: int) -> list[Group]:
async with async_session() as session:
rows = (await session.execute(
select(Group)
.join(GroupMembership, GroupMembership.group_id == Group.id)
.where(GroupMembership.user_id == user_id)
)).scalars().all()
return list(rows)
+17
View File
@@ -441,3 +441,20 @@ async def build_note_graph(
edges.append({"source": nid, "target": tag_node_id, "type": "tag"})
return {"nodes": nodes, "edges": edges}
# ---------------------------------------------------------------------------
# Shared-access variant
# ---------------------------------------------------------------------------
async def get_note_for_user(
accessing_user_id: int, note_id: int
) -> tuple["Note", str] | None:
"""Returns (note, permission) if user has any access, else None."""
from fabledassistant.services.access import get_note_permission
perm = await get_note_permission(accessing_user_id, note_id)
if perm is None:
return None
async with async_session() as session:
note = await session.get(Note, note_id)
return (note, perm) if note else None
@@ -249,3 +249,199 @@ def start_notification_loop() -> None:
global _notification_task
if _notification_task is None or _notification_task.done():
_notification_task = asyncio.create_task(_notification_loop())
# ---------------------------------------------------------------------------
# In-app notifications (Notification model — shares, group events)
# ---------------------------------------------------------------------------
async def create_in_app_notification(user_id: int, notif_type: str, payload: dict):
"""Create an in-app Notification record."""
from fabledassistant.models.notification import Notification
async with async_session() as session:
n = Notification(user_id=user_id, type=notif_type, payload=payload)
session.add(n)
await session.commit()
await session.refresh(n)
return n
async def _fire_push_notif(user_id: int, title: str, body: str, url: str) -> None:
try:
from fabledassistant.services.push import send_push_notification
await send_push_notification(user_id, title, body, url=url)
except Exception:
logger.exception("Push notification failed for user %d", user_id)
async def _fire_share_email(user_id: int, subject: str, body_text: str) -> None:
try:
if not await is_smtp_configured():
return
async with async_session() as session:
user = await session.get(User, user_id)
if user and user.email:
html = _email_html(subject, f"<p>{body_text.replace(chr(10), '<br>')}</p>")
await send_email(user.email, subject, html)
except Exception:
logger.exception("Share email notification failed for user %d", user_id)
async def _group_member_ids(group_id: int) -> list[int]:
from fabledassistant.models.group import GroupMembership
async with async_session() as session:
rows = (await session.execute(
select(GroupMembership.user_id).where(GroupMembership.group_id == group_id)
)).scalars().all()
return list(rows)
async def notify_project_shared(
project_id: int,
permission: str,
invited_by_user_id: int,
target_user_id: int | None,
target_group_id: int | None,
) -> None:
from fabledassistant.models.project import Project
async with async_session() as session:
project = await session.get(Project, project_id)
inviter = await session.get(User, invited_by_user_id)
if not project or not inviter:
return
recipients: list[int] = []
if target_user_id:
recipients = [target_user_id]
elif target_group_id:
recipients = [uid for uid in await _group_member_ids(target_group_id) if uid != invited_by_user_id]
url = f"/projects/{project_id}"
msg = f"{inviter.username} shared \"{project.title}\" with you as {permission}"
for uid in recipients:
await create_in_app_notification(uid, "project_shared", {
"project_id": project_id,
"project_title": project.title,
"permission": permission,
"invited_by": inviter.username,
"url": url,
})
asyncio.create_task(_fire_push_notif(uid, "Project shared with you", msg, url))
asyncio.create_task(_fire_share_email(uid, f"[Fabled] {inviter.username} shared a project with you", msg))
async def notify_note_shared(
note_id: int,
permission: str,
invited_by_user_id: int,
target_user_id: int | None,
target_group_id: int | None,
) -> None:
from fabledassistant.models.note import Note
async with async_session() as session:
note = await session.get(Note, note_id)
inviter = await session.get(User, invited_by_user_id)
if not note or not inviter:
return
recipients: list[int] = []
if target_user_id:
recipients = [target_user_id]
elif target_group_id:
recipients = [uid for uid in await _group_member_ids(target_group_id) if uid != invited_by_user_id]
route = "tasks" if note.is_task else "notes"
url = f"/{route}/{note_id}"
msg = f"{inviter.username} shared \"{note.title}\" with you as {permission}"
for uid in recipients:
await create_in_app_notification(uid, "note_shared", {
"note_id": note_id,
"note_title": note.title,
"permission": permission,
"invited_by": inviter.username,
"url": url,
})
asyncio.create_task(_fire_push_notif(uid, "Note shared with you", msg, url))
asyncio.create_task(_fire_share_email(uid, f"[Fabled] {inviter.username} shared a note with you", msg))
async def notify_group_added(
group_id: int, role: str, invited_by_user_id: int, target_user_id: int
) -> None:
from fabledassistant.models.group import Group
async with async_session() as session:
group = await session.get(Group, group_id)
inviter = await session.get(User, invited_by_user_id)
if not group or not inviter:
return
url = f"/groups/{group_id}"
msg = f"{inviter.username} added you to group \"{group.name}\" as {role}"
await create_in_app_notification(target_user_id, "group_added", {
"group_id": group_id,
"group_name": group.name,
"role": role,
"invited_by": inviter.username,
"url": url,
})
asyncio.create_task(_fire_push_notif(target_user_id, "Added to a group", msg, url))
asyncio.create_task(_fire_share_email(target_user_id, "[Fabled] You've been added to a group", msg))
async def list_in_app_notifications(user_id: int, unread_only: bool = True) -> list[dict]:
from fabledassistant.models.notification import Notification
async with async_session() as session:
q = select(Notification).where(Notification.user_id == user_id)
if unread_only:
q = q.where(Notification.read_at.is_(None))
q = q.order_by(Notification.created_at.desc()).limit(50)
rows = (await session.execute(q)).scalars().all()
return [n.to_dict() for n in rows]
async def unread_notification_count(user_id: int) -> int:
from fabledassistant.models.notification import Notification
async with async_session() as session:
result = await session.execute(
select(func.count()).where(
Notification.user_id == user_id,
Notification.read_at.is_(None),
)
)
return result.scalar() or 0
async def mark_notification_read(user_id: int, notification_id: int) -> bool:
from fabledassistant.models.notification import Notification
from datetime import timezone as tz
async with async_session() as session:
n = (await session.execute(
select(Notification).where(
Notification.id == notification_id,
Notification.user_id == user_id,
)
)).scalar_one_or_none()
if not n:
return False
from datetime import datetime
n.read_at = datetime.now(tz.utc)
await session.commit()
return True
async def mark_all_notifications_read(user_id: int) -> int:
from fabledassistant.models.notification import Notification
from datetime import datetime, timezone as tz
from sqlalchemy import update as sa_update
async with async_session() as session:
result = await session.execute(
sa_update(Notification)
.where(Notification.user_id == user_id, Notification.read_at.is_(None))
.values(read_at=datetime.now(tz.utc))
.returning(Notification.id)
)
await session.commit()
return len(result.fetchall())
+75
View File
@@ -144,3 +144,78 @@ async def get_project_summary(user_id: int, project_id: int) -> dict:
"last_activity": last_activity_result.isoformat() if last_activity_result else None,
"milestone_summary": milestone_summary,
}
# ---------------------------------------------------------------------------
# Shared-access variants (honour ProjectShare in addition to ownership)
# ---------------------------------------------------------------------------
async def get_project_for_user(
accessing_user_id: int, project_id: int
) -> tuple[Project, str] | None:
"""Returns (project, permission) if user has any access, else None."""
from fabledassistant.services.access import get_project_permission
perm = await get_project_permission(accessing_user_id, project_id)
if perm is None:
return None
async with async_session() as session:
project = await session.get(Project, project_id)
return (project, perm) if project else None
async def list_projects_for_user(user_id: int, status: str | None = None) -> list[dict]:
"""Owned projects + shared projects, each dict has 'permission' field."""
from fabledassistant.models.group import GroupMembership
from fabledassistant.models.share import ProjectShare
from fabledassistant.services.access import PERMISSION_RANK
owned = await list_projects(user_id, status)
owned_ids = {p.id for p in owned}
result = []
for p in owned:
d = p.to_dict() if hasattr(p, "to_dict") else {"id": p.id, "title": p.title}
d["permission"] = "owner"
result.append(d)
async with async_session() as session:
user_group_ids = (await session.execute(
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
)).scalars().all()
shared_direct = (await session.execute(
select(ProjectShare).where(ProjectShare.shared_with_user_id == user_id)
)).scalars().all()
shared_group: list[ProjectShare] = []
if user_group_ids:
shared_group = (await session.execute(
select(ProjectShare).where(
ProjectShare.shared_with_group_id.in_(user_group_ids)
)
)).scalars().all()
seen: dict[int, str] = {}
for share in list(shared_direct) + list(shared_group):
if share.project_id in owned_ids:
continue
prev = seen.get(share.project_id)
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
seen[share.project_id] = share.permission
for pid, perm in seen.items():
if status:
async with async_session() as session:
proj = await session.get(Project, pid)
if not proj or proj.status != status:
continue
else:
async with async_session() as session:
proj = await session.get(Project, pid)
if proj:
d = proj.to_dict() if hasattr(proj, "to_dict") else {"id": proj.id, "title": proj.title}
d["permission"] = perm
d["is_shared"] = True
result.append(d)
return result
+264
View File
@@ -0,0 +1,264 @@
"""Sharing service — create/manage project and note shares."""
import logging
from sqlalchemy import select
from fabledassistant.models import async_session
from fabledassistant.models.group import Group, GroupMembership
from fabledassistant.models.note import Note
from fabledassistant.models.project import Project
from fabledassistant.models.share import NoteShare, ProjectShare
from fabledassistant.models.user import User
logger = logging.getLogger(__name__)
VALID_PERMISSIONS = {"viewer", "editor", "admin"}
# ---------------------------------------------------------------------------
# Project shares
# ---------------------------------------------------------------------------
async def share_project(
acting_user_id: int,
project_id: int,
*,
target_user_id: int | None = None,
target_group_id: int | None = None,
permission: str = "viewer",
) -> ProjectShare | None:
if permission not in VALID_PERMISSIONS:
return None
from fabledassistant.services.access import can_admin_project
if not await can_admin_project(acting_user_id, project_id):
return None
async with async_session() as session:
share = ProjectShare(
project_id=project_id,
shared_with_user_id=target_user_id,
shared_with_group_id=target_group_id,
permission=permission,
invited_by=acting_user_id,
)
session.add(share)
await session.commit()
await session.refresh(share)
return share
async def update_project_share(
acting_user_id: int, share_id: int, permission: str
) -> ProjectShare | None:
if permission not in VALID_PERMISSIONS:
return None
async with async_session() as session:
share = await session.get(ProjectShare, share_id)
if not share:
return None
from fabledassistant.services.access import can_admin_project
if not await can_admin_project(acting_user_id, share.project_id):
return None
share.permission = permission
await session.commit()
await session.refresh(share)
return share
async def remove_project_share(acting_user_id: int, share_id: int) -> bool:
async with async_session() as session:
share = await session.get(ProjectShare, share_id)
if not share:
return False
from fabledassistant.services.access import can_admin_project
if not await can_admin_project(acting_user_id, share.project_id):
return False
await session.delete(share)
await session.commit()
return True
async def list_project_shares(project_id: int) -> list[dict]:
async with async_session() as session:
shares = (await session.execute(
select(ProjectShare).where(ProjectShare.project_id == project_id)
)).scalars().all()
result = []
for s in shares:
d = s.to_dict()
if s.shared_with_user_id:
user = await session.get(User, s.shared_with_user_id)
d["username"] = user.username if user else None
if s.shared_with_group_id:
group = await session.get(Group, s.shared_with_group_id)
d["group_name"] = group.name if group else None
result.append(d)
return result
# ---------------------------------------------------------------------------
# Note shares
# ---------------------------------------------------------------------------
async def share_note(
acting_user_id: int,
note_id: int,
*,
target_user_id: int | None = None,
target_group_id: int | None = None,
permission: str = "viewer",
) -> NoteShare | None:
if permission not in VALID_PERMISSIONS:
return None
from fabledassistant.services.access import get_note_permission
perm = await get_note_permission(acting_user_id, note_id)
if perm not in ("admin", "owner"):
return None
async with async_session() as session:
share = NoteShare(
note_id=note_id,
shared_with_user_id=target_user_id,
shared_with_group_id=target_group_id,
permission=permission,
invited_by=acting_user_id,
)
session.add(share)
await session.commit()
await session.refresh(share)
return share
async def update_note_share(
acting_user_id: int, share_id: int, permission: str
) -> NoteShare | None:
if permission not in VALID_PERMISSIONS:
return None
async with async_session() as session:
share = await session.get(NoteShare, share_id)
if not share:
return None
from fabledassistant.services.access import get_note_permission
perm = await get_note_permission(acting_user_id, share.note_id)
if perm not in ("admin", "owner"):
return None
share.permission = permission
await session.commit()
await session.refresh(share)
return share
async def remove_note_share(acting_user_id: int, share_id: int) -> bool:
async with async_session() as session:
share = await session.get(NoteShare, share_id)
if not share:
return False
from fabledassistant.services.access import get_note_permission
perm = await get_note_permission(acting_user_id, share.note_id)
if perm not in ("admin", "owner"):
return False
await session.delete(share)
await session.commit()
return True
async def list_note_shares(note_id: int) -> list[dict]:
async with async_session() as session:
shares = (await session.execute(
select(NoteShare).where(NoteShare.note_id == note_id)
)).scalars().all()
result = []
for s in shares:
d = s.to_dict()
if s.shared_with_user_id:
user = await session.get(User, s.shared_with_user_id)
d["username"] = user.username if user else None
if s.shared_with_group_id:
group = await session.get(Group, s.shared_with_group_id)
d["group_name"] = group.name if group else None
result.append(d)
return result
# ---------------------------------------------------------------------------
# Shared-with-me
# ---------------------------------------------------------------------------
async def list_shared_with_me(user_id: int) -> dict:
"""All projects and notes shared with the user (directly or via group)."""
async with async_session() as session:
user_group_ids = (await session.execute(
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
)).scalars().all()
# --- Projects ---
proj_direct = (await session.execute(
select(ProjectShare).where(ProjectShare.shared_with_user_id == user_id)
)).scalars().all()
proj_group: list[ProjectShare] = []
if user_group_ids:
proj_group = (await session.execute(
select(ProjectShare).where(
ProjectShare.shared_with_group_id.in_(user_group_ids)
)
)).scalars().all()
seen_projects: dict[int, str] = {}
for share in list(proj_direct) + list(proj_group):
prev = seen_projects.get(share.project_id)
from fabledassistant.services.access import PERMISSION_RANK
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
seen_projects[share.project_id] = share.permission
projects = []
for pid, perm in seen_projects.items():
proj = await session.get(Project, pid)
if proj:
owner = await session.get(User, proj.user_id)
projects.append({
"id": proj.id,
"title": proj.title,
"description": proj.description,
"status": proj.status,
"color": proj.color,
"updated_at": proj.updated_at.isoformat(),
"owner_username": owner.username if owner else None,
"permission": perm,
})
# --- Notes / Tasks ---
note_direct = (await session.execute(
select(NoteShare).where(NoteShare.shared_with_user_id == user_id)
)).scalars().all()
note_group: list[NoteShare] = []
if user_group_ids:
note_group = (await session.execute(
select(NoteShare).where(
NoteShare.shared_with_group_id.in_(user_group_ids)
)
)).scalars().all()
seen_notes: dict[int, str] = {}
for share in list(note_direct) + list(note_group):
prev = seen_notes.get(share.note_id)
from fabledassistant.services.access import PERMISSION_RANK
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
seen_notes[share.note_id] = share.permission
notes = []
for nid, perm in seen_notes.items():
note = await session.get(Note, nid)
if note:
owner = await session.get(User, note.user_id)
notes.append({
"id": note.id,
"title": note.title,
"is_task": note.is_task,
"project_id": note.project_id,
"updated_at": note.updated_at.isoformat(),
"owner_username": owner.username if owner else None,
"permission": perm,
})
return {"projects": projects, "notes": notes}