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
@@ -0,0 +1,209 @@
"""Add groups, group_memberships, project_shares, note_shares, notifications tables.
Revision ID: 0025
Revises: 0024
Create Date: 2026-03-11
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0025"
down_revision = "0024"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"groups",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("name", sa.Text(), nullable=False, unique=True),
sa.Column("description", sa.Text()),
sa.Column(
"created_by",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="SET NULL"),
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
)
op.create_table(
"group_memberships",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"group_id",
sa.Integer(),
sa.ForeignKey("groups.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("role", sa.Text(), nullable=False, server_default="member"),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.UniqueConstraint("group_id", "user_id", name="uq_gm_group_user"),
)
op.create_index("idx_gm_user", "group_memberships", ["user_id"])
op.create_table(
"project_shares",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"project_id",
sa.Integer(),
sa.ForeignKey("projects.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"shared_with_user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
),
sa.Column(
"shared_with_group_id",
sa.Integer(),
sa.ForeignKey("groups.id", ondelete="CASCADE"),
),
sa.Column("permission", sa.Text(), nullable=False),
sa.Column(
"invited_by",
sa.Integer(),
sa.ForeignKey("users.id"),
nullable=False,
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.CheckConstraint(
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
name="ck_ps_exclusive_target",
),
)
op.create_index("idx_ps_project", "project_shares", ["project_id"])
op.execute(
"CREATE UNIQUE INDEX idx_ps_user ON project_shares(project_id, shared_with_user_id)"
" WHERE shared_with_user_id IS NOT NULL"
)
op.execute(
"CREATE UNIQUE INDEX idx_ps_group ON project_shares(project_id, shared_with_group_id)"
" WHERE shared_with_group_id IS NOT NULL"
)
op.create_table(
"note_shares",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"note_id",
sa.Integer(),
sa.ForeignKey("notes.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"shared_with_user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
),
sa.Column(
"shared_with_group_id",
sa.Integer(),
sa.ForeignKey("groups.id", ondelete="CASCADE"),
),
sa.Column("permission", sa.Text(), nullable=False),
sa.Column(
"invited_by",
sa.Integer(),
sa.ForeignKey("users.id"),
nullable=False,
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
sa.CheckConstraint(
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
name="ck_ns_exclusive_target",
),
)
op.execute(
"CREATE UNIQUE INDEX idx_ns_user ON note_shares(note_id, shared_with_user_id)"
" WHERE shared_with_user_id IS NOT NULL"
)
op.execute(
"CREATE UNIQUE INDEX idx_ns_group ON note_shares(note_id, shared_with_group_id)"
" WHERE shared_with_group_id IS NOT NULL"
)
op.create_table(
"notifications",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column(
"user_id",
sa.Integer(),
sa.ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("type", sa.Text(), nullable=False),
sa.Column(
"payload",
postgresql.JSONB(),
nullable=False,
server_default="{}",
),
sa.Column("read_at", sa.DateTime(timezone=True)),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.func.now(),
nullable=False,
),
)
op.execute(
"CREATE INDEX idx_notif_user_unread ON notifications(user_id, read_at)"
" WHERE read_at IS NULL"
)
def downgrade() -> None:
op.drop_table("notifications")
op.drop_table("note_shares")
op.drop_table("project_shares")
op.drop_table("group_memberships")
op.drop_table("groups")
+105
View File
@@ -75,6 +75,111 @@ export async function apiDelete(path: string): Promise<void> {
return handleResponse<void>(res, path);
}
// ---------------------------------------------------------------------------
// Sharing, Groups, Notifications, User search
// ---------------------------------------------------------------------------
export interface ShareEntry {
id: number
permission: string
shared_with_user_id: number | null
shared_with_group_id: number | null
username?: string
group_name?: string
invited_by: number
created_at: string
}
export interface GroupEntry {
id: number
name: string
description: string | null
created_by: number | null
member_count: number
is_member: boolean
created_at: string
updated_at: string
}
export interface GroupMember {
id: number
group_id: number
user_id: number
role: string
username: string
email: string | null
created_at: string
}
export interface NotificationEntry {
id: number
user_id: number
type: string
payload: Record<string, unknown>
read_at: string | null
created_at: string
}
export interface UserSearchResult {
id: number
username: string
email: string | null
}
// --- User search ---
export const searchUsers = (q: string) =>
apiGet<{ users: UserSearchResult[] }>(`/api/users/search?q=${encodeURIComponent(q)}`).then(r => r.users)
// --- Groups ---
export const listGroups = () => apiGet<{ groups: GroupEntry[] }>('/api/groups').then(r => r.groups)
export const createGroup = (name: string, description?: string) =>
apiPost<GroupEntry>('/api/groups', { name, description })
export const updateGroup = (id: number, data: { name?: string; description?: string }) =>
apiPatch<GroupEntry>(`/api/groups/${id}`, data)
export const deleteGroup = (id: number) => apiDelete(`/api/groups/${id}`)
export const getGroupDetail = (id: number) =>
apiGet<GroupEntry & { members: GroupMember[] }>(`/api/groups/${id}`)
export const listGroupMembers = (id: number) =>
apiGet<{ members: GroupMember[] }>(`/api/groups/${id}/members`).then(r => r.members)
export const addGroupMember = (groupId: number, userId: number, role: string) =>
apiPost<GroupMember>(`/api/groups/${groupId}/members`, { user_id: userId, role })
export const updateGroupMember = (groupId: number, userId: number, role: string) =>
apiPatch<GroupMember>(`/api/groups/${groupId}/members/${userId}`, { role })
export const removeGroupMember = (groupId: number, userId: number) =>
apiDelete(`/api/groups/${groupId}/members/${userId}`)
// --- Project shares ---
export const listProjectShares = (projectId: number) =>
apiGet<{ shares: ShareEntry[] }>(`/api/projects/${projectId}/shares`).then(r => r.shares)
export const createProjectShare = (projectId: number, body: { user_id?: number; group_id?: number; permission: string }) =>
apiPost<ShareEntry>(`/api/projects/${projectId}/shares`, body)
export const updateProjectShare = (projectId: number, shareId: number, permission: string) =>
apiPatch<ShareEntry>(`/api/projects/${projectId}/shares/${shareId}`, { permission })
export const deleteProjectShare = (projectId: number, shareId: number) =>
apiDelete(`/api/projects/${projectId}/shares/${shareId}`)
// --- Note / task shares ---
export const listNoteShares = (noteId: number) =>
apiGet<{ shares: ShareEntry[] }>(`/api/notes/${noteId}/shares`).then(r => r.shares)
export const createNoteShare = (noteId: number, body: { user_id?: number; group_id?: number; permission: string }) =>
apiPost<ShareEntry>(`/api/notes/${noteId}/shares`, body)
export const updateNoteShare = (noteId: number, shareId: number, permission: string) =>
apiPatch<ShareEntry>(`/api/notes/${noteId}/shares/${shareId}`, { permission })
export const deleteNoteShare = (noteId: number, shareId: number) =>
apiDelete(`/api/notes/${noteId}/shares/${shareId}`)
// --- Shared-with-me ---
export const getSharedWithMe = () =>
apiGet<{ projects: Record<string, unknown>[]; notes: Record<string, unknown>[] }>('/api/shared-with-me')
// --- In-app notifications ---
export const getNotifications = (all = false) =>
apiGet<{ notifications: NotificationEntry[] }>(`/api/notifications${all ? '?all=true' : ''}`).then(r => r.notifications)
export const getNotificationCount = () =>
apiGet<{ count: number }>('/api/notifications/count').then(r => r.count)
export const markNotificationRead = (id: number) => apiPost<void>(`/api/notifications/${id}/read`, {})
export const markAllNotificationsRead = () => apiPost<{ marked: number }>('/api/notifications/read-all', {})
export interface SSEStreamHandle {
close(): void;
/** Resolves when the stream closes (normally or via error/abort). */
+5
View File
@@ -6,6 +6,7 @@ import { useShortcuts } from "@/composables/useShortcuts";
import { useAuthStore } from "@/stores/auth";
import { useChatStore } from "@/stores/chat";
import AppLogo from "@/components/AppLogo.vue";
import NotificationBell from "@/components/NotificationBell.vue";
const { theme, toggleTheme } = useTheme();
const { toggleShortcuts } = useShortcuts();
@@ -76,6 +77,7 @@ router.afterEach(() => {
<router-link to="/tasks" class="nav-link">Tasks</router-link>
<router-link to="/chat" :class="['nav-link', { 'router-link-active': isChatActive }]">Chat</router-link>
<router-link to="/graph" class="nav-link">Graph</router-link>
<router-link to="/shared" class="nav-link">Shared</router-link>
</div>
<!-- Right: status + utilities + gear + user -->
@@ -85,6 +87,8 @@ router.afterEach(() => {
<span class="status-text">{{ statusShortLabel }}</span>
</span>
<NotificationBell />
<button class="btn-icon" @click="toggleShortcuts" title="Keyboard shortcuts (?)">?</button>
<button class="btn-icon" @click="toggleTheme" :title="`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`">
@@ -121,6 +125,7 @@ router.afterEach(() => {
<router-link to="/tasks" class="nav-link">Tasks</router-link>
<router-link to="/chat" :class="['nav-link', { 'router-link-active': isChatActive }]">Chat</router-link>
<router-link to="/graph" class="nav-link">Graph</router-link>
<router-link to="/shared" class="nav-link">Shared</router-link>
<div class="mobile-divider"></div>
<router-link to="/settings" class="nav-link">Settings</router-link>
<div class="mobile-divider"></div>
@@ -0,0 +1,100 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useNotificationsStore } from '@/stores/notifications'
import NotificationsPanel from './NotificationsPanel.vue'
const store = useNotificationsStore()
const open = ref(false)
const wrapRef = ref<HTMLElement | null>(null)
let pollInterval: ReturnType<typeof setInterval> | null = null
function toggle() {
open.value = !open.value
if (open.value) store.fetchAll()
}
function close() {
open.value = false
}
function onDocClick(e: MouseEvent) {
if (open.value && wrapRef.value && !wrapRef.value.contains(e.target as Node)) {
close()
}
}
onMounted(() => {
store.fetchCount()
pollInterval = setInterval(() => store.fetchCount(), 60_000)
document.addEventListener('click', onDocClick, true)
})
onUnmounted(() => {
if (pollInterval) clearInterval(pollInterval)
document.removeEventListener('click', onDocClick, true)
})
</script>
<template>
<div class="bell-wrap" ref="wrapRef">
<button
class="btn-bell"
:class="{ active: open }"
@click="toggle"
aria-label="Notifications"
:title="`${store.count} unread notification${store.count !== 1 ? 's' : ''}`"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
<path d="M13.73 21a2 2 0 0 1-3.46 0"/>
</svg>
<span v-if="store.count > 0" class="bell-badge" aria-live="polite">{{ store.count > 99 ? '99+' : store.count }}</span>
</button>
<NotificationsPanel v-if="open" @close="close" />
</div>
</template>
<style scoped>
.bell-wrap {
position: relative;
}
.btn-bell {
background: none;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
padding: 0.25rem 0.45rem;
cursor: pointer;
color: var(--color-text-muted);
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.btn-bell:hover,
.btn-bell.active {
background: var(--color-bg-card);
color: var(--color-text);
border-color: var(--color-primary);
}
.bell-badge {
position: absolute;
top: -5px;
right: -5px;
background: var(--color-danger, #ef4444);
color: #fff;
font-size: 0.6rem;
font-weight: 700;
min-width: 16px;
height: 16px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 3px;
line-height: 1;
pointer-events: none;
}
</style>
@@ -0,0 +1,156 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useNotificationsStore } from '@/stores/notifications'
import { relativeTime } from '@/composables/useRelativeTime'
const emit = defineEmits<{ close: [] }>()
const store = useNotificationsStore()
const router = useRouter()
const typeIcon: Record<string, string> = {
project_shared: '📁',
note_shared: '📝',
group_added: '👥',
}
async function handleClick(notif: { id: number; payload: Record<string, unknown> }) {
await store.markRead(notif.id)
const url = notif.payload.url as string | undefined
if (url) {
emit('close')
router.push(url)
}
}
onMounted(() => store.fetchAll())
</script>
<template>
<div class="notif-panel" role="dialog" aria-label="Notifications">
<header class="notif-panel-header">
<span class="notif-panel-title">Notifications</span>
<button
v-if="store.count > 0"
class="btn-mark-all"
@click="store.markAll()"
>Mark all read</button>
</header>
<ul class="notif-list" v-if="store.items.length">
<li
v-for="n in store.items"
:key="n.id"
class="notif-item"
@click="handleClick(n)"
>
<span class="notif-icon">{{ typeIcon[n.type] ?? '🔔' }}</span>
<div class="notif-body">
<p class="notif-msg">
<strong v-if="n.payload.invited_by">{{ n.payload.invited_by }}</strong>
{{ n.type === 'project_shared'
? ` shared "${n.payload.project_title}" with you as ${n.payload.permission}`
: n.type === 'note_shared'
? ` shared "${n.payload.note_title}" with you as ${n.payload.permission}`
: ` added you to "${n.payload.group_name}" as ${n.payload.role}` }}
</p>
<span class="notif-time">{{ relativeTime(n.created_at) }}</span>
</div>
<button class="btn-notif-close" @click.stop="store.markRead(n.id)" aria-label="Dismiss"></button>
</li>
</ul>
<div v-else class="notif-empty">No unread notifications</div>
</div>
</template>
<style scoped>
.notif-panel {
position: absolute;
top: calc(100% + 8px);
right: 0;
width: 340px;
max-height: 400px;
overflow-y: auto;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
z-index: 500;
}
.notif-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--color-border);
position: sticky;
top: 0;
background: var(--color-surface);
}
.notif-panel-title {
font-weight: 700;
font-size: 0.9rem;
}
.btn-mark-all {
background: none;
border: none;
color: var(--color-primary);
font-size: 0.78rem;
cursor: pointer;
padding: 0;
}
.btn-mark-all:hover { text-decoration: underline; }
.notif-list {
list-style: none;
padding: 0;
margin: 0;
}
.notif-item {
display: flex;
align-items: flex-start;
gap: 0.6rem;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--color-border);
cursor: pointer;
transition: background 0.1s;
}
.notif-item:last-child { border-bottom: none; }
.notif-item:hover { background: var(--color-hover); }
.notif-icon { font-size: 1.2rem; flex-shrink: 0; margin-top: 0.1rem; }
.notif-body { flex: 1; min-width: 0; }
.notif-msg {
margin: 0 0 0.2rem;
font-size: 0.85rem;
color: var(--color-text);
line-height: 1.4;
word-break: break-word;
}
.notif-time { font-size: 0.75rem; color: var(--color-muted); }
.btn-notif-close {
background: none;
border: none;
color: var(--color-muted);
cursor: pointer;
font-size: 0.8rem;
padding: 0.1rem 0.25rem;
flex-shrink: 0;
transition: color 0.1s;
}
.btn-notif-close:hover { color: var(--color-text); }
.notif-empty {
padding: 1.5rem;
text-align: center;
color: var(--color-muted);
font-size: 0.88rem;
font-style: italic;
}
</style>
+417
View File
@@ -0,0 +1,417 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
searchUsers,
listGroups,
listProjectShares,
createProjectShare,
updateProjectShare,
deleteProjectShare,
listNoteShares,
createNoteShare,
updateNoteShare,
deleteNoteShare,
type ShareEntry,
type GroupEntry,
type UserSearchResult,
} from '@/api/client'
const props = defineProps<{
resourceType: 'project' | 'note'
resourceId: number
resourceTitle: string
}>()
const emit = defineEmits<{ close: [] }>()
const addMode = ref<'user' | 'group'>('user')
const userQuery = ref('')
const userResults = ref<UserSearchResult[]>([])
const selectedUser = ref<UserSearchResult | null>(null)
const selectedGroupId = ref<number | ''>('')
const newPermission = ref('viewer')
const groups = ref<GroupEntry[]>([])
const shares = ref<ShareEntry[]>([])
const saving = ref(false)
let searchTimer: ReturnType<typeof setTimeout> | null = null
function debounceSearch() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(async () => {
if (userQuery.value.length < 2) { userResults.value = []; return }
userResults.value = await searchUsers(userQuery.value)
}, 300)
}
function selectUser(u: UserSearchResult) {
selectedUser.value = u
userQuery.value = u.username
userResults.value = []
}
async function loadShares() {
if (props.resourceType === 'project') {
shares.value = await listProjectShares(props.resourceId)
} else {
shares.value = await listNoteShares(props.resourceId)
}
}
async function addShare() {
if (saving.value) return
saving.value = true
try {
const body: { user_id?: number; group_id?: number; permission: string } = {
permission: newPermission.value,
}
if (addMode.value === 'user' && selectedUser.value) {
body.user_id = selectedUser.value.id
} else if (addMode.value === 'group' && selectedGroupId.value) {
body.group_id = selectedGroupId.value as number
} else {
return
}
if (props.resourceType === 'project') {
await createProjectShare(props.resourceId, body)
} else {
await createNoteShare(props.resourceId, body)
}
selectedUser.value = null
userQuery.value = ''
selectedGroupId.value = ''
newPermission.value = 'viewer'
await loadShares()
} finally {
saving.value = false
}
}
async function changePermission(share: ShareEntry, permission: string) {
if (props.resourceType === 'project') {
await updateProjectShare(props.resourceId, share.id, permission)
} else {
await updateNoteShare(props.resourceId, share.id, permission)
}
await loadShares()
}
async function removeShare(share: ShareEntry) {
if (props.resourceType === 'project') {
await deleteProjectShare(props.resourceId, share.id)
} else {
await deleteNoteShare(props.resourceId, share.id)
}
await loadShares()
}
onMounted(async () => {
groups.value = await listGroups()
await loadShares()
})
</script>
<template>
<Teleport to="body">
<div class="share-overlay" @click.self="emit('close')">
<div class="share-dialog" role="dialog" :aria-label="`Share ${resourceTitle}`">
<header class="share-header">
<h2 class="share-title">Share "{{ resourceTitle }}"</h2>
<button class="btn-close" @click="emit('close')" aria-label="Close"></button>
</header>
<!-- Add share form -->
<div class="share-add">
<div class="share-tabs">
<button :class="['share-tab', { active: addMode === 'user' }]" @click="addMode = 'user'">User</button>
<button :class="['share-tab', { active: addMode === 'group' }]" @click="addMode = 'group'">Group</button>
</div>
<div v-if="addMode === 'user'" class="share-target-form">
<div class="user-search-wrap">
<input
v-model="userQuery"
class="share-input"
placeholder="Search by username or email…"
@input="debounceSearch"
autocomplete="off"
/>
<ul v-if="userResults.length" class="user-results">
<li v-for="u in userResults" :key="u.id" @click="selectUser(u)" class="user-result-item">
<span class="user-result-name">{{ u.username }}</span>
<span class="user-result-email">{{ u.email }}</span>
</li>
</ul>
</div>
<template v-if="selectedUser">
<select v-model="newPermission" class="perm-select">
<option value="viewer">Viewer</option>
<option value="editor">Editor</option>
<option value="admin">Admin</option>
</select>
<button class="btn-add-share" @click="addShare" :disabled="saving">Add</button>
</template>
</div>
<div v-else class="share-target-form">
<select v-model="selectedGroupId" class="share-input">
<option value="" disabled>Select a group</option>
<option v-for="g in groups" :key="g.id" :value="g.id">{{ g.name }} ({{ g.member_count }} members)</option>
</select>
<select v-model="newPermission" class="perm-select">
<option value="viewer">Viewer</option>
<option value="editor">Editor</option>
<option value="admin">Admin</option>
</select>
<button class="btn-add-share" @click="addShare" :disabled="saving || !selectedGroupId">Add</button>
</div>
</div>
<!-- Current shares -->
<div class="shares-list-wrap">
<p class="shares-label">Current access</p>
<ul class="shares-list">
<li v-for="share in shares" :key="share.id" class="share-row">
<span class="share-target-icon">{{ share.shared_with_user_id ? '👤' : '👥' }}</span>
<span class="share-target-name">
{{ share.shared_with_user_id ? share.username : share.group_name }}
</span>
<select
class="perm-select-inline"
:value="share.permission"
@change="changePermission(share, ($event.target as HTMLSelectElement).value)"
>
<option value="viewer">Viewer</option>
<option value="editor">Editor</option>
<option value="admin">Admin</option>
</select>
<button class="btn-remove-share" @click="removeShare(share)" aria-label="Remove"></button>
</li>
<li v-if="!shares.length" class="shares-empty">Not shared with anyone yet</li>
</ul>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
.share-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.share-dialog {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
width: 480px;
max-width: 95vw;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.share-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--color-border);
}
.share-title {
font-family: 'Fraunces', Georgia, serif;
font-size: 1.1rem;
font-weight: 700;
margin: 0;
color: var(--color-text);
}
.btn-close {
background: none;
border: none;
color: var(--color-muted);
cursor: pointer;
font-size: 1.1rem;
padding: 0.25rem;
line-height: 1;
border-radius: 4px;
transition: color 0.15s;
}
.btn-close:hover { color: var(--color-text); }
.share-add {
padding: 1rem 1.5rem;
border-bottom: 1px solid var(--color-border);
}
.share-tabs {
display: flex;
gap: 0.25rem;
margin-bottom: 0.75rem;
}
.share-tab {
background: none;
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 0.3rem 0.8rem;
font-size: 0.82rem;
cursor: pointer;
color: var(--color-muted);
transition: all 0.15s;
}
.share-tab.active {
background: var(--color-primary);
border-color: var(--color-primary);
color: #fff;
}
.share-target-form {
display: flex;
gap: 0.5rem;
align-items: flex-start;
flex-wrap: wrap;
}
.user-search-wrap {
flex: 1;
position: relative;
}
.share-input {
width: 100%;
padding: 0.45rem 0.7rem;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-surface);
color: var(--color-text);
font-size: 0.9rem;
outline: none;
transition: border-color 0.15s;
}
.share-input:focus { border-color: var(--color-primary); }
.user-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 2px;
list-style: none;
padding: 0.25rem 0;
z-index: 10;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
max-height: 180px;
overflow-y: auto;
}
.user-result-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.8rem;
cursor: pointer;
transition: background 0.1s;
}
.user-result-item:hover { background: var(--color-hover); }
.user-result-name { font-weight: 600; font-size: 0.88rem; }
.user-result-email { color: var(--color-muted); font-size: 0.8rem; }
.perm-select {
padding: 0.45rem 0.5rem;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-surface);
color: var(--color-text);
font-size: 0.85rem;
cursor: pointer;
}
.btn-add-share {
padding: 0.45rem 1rem;
background: linear-gradient(135deg, #6366f1, #4f46e5);
color: #fff;
border: none;
border-radius: 6px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
transition: opacity 0.15s;
white-space: nowrap;
}
.btn-add-share:disabled { opacity: 0.5; cursor: not-allowed; }
.shares-list-wrap {
padding: 1rem 1.5rem 1.5rem;
}
.shares-label {
font-size: 0.78rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--color-muted);
margin: 0 0 0.5rem;
}
.shares-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.share-row {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border-radius: 8px;
background: var(--color-hover);
}
.share-target-icon { font-size: 1rem; flex-shrink: 0; }
.share-target-name { flex: 1; font-size: 0.88rem; font-weight: 500; }
.perm-select-inline {
padding: 0.25rem 0.4rem;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-surface);
color: var(--color-text);
font-size: 0.8rem;
cursor: pointer;
}
.btn-remove-share {
background: none;
border: none;
color: var(--color-muted);
cursor: pointer;
font-size: 0.9rem;
padding: 0.15rem 0.3rem;
border-radius: 4px;
transition: color 0.15s;
flex-shrink: 0;
}
.btn-remove-share:hover { color: var(--color-danger, #ef4444); }
.shares-empty {
color: var(--color-muted);
font-size: 0.85rem;
font-style: italic;
text-align: center;
padding: 0.75rem;
}
</style>
+5
View File
@@ -105,6 +105,11 @@ const router = createRouter({
name: "chat-conversation",
component: () => import("@/views/ChatView.vue"),
},
{
path: "/shared",
name: "shared-with-me",
component: () => import("@/views/SharedWithMeView.vue"),
},
{
path: "/settings",
name: "settings",
+45
View File
@@ -0,0 +1,45 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
getNotificationCount,
getNotifications,
markAllNotificationsRead,
markNotificationRead,
type NotificationEntry,
} from '@/api/client'
export const useNotificationsStore = defineStore('notifications', () => {
const count = ref(0)
const items = ref<NotificationEntry[]>([])
async function fetchCount() {
try {
count.value = await getNotificationCount()
} catch {
// silently ignore — polling failure shouldn't surface to user
}
}
async function fetchAll() {
try {
items.value = await getNotifications(false)
count.value = items.value.length
} catch {
//
}
}
async function markRead(id: number) {
await markNotificationRead(id)
items.value = items.value.filter(n => n.id !== id)
count.value = Math.max(0, count.value - 1)
}
async function markAll() {
await markAllNotificationsRead()
items.value = []
count.value = 0
}
return { count, items, fetchCount, fetchAll, markRead, markAll }
})
+24
View File
@@ -8,12 +8,14 @@ import { apiPost, apiGet } from "@/api/client";
import type { Note } from "@/types/note";
import TagPill from "@/components/TagPill.vue";
import TableOfContents from "@/components/TableOfContents.vue";
import ShareDialog from "@/components/ShareDialog.vue";
const route = useRoute();
const router = useRouter();
const store = useNotesStore();
const backlinks = ref<{ type: string; id: number; title: string }[]>([]);
const converting = ref(false);
const showShare = ref(false);
// Context enrichment
const projectTitle = ref<string | null>(null);
@@ -169,6 +171,7 @@ async function convertToTask() {
>
{{ converting ? "Converting..." : "Convert to Task" }}
</button>
<button class="btn-share" @click="showShare = true">Share</button>
</div>
<!-- Breadcrumb: parent project milestone -->
@@ -248,6 +251,14 @@ async function convertToTask() {
class="toc-sidebar"
/>
</div>
<ShareDialog
v-if="showShare && store.currentNote"
resource-type="note"
:resource-id="store.currentNote.id"
:resource-title="store.currentNote.title || '(untitled)'"
@close="showShare = false"
/>
</template>
<style src="@/assets/viewer-shared.css" />
@@ -334,6 +345,19 @@ async function convertToTask() {
cursor: default;
}
.btn-share {
padding: 0.3rem 0.75rem;
background: var(--color-bg-secondary);
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
color: var(--color-text-secondary);
cursor: pointer;
font-size: 0.85rem;
font-family: inherit;
transition: border-color 0.15s, color 0.15s;
}
.btn-share:hover { border-color: var(--color-primary); color: var(--color-primary); }
.note-title {
font-family: "Fraunces", Georgia, serif;
font-size: 2rem;
+24
View File
@@ -4,6 +4,7 @@ import { useRoute, useRouter } from "vue-router";
import { apiGet, apiPatch, apiDelete, apiPost } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import { relativeTime } from "@/composables/useRelativeTime";
import ShareDialog from "@/components/ShareDialog.vue";
interface Milestone {
id: number;
@@ -267,6 +268,7 @@ async function saveProject() {
}
const showDeleteConfirm = ref(false);
const showShare = ref(false);
async function confirmDelete() {
if (!project.value) return;
@@ -294,6 +296,7 @@ async function confirmDelete() {
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/></svg>
Workspace
</router-link>
<button v-if="project" class="btn-share" @click="showShare = true">Share</button>
<button v-if="project" class="btn-danger-outline" @click="showDeleteConfirm = true">Delete</button>
</div>
</div>
@@ -582,6 +585,14 @@ async function confirmDelete() {
</div>
</div>
</teleport>
<ShareDialog
v-if="showShare && project"
resource-type="project"
:resource-id="project.id"
:resource-title="project.title"
@close="showShare = false"
/>
</main>
</template>
@@ -634,6 +645,19 @@ async function confirmDelete() {
}
.btn-workspace:hover { box-shadow: 0 4px 14px rgba(99, 102, 241, 0.42); opacity: 0.95; color: #fff; }
.btn-share {
padding: 0.4rem 0.8rem;
background: none;
border: 1px solid var(--color-border);
color: var(--color-text-secondary);
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.85rem;
font-family: inherit;
transition: border-color 0.15s, color 0.15s;
}
.btn-share:hover { border-color: var(--color-primary); color: var(--color-primary); }
.btn-danger-outline {
padding: 0.4rem 0.8rem;
background: none;
+359 -3
View File
@@ -3,7 +3,7 @@ import { ref, watch, onMounted } from "vue";
import { useSettingsStore } from "@/stores/settings";
import { useAuthStore } from "@/stores/auth";
import { useToastStore } from "@/stores/toast";
import { apiGet, apiPost, apiPut, apiDelete } from "@/api/client";
import { apiGet, apiPost, apiPut, apiDelete, listGroups, createGroup, deleteGroup, listGroupMembers, addGroupMember, removeGroupMember, searchUsers, type GroupEntry, type GroupMember, type UserSearchResult } from "@/api/client";
import { usePushStore } from "@/stores/push";
import type { User } from "@/types/auth";
import PaginationBar from "@/components/PaginationBar.vue";
@@ -31,15 +31,91 @@ const restoring = ref(false);
const restoreFileInput = ref<HTMLInputElement | null>(null);
// Migrate stored "admin" → "config"; unknown tabs fall back to "general"
const VALID_TABS = new Set(["general", "account", "notifications", "integrations", "data", "config", "users", "logs"]);
const VALID_TABS = new Set(["general", "account", "notifications", "integrations", "data", "config", "users", "logs", "groups"]);
const _stored = localStorage.getItem("settings_tab") ?? "general";
const activeTab = ref(VALID_TABS.has(_stored) ? (_stored === "admin" ? "config" : _stored) : "general");
watch(activeTab, (v) => {
localStorage.setItem("settings_tab", v === "admin" ? "config" : v);
if (v === "users" && authStore.isAdmin) loadUsersPanel();
if (v === "logs" && authStore.isAdmin) loadLogsPanel();
if (v === "groups" && authStore.isAdmin) loadGroupsPanel();
});
// Groups management
const groups = ref<GroupEntry[]>([]);
const groupsLoading = ref(false);
const newGroupName = ref("");
const newGroupDesc = ref("");
const creatingGroup = ref(false);
const expandedGroupId = ref<number | null>(null);
const groupMembers = ref<Record<number, GroupMember[]>>({});
const groupMemberSearch = ref("");
const groupMemberResults = ref<UserSearchResult[]>([]);
let groupSearchTimer: ReturnType<typeof setTimeout> | null = null;
const groupMemberRole = ref("member");
async function loadGroupsPanel() {
groupsLoading.value = true;
try {
groups.value = await listGroups();
} finally {
groupsLoading.value = false;
}
}
async function createNewGroup() {
if (!newGroupName.value.trim() || creatingGroup.value) return;
creatingGroup.value = true;
try {
await createGroup(newGroupName.value.trim(), newGroupDesc.value.trim() || undefined);
newGroupName.value = "";
newGroupDesc.value = "";
await loadGroupsPanel();
} finally {
creatingGroup.value = false;
}
}
async function deleteGroupConfirm(g: GroupEntry) {
if (!confirm(`Delete group "${g.name}"? This cannot be undone.`)) return;
await deleteGroup(g.id);
if (expandedGroupId.value === g.id) expandedGroupId.value = null;
await loadGroupsPanel();
}
async function toggleGroupExpand(g: GroupEntry) {
if (expandedGroupId.value === g.id) {
expandedGroupId.value = null;
return;
}
expandedGroupId.value = g.id;
groupMemberSearch.value = "";
groupMemberResults.value = [];
groupMembers.value[g.id] = await listGroupMembers(g.id);
}
function debounceGroupMemberSearch() {
if (groupSearchTimer) clearTimeout(groupSearchTimer);
groupSearchTimer = setTimeout(async () => {
if (groupMemberSearch.value.length < 2) { groupMemberResults.value = []; return; }
groupMemberResults.value = await searchUsers(groupMemberSearch.value);
}, 300);
}
async function addMemberToGroup(groupId: number, user: UserSearchResult) {
await addGroupMember(groupId, user.id, groupMemberRole.value);
groupMembers.value[groupId] = await listGroupMembers(groupId);
groupMemberSearch.value = "";
groupMemberResults.value = [];
await loadGroupsPanel();
}
async function removeMemberFromGroup(groupId: number, userId: number) {
await removeGroupMember(groupId, userId);
groupMembers.value[groupId] = await listGroupMembers(groupId);
await loadGroupsPanel();
}
// Chat retention
const chatRetentionDays = ref(90);
const savingRetention = ref(false);
@@ -158,6 +234,7 @@ onMounted(async () => {
} catch {
// base URL not configured yet
}
if (activeTab.value === "groups") loadGroupsPanel();
}
});
@@ -703,7 +780,7 @@ function formatUserDate(iso: string): string {
<div v-if="authStore.isAdmin" class="sidebar-group">
<div class="sidebar-group-label">Admin</div>
<button
v-for="tab in ['config', 'users', 'logs']"
v-for="tab in ['config', 'users', 'groups', 'logs']"
:key="tab"
:class="['sidebar-item', { active: activeTab === tab }]"
@click="activeTab = tab"
@@ -1385,6 +1462,78 @@ function formatUserDate(iso: string): string {
</div>
<!-- Groups -->
<div v-if="authStore.isAdmin" v-show="activeTab === 'groups'" class="settings-grid">
<section class="settings-section full-width">
<h2>Groups</h2>
<p class="section-desc">Manage platform-wide groups for sharing projects and notes.</p>
<!-- Create group form -->
<div class="group-create-form">
<input v-model="newGroupName" class="input-field" placeholder="Group name" maxlength="100" @keydown.enter="createNewGroup" />
<input v-model="newGroupDesc" class="input-field" placeholder="Description (optional)" maxlength="255" @keydown.enter="createNewGroup" />
<button class="btn-primary" @click="createNewGroup" :disabled="creatingGroup || !newGroupName.trim()">
{{ creatingGroup ? 'Creating…' : 'Create Group' }}
</button>
</div>
<!-- Groups list -->
<div v-if="groupsLoading" class="loading-msg">Loading groups</div>
<div v-else-if="!groups.length" class="empty-msg">No groups yet.</div>
<div v-else class="groups-list">
<div v-for="g in groups" :key="g.id" class="group-card">
<div class="group-card-header">
<div class="group-card-info">
<span class="group-name">{{ g.name }}</span>
<span class="group-meta">{{ g.member_count }} member{{ g.member_count !== 1 ? 's' : '' }}</span>
<span v-if="g.description" class="group-desc">{{ g.description }}</span>
</div>
<div class="group-card-actions">
<button class="btn-sm" @click="toggleGroupExpand(g)">
{{ expandedGroupId === g.id ? 'Collapse' : 'Manage' }}
</button>
<button class="btn-sm btn-danger-sm" @click="deleteGroupConfirm(g)">Delete</button>
</div>
</div>
<!-- Members panel -->
<div v-if="expandedGroupId === g.id" class="group-members-panel">
<div class="members-search">
<div class="member-search-wrap">
<input
v-model="groupMemberSearch"
class="input-field"
placeholder="Search user to add…"
@input="debounceGroupMemberSearch"
autocomplete="off"
/>
<ul v-if="groupMemberResults.length" class="member-results">
<li v-for="u in groupMemberResults" :key="u.id" class="member-result-item" @click="addMemberToGroup(g.id, u)">
<span class="member-result-name">{{ u.username }}</span>
<span class="member-result-email">{{ u.email }}</span>
</li>
</ul>
</div>
<select v-model="groupMemberRole" class="role-select">
<option value="member">Member</option>
<option value="owner">Owner</option>
</select>
</div>
<ul class="members-list">
<li v-for="m in (groupMembers[g.id] || [])" :key="m.user_id" class="member-row">
<span class="member-name">{{ m.username }}</span>
<span class="member-role-badge" :class="`role-${m.role}`">{{ m.role }}</span>
<button class="btn-sm btn-danger-sm" @click="removeMemberFromGroup(g.id, m.user_id)">Remove</button>
</li>
<li v-if="!(groupMembers[g.id]?.length)" class="members-empty">No members yet.</li>
</ul>
</div>
</div>
</div>
</section>
</div>
</div><!-- end .settings-content -->
</main>
</template>
@@ -2056,4 +2205,211 @@ function formatUserDate(iso: string): string {
background: var(--color-bg-secondary); color: var(--color-text-muted);
margin-right: 0.25rem;
}
/* ── Groups tab ──────────────────────────────────────────────── */
.btn-primary {
padding: 0.4rem 0.9rem;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.875rem;
font-family: inherit;
white-space: nowrap;
}
.btn-primary:disabled { opacity: 0.6; cursor: default; }
.btn-primary:hover:not(:disabled) { opacity: 0.9; }
.input-field {
width: 100%;
padding: 0.4rem 0.6rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
background: var(--color-surface);
color: var(--color-text);
font-size: 0.875rem;
font-family: inherit;
outline: none;
transition: border-color 0.15s;
}
.input-field:focus { border-color: var(--color-primary); }
.group-create-form {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: 1.5rem;
align-items: center;
}
.group-create-form .input-field { flex: 1; min-width: 160px; }
.loading-msg, .empty-msg {
color: var(--color-text-muted);
font-style: italic;
font-size: 0.88rem;
padding: 0.5rem 0;
}
.groups-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.group-card {
border: 1px solid var(--color-border);
border-radius: var(--radius-md, 8px);
overflow: hidden;
}
.group-card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1rem;
background: var(--color-bg-secondary);
}
.group-card-info {
display: flex;
align-items: center;
gap: 0.75rem;
flex: 1;
min-width: 0;
}
.group-name {
font-weight: 600;
font-size: 0.9rem;
color: var(--color-text);
}
.group-meta {
font-size: 0.78rem;
color: var(--color-text-muted);
white-space: nowrap;
}
.group-desc {
font-size: 0.82rem;
color: var(--color-text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-card-actions {
display: flex;
gap: 0.35rem;
flex-shrink: 0;
}
.btn-sm {
padding: 0.25rem 0.6rem;
background: none;
border: 1px solid var(--color-border);
border-radius: 4px;
font-size: 0.78rem;
color: var(--color-text-secondary);
cursor: pointer;
font-family: inherit;
transition: border-color 0.15s, color 0.15s;
}
.btn-sm:hover { border-color: var(--color-primary); color: var(--color-primary); }
.btn-danger-sm:hover { border-color: var(--color-danger, #e74c3c); color: var(--color-danger, #e74c3c); }
.group-members-panel {
padding: 0.75rem 1rem 1rem;
border-top: 1px solid var(--color-border);
background: var(--color-surface);
}
.members-search {
display: flex;
gap: 0.5rem;
align-items: flex-start;
margin-bottom: 0.75rem;
}
.member-search-wrap {
flex: 1;
position: relative;
}
.member-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 2px;
list-style: none;
padding: 0.25rem 0;
z-index: 10;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
max-height: 160px;
overflow-y: auto;
}
.member-result-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.45rem 0.8rem;
cursor: pointer;
transition: background 0.1s;
}
.member-result-item:hover { background: var(--color-hover); }
.member-result-name { font-weight: 600; font-size: 0.85rem; }
.member-result-email { color: var(--color-text-muted); font-size: 0.78rem; }
.role-select {
padding: 0.4rem 0.5rem;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-surface);
color: var(--color-text);
font-size: 0.85rem;
cursor: pointer;
font-family: inherit;
}
.members-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.member-row {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.4rem 0.5rem;
border-radius: 6px;
background: var(--color-hover);
}
.member-name { flex: 1; font-size: 0.88rem; font-weight: 500; color: var(--color-text); }
.member-role-badge {
font-size: 0.7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 0.15rem 0.4rem;
border-radius: 4px;
}
.role-owner { background: color-mix(in srgb, var(--color-warning, #f59e0b) 15%, transparent); color: var(--color-warning, #f59e0b); }
.role-member { background: color-mix(in srgb, var(--color-muted) 15%, transparent); color: var(--color-muted); }
.members-empty {
color: var(--color-text-muted);
font-style: italic;
font-size: 0.82rem;
padding: 0.25rem 0.5rem;
}
</style>
+256
View File
@@ -0,0 +1,256 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getSharedWithMe } from '@/api/client'
interface SharedProject {
id: number
title: string
description: string | null
status: string
color: string | null
permission: string
owner_username: string
}
interface SharedNote {
id: number
title: string
is_task: boolean
permission: string
owner_username: string
}
const projects = ref<SharedProject[]>([])
const notes = ref<SharedNote[]>([])
const loading = ref(true)
onMounted(async () => {
try {
const data = await getSharedWithMe()
projects.value = data.projects as unknown as SharedProject[]
notes.value = data.notes as unknown as SharedNote[]
} finally {
loading.value = false
}
})
</script>
<template>
<div class="shared-page page-container">
<header class="page-header">
<h1 class="page-title">Shared with me</h1>
</header>
<div v-if="loading" class="loading-state">Loading</div>
<template v-else>
<!-- Projects -->
<section class="shared-section">
<h2 class="section-heading">Projects</h2>
<div v-if="projects.length" class="shared-grid">
<router-link
v-for="p in projects"
:key="p.id"
:to="`/projects/${p.id}`"
class="shared-card"
>
<div class="card-color-bar" :style="p.color ? `background: ${p.color}` : ''" />
<div class="card-body">
<div class="card-title">{{ p.title }}</div>
<div class="card-meta">
<span class="card-owner">by {{ p.owner_username }}</span>
<span class="perm-badge" :class="`perm-${p.permission}`">{{ p.permission }}</span>
</div>
<p v-if="p.description" class="card-desc">{{ p.description }}</p>
</div>
</router-link>
</div>
<p v-else class="empty-msg">No projects shared with you yet.</p>
</section>
<!-- Notes & Tasks -->
<section class="shared-section">
<h2 class="section-heading">Notes & Tasks</h2>
<div v-if="notes.length" class="shared-list">
<router-link
v-for="n in notes"
:key="n.id"
:to="n.is_task ? `/tasks/${n.id}` : `/notes/${n.id}`"
class="shared-row"
>
<span class="row-icon">{{ n.is_task ? '✓' : '📄' }}</span>
<span class="row-title">{{ n.title || '(untitled)' }}</span>
<span class="row-owner">by {{ n.owner_username }}</span>
<span class="perm-badge" :class="`perm-${n.permission}`">{{ n.permission }}</span>
</router-link>
</div>
<p v-else class="empty-msg">No notes or tasks shared with you yet.</p>
</section>
</template>
</div>
</template>
<style scoped>
.shared-page {
padding: 2rem;
max-width: 900px;
margin: 0 auto;
}
.page-header {
margin-bottom: 2rem;
}
.page-title {
font-family: 'Fraunces', Georgia, serif;
font-size: 1.8rem;
font-weight: 700;
margin: 0;
color: var(--color-text);
}
.loading-state {
color: var(--color-muted);
padding: 2rem;
text-align: center;
}
.shared-section {
margin-bottom: 2.5rem;
}
.section-heading {
font-size: 0.8rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.07em;
color: var(--color-muted);
margin: 0 0 0.75rem;
}
.shared-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 1rem;
}
.shared-card {
display: flex;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
overflow: hidden;
text-decoration: none;
transition: box-shadow 0.15s, transform 0.15s;
}
.shared-card:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
transform: translateY(-1px);
}
.card-color-bar {
width: 4px;
flex-shrink: 0;
background: var(--color-border);
}
.card-body {
padding: 0.9rem 1rem;
flex: 1;
min-width: 0;
}
.card-title {
font-weight: 600;
font-size: 0.95rem;
color: var(--color-text);
margin-bottom: 0.3rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.card-meta {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.4rem;
}
.card-owner {
font-size: 0.78rem;
color: var(--color-muted);
}
.card-desc {
font-size: 0.82rem;
color: var(--color-muted);
margin: 0;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.shared-list {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.shared-row {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 0.9rem;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
text-decoration: none;
transition: background 0.1s;
}
.shared-row:hover {
background: var(--color-hover);
}
.row-icon {
font-size: 0.9rem;
flex-shrink: 0;
color: var(--color-muted);
}
.row-title {
flex: 1;
font-size: 0.9rem;
color: var(--color-text);
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.row-owner {
font-size: 0.78rem;
color: var(--color-muted);
white-space: nowrap;
}
.perm-badge {
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 0.15rem 0.45rem;
border-radius: 4px;
white-space: nowrap;
}
.perm-viewer { background: color-mix(in srgb, var(--color-muted) 15%, transparent); color: var(--color-muted); }
.perm-editor { background: color-mix(in srgb, var(--color-primary) 15%, transparent); color: var(--color-primary); }
.perm-admin { background: color-mix(in srgb, var(--color-warning, #f59e0b) 15%, transparent); color: var(--color-warning, #f59e0b); }
.empty-msg {
color: var(--color-muted);
font-style: italic;
font-size: 0.88rem;
margin: 0;
padding: 1rem 0;
}
</style>
+24
View File
@@ -12,6 +12,7 @@ import StatusBadge from "@/components/StatusBadge.vue";
import PriorityBadge from "@/components/PriorityBadge.vue";
import TagPill from "@/components/TagPill.vue";
import TableOfContents from "@/components/TableOfContents.vue";
import ShareDialog from "@/components/ShareDialog.vue";
const route = useRoute();
const router = useRouter();
@@ -19,6 +20,7 @@ const store = useTasksStore();
const notesStore = useNotesStore();
const backlinks = ref<{ type: string; id: number; title: string }[]>([]);
const converting = ref(false);
const showShare = ref(false);
// Context enrichment
const projectTitle = ref<string | null>(null);
@@ -240,6 +242,7 @@ const subTaskProgress = computed(() => {
>
{{ converting ? "Converting..." : "Convert to Note" }}
</button>
<button class="btn-share" @click="showShare = true">Share</button>
</div>
<!-- Breadcrumb: parent task project milestone -->
@@ -364,6 +367,14 @@ const subTaskProgress = computed(() => {
class="toc-sidebar"
/>
</div>
<ShareDialog
v-if="showShare && store.currentTask"
resource-type="note"
:resource-id="store.currentTask.id"
:resource-title="store.currentTask.title || '(untitled)'"
@close="showShare = false"
/>
</template>
<style src="@/assets/viewer-shared.css" />
@@ -464,6 +475,19 @@ const subTaskProgress = computed(() => {
cursor: default;
}
.btn-share {
padding: 0.3rem 0.75rem;
background: var(--color-bg-secondary);
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
color: var(--color-text-secondary);
cursor: pointer;
font-size: 0.85rem;
font-family: inherit;
transition: border-color 0.15s, color 0.15s;
}
.btn-share:hover { border-color: var(--color-primary); color: var(--color-primary); }
.task-title {
font-family: "Fraunces", Georgia, serif;
font-size: 2rem;
+8
View File
@@ -22,6 +22,10 @@ from fabledassistant.routes.push import push_bp
from fabledassistant.routes.quick_capture import quick_capture_bp
from fabledassistant.routes.settings import settings_bp
from fabledassistant.routes.tasks import tasks_bp
from fabledassistant.routes.groups import groups_bp
from fabledassistant.routes.shares import shares_bp
from fabledassistant.routes.in_app_notifications import notifications_bp
from fabledassistant.routes.users import users_bp
STATIC_DIR = Path(__file__).parent / "static"
logger = logging.getLogger(__name__)
@@ -67,6 +71,10 @@ def create_app() -> Quart:
app.register_blueprint(settings_bp)
app.register_blueprint(task_logs_bp)
app.register_blueprint(tasks_bp)
app.register_blueprint(groups_bp)
app.register_blueprint(shares_bp)
app.register_blueprint(notifications_bp)
app.register_blueprint(users_bp)
@app.before_request
async def before_request():
+3
View File
@@ -35,3 +35,6 @@ from fabledassistant.models.milestone import Milestone # noqa: E402, F401
from fabledassistant.models.task_log import TaskLog # noqa: E402, F401
from fabledassistant.models.note_draft import NoteDraft # noqa: E402, F401
from fabledassistant.models.note_version import NoteVersion # noqa: E402, F401
from fabledassistant.models.group import Group, GroupMembership # noqa: E402, F401
from fabledassistant.models.share import NoteShare, ProjectShare # noqa: E402, F401
from fabledassistant.models.notification import Notification # noqa: E402, F401
+57
View File
@@ -0,0 +1,57 @@
from datetime import datetime, timezone
from sqlalchemy import ForeignKey, Integer, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from fabledassistant.models import Base
from fabledassistant.models.base import CreatedAtMixin, TimestampMixin
class Group(Base, TimestampMixin):
__tablename__ = "groups"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
description: Mapped[str | None] = mapped_column(Text)
created_by: Mapped[int | None] = mapped_column(
Integer, ForeignKey("users.id", ondelete="SET NULL")
)
memberships: Mapped[list["GroupMembership"]] = relationship(
"GroupMembership", back_populates="group", cascade="all, delete-orphan"
)
def to_dict(self) -> dict:
return {
"id": self.id,
"name": self.name,
"description": self.description,
"created_by": self.created_by,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
}
class GroupMembership(Base, CreatedAtMixin):
__tablename__ = "group_memberships"
__table_args__ = (UniqueConstraint("group_id", "user_id", name="uq_gm_group_user"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
group_id: Mapped[int] = mapped_column(
Integer, ForeignKey("groups.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
role: Mapped[str] = mapped_column(Text, nullable=False, default="member")
group: Mapped["Group"] = relationship("Group", back_populates="memberships")
def to_dict(self) -> dict:
return {
"id": self.id,
"group_id": self.group_id,
"user_id": self.user_id,
"role": self.role,
"created_at": self.created_at.isoformat(),
}
@@ -0,0 +1,31 @@
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from fabledassistant.models import Base
from fabledassistant.models.base import CreatedAtMixin
class Notification(Base, CreatedAtMixin):
__tablename__ = "notifications"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
# project_shared | note_shared | group_added
type: Mapped[str] = mapped_column(Text, nullable=False)
payload: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"type": self.type,
"payload": self.payload,
"read_at": self.read_at.isoformat() if self.read_at else None,
"created_at": self.created_at.isoformat(),
}
+79
View File
@@ -0,0 +1,79 @@
from sqlalchemy import CheckConstraint, ForeignKey, Integer, Text
from sqlalchemy.orm import Mapped, mapped_column
from fabledassistant.models import Base
from fabledassistant.models.base import TimestampMixin
class ProjectShare(Base, TimestampMixin):
__tablename__ = "project_shares"
__table_args__ = (
CheckConstraint(
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
name="ck_ps_exclusive_target",
),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
project_id: Mapped[int] = mapped_column(
Integer, ForeignKey("projects.id", ondelete="CASCADE"), nullable=False
)
shared_with_user_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE")
)
shared_with_group_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("groups.id", ondelete="CASCADE")
)
permission: Mapped[str] = mapped_column(Text, nullable=False)
invited_by: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id"), nullable=False
)
def to_dict(self) -> dict:
return {
"id": self.id,
"project_id": self.project_id,
"shared_with_user_id": self.shared_with_user_id,
"shared_with_group_id": self.shared_with_group_id,
"permission": self.permission,
"invited_by": self.invited_by,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
}
class NoteShare(Base, TimestampMixin):
__tablename__ = "note_shares"
__table_args__ = (
CheckConstraint(
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
name="ck_ns_exclusive_target",
),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
note_id: Mapped[int] = mapped_column(
Integer, ForeignKey("notes.id", ondelete="CASCADE"), nullable=False
)
shared_with_user_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE")
)
shared_with_group_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("groups.id", ondelete="CASCADE")
)
permission: Mapped[str] = mapped_column(Text, nullable=False)
invited_by: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id"), nullable=False
)
def to_dict(self) -> dict:
return {
"id": self.id,
"note_id": self.note_id,
"shared_with_user_id": self.shared_with_user_id,
"shared_with_group_id": self.shared_with_group_id,
"permission": self.permission,
"invited_by": self.invited_by,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
}
+112
View File
@@ -0,0 +1,112 @@
import asyncio
from quart import Blueprint, g, jsonify, request
from fabledassistant.auth import get_current_user_id, login_required
from fabledassistant.services import groups as group_svc
from fabledassistant.services.notifications import notify_group_added
groups_bp = Blueprint("groups", __name__, url_prefix="/api/groups")
@groups_bp.route("", methods=["GET"])
@login_required
async def list_groups():
uid = get_current_user_id()
return jsonify({"groups": await group_svc.list_groups(uid)})
@groups_bp.route("", methods=["POST"])
@login_required
async def create_group():
uid = get_current_user_id()
data = await request.get_json()
name = (data.get("name") or "").strip()
if not name:
return jsonify({"error": "Name is required"}), 400
try:
group = await group_svc.create_group(uid, name, data.get("description"))
except Exception:
return jsonify({"error": "Group name already taken"}), 409
return jsonify(group.to_dict()), 201
@groups_bp.route("/<int:group_id>", methods=["GET"])
@login_required
async def get_group(group_id: int):
group = await group_svc.get_group(group_id)
if not group:
return jsonify({"error": "Not found"}), 404
members = await group_svc.list_members(group_id)
return jsonify({**group.to_dict(), "members": members})
@groups_bp.route("/<int:group_id>", methods=["PATCH"])
@login_required
async def update_group(group_id: int):
uid = get_current_user_id()
data = await request.get_json()
updates = {k: v for k, v in data.items() if k in ("name", "description")}
group = await group_svc.update_group(uid, group_id, g.user.role == "admin", **updates)
if not group:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(group.to_dict())
@groups_bp.route("/<int:group_id>", methods=["DELETE"])
@login_required
async def delete_group(group_id: int):
uid = get_current_user_id()
deleted = await group_svc.delete_group(uid, group_id, g.user.role == "admin")
if not deleted:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
@groups_bp.route("/<int:group_id>/members", methods=["GET"])
@login_required
async def list_members(group_id: int):
members = await group_svc.list_members(group_id)
return jsonify({"members": members})
@groups_bp.route("/<int:group_id>/members", methods=["POST"])
@login_required
async def add_member(group_id: int):
uid = get_current_user_id()
data = await request.get_json()
target_uid = data.get("user_id")
role = data.get("role", "member")
if not target_uid:
return jsonify({"error": "user_id required"}), 400
if role not in ("owner", "member"):
return jsonify({"error": "role must be owner or member"}), 400
membership = await group_svc.add_member(uid, group_id, target_uid, role, g.user.role == "admin")
if not membership:
return jsonify({"error": "Forbidden, group not found, or user already a member"}), 403
asyncio.create_task(notify_group_added(group_id, role, uid, target_uid))
return jsonify(membership.to_dict()), 201
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["PATCH"])
@login_required
async def update_member(group_id: int, target_uid: int):
uid = get_current_user_id()
data = await request.get_json()
role = data.get("role")
if role not in ("owner", "member"):
return jsonify({"error": "role must be owner or member"}), 400
m = await group_svc.update_member_role(uid, group_id, target_uid, role, g.user.role == "admin")
if not m:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(m.to_dict())
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["DELETE"])
@login_required
async def remove_member(group_id: int, target_uid: int):
uid = get_current_user_id()
removed = await group_svc.remove_member(uid, group_id, target_uid, g.user.role == "admin")
if not removed:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
@@ -0,0 +1,44 @@
from quart import Blueprint, jsonify, request
from fabledassistant.auth import get_current_user_id, login_required
from fabledassistant.services.notifications import (
list_in_app_notifications,
mark_all_notifications_read,
mark_notification_read,
unread_notification_count,
)
notifications_bp = Blueprint("notifications", __name__, url_prefix="/api/notifications")
@notifications_bp.route("", methods=["GET"])
@login_required
async def list_notifications():
uid = get_current_user_id()
all_flag = request.args.get("all", "false").lower() == "true"
items = await list_in_app_notifications(uid, unread_only=not all_flag)
return jsonify({"notifications": items})
@notifications_bp.route("/count", methods=["GET"])
@login_required
async def get_count():
uid = get_current_user_id()
return jsonify({"count": await unread_notification_count(uid)})
@notifications_bp.route("/<int:notif_id>/read", methods=["POST"])
@login_required
async def mark_read(notif_id: int):
uid = get_current_user_id()
if not await mark_notification_read(uid, notif_id):
return jsonify({"error": "Not found"}), 404
return jsonify({"status": "ok"})
@notifications_bp.route("/read-all", methods=["POST"])
@login_required
async def mark_all_read():
uid = get_current_user_id()
count = await mark_all_notifications_read(uid)
return jsonify({"status": "ok", "marked": count})
+7 -3
View File
@@ -26,6 +26,7 @@ from fabledassistant.services.notes import (
get_backlinks,
get_note,
get_note_by_title,
get_note_for_user,
get_or_create_note_by_title,
list_notes,
update_note,
@@ -189,10 +190,13 @@ async def resolve_title_route():
@login_required
async def get_note_route(note_id: int):
uid = get_current_user_id()
note = await get_note(uid, note_id)
if note is None:
result = await get_note_for_user(uid, note_id)
if result is None:
return not_found("Note")
return jsonify(note.to_dict())
note, permission = result
data = note.to_dict()
data["permission"] = permission
return jsonify(data)
@notes_bp.route("/<int:note_id>", methods=["PUT"])
+14 -8
View File
@@ -11,8 +11,9 @@ from fabledassistant.services.projects import (
create_project,
delete_project,
get_project,
get_project_for_user,
get_project_summary,
list_projects,
list_projects_for_user,
update_project,
)
@@ -26,8 +27,8 @@ projects_bp = Blueprint("projects", __name__, url_prefix="/api/projects")
async def list_projects_route():
uid = get_current_user_id()
status = request.args.get("status")
projects = await list_projects(uid, status=status)
return jsonify({"projects": [p.to_dict() for p in projects]})
projects = await list_projects_for_user(uid, status=status)
return jsonify({"projects": projects})
@projects_bp.route("", methods=["POST"])
@@ -51,12 +52,16 @@ async def create_project_route():
@login_required
async def get_project_route(project_id: int):
uid = get_current_user_id()
project = await get_project(uid, project_id)
if project is None:
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
summary = await get_project_summary(uid, project_id)
project, permission = result
# Summary uses the project owner's uid for stats when viewer is not the owner
owner_uid = project.user_id or uid
summary = await get_project_summary(owner_uid, project_id)
data = project.to_dict()
data["summary"] = summary
data["permission"] = permission
return jsonify(data)
@@ -87,9 +92,10 @@ async def delete_project_route(project_id: int):
@login_required
async def get_project_notes_route(project_id: int):
uid = get_current_user_id()
project = await get_project(uid, project_id)
if project is None:
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, _ = result
# type filter: "note", "task", or None (both)
type_filter = request.args.get("type")
+128
View File
@@ -0,0 +1,128 @@
import asyncio
from quart import Blueprint, jsonify, request
from fabledassistant.auth import get_current_user_id, login_required
from fabledassistant.services import sharing as share_svc
from fabledassistant.services.access import can_admin_project, can_write_note
from fabledassistant.services.notifications import notify_note_shared, notify_project_shared
from fabledassistant.services.sharing import list_shared_with_me
shares_bp = Blueprint("shares", __name__)
# ---------------------------------------------------------------------------
# Project shares
# ---------------------------------------------------------------------------
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["GET"])
@login_required
async def list_project_shares(project_id: int):
uid = get_current_user_id()
if not await can_admin_project(uid, project_id):
return jsonify({"error": "Forbidden"}), 403
return jsonify({"shares": await share_svc.list_project_shares(project_id)})
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["POST"])
@login_required
async def create_project_share(project_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.share_project(
uid, project_id,
target_user_id=data.get("user_id"),
target_group_id=data.get("group_id"),
permission=data.get("permission", "viewer"),
)
if not share:
return jsonify({"error": "Forbidden or invalid permission"}), 403
asyncio.create_task(notify_project_shared(
project_id, share.permission, uid,
data.get("user_id"), data.get("group_id"),
))
return jsonify(share.to_dict()), 201
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["PATCH"])
@login_required
async def update_project_share(project_id: int, share_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.update_project_share(uid, share_id, data.get("permission", ""))
if not share:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(share.to_dict())
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["DELETE"])
@login_required
async def remove_project_share(project_id: int, share_id: int):
uid = get_current_user_id()
if not await share_svc.remove_project_share(uid, share_id):
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
# ---------------------------------------------------------------------------
# Note / task shares
# ---------------------------------------------------------------------------
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["GET"])
@login_required
async def list_note_shares(note_id: int):
uid = get_current_user_id()
if not await can_write_note(uid, note_id):
return jsonify({"error": "Forbidden"}), 403
return jsonify({"shares": await share_svc.list_note_shares(note_id)})
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["POST"])
@login_required
async def create_note_share(note_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.share_note(
uid, note_id,
target_user_id=data.get("user_id"),
target_group_id=data.get("group_id"),
permission=data.get("permission", "viewer"),
)
if not share:
return jsonify({"error": "Forbidden or invalid permission"}), 403
asyncio.create_task(notify_note_shared(
note_id, share.permission, uid,
data.get("user_id"), data.get("group_id"),
))
return jsonify(share.to_dict()), 201
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["PATCH"])
@login_required
async def update_note_share(note_id: int, share_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.update_note_share(uid, share_id, data.get("permission", ""))
if not share:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(share.to_dict())
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["DELETE"])
@login_required
async def remove_note_share(note_id: int, share_id: int):
uid = get_current_user_id()
if not await share_svc.remove_note_share(uid, share_id):
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
# ---------------------------------------------------------------------------
# Shared-with-me
# ---------------------------------------------------------------------------
@shares_bp.route("/api/shared-with-me", methods=["GET"])
@login_required
async def shared_with_me():
uid = get_current_user_id()
return jsonify(await list_shared_with_me(uid))
+5 -2
View File
@@ -7,6 +7,7 @@ from fabledassistant.services.notes import (
create_note,
delete_note,
get_note,
get_note_for_user,
list_notes,
update_note,
)
@@ -99,10 +100,12 @@ async def create_task_route():
@login_required
async def get_task_route(task_id: int):
uid = get_current_user_id()
task = await get_note(uid, task_id)
if task is None:
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task, permission = result
data = task.to_dict()
data["permission"] = permission
if task.parent_id:
parent = await get_note(uid, task.parent_id)
data["parent_title"] = parent.title if parent else None
+29
View File
@@ -0,0 +1,29 @@
from quart import Blueprint, jsonify, request
from sqlalchemy import or_, select
from fabledassistant.auth import get_current_user_id, login_required
from fabledassistant.models import async_session
from fabledassistant.models.user import User
users_bp = Blueprint("users", __name__, url_prefix="/api/users")
@users_bp.route("/search", methods=["GET"])
@login_required
async def search_users():
uid = get_current_user_id()
q = (request.args.get("q") or "").strip()
if len(q) < 2:
return jsonify({"users": []})
like = f"{q}%"
async with async_session() as session:
users = (await session.execute(
select(User).where(
User.id != uid,
or_(User.username.ilike(like), User.email.ilike(like)),
).limit(10)
)).scalars().all()
return jsonify({"users": [
{"id": u.id, "username": u.username, "email": u.email}
for u in users
]})
+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}