diff --git a/index.html b/index.html index c721de74..0d39cd46 100644 --- a/index.html +++ b/index.html @@ -13,6 +13,24 @@ Synco. + + + + + + + + + + + + + + + + + + diff --git a/src/composables/useAgenda.ts b/src/composables/useAgenda.ts index 1e727c5d..01d73acb 100644 --- a/src/composables/useAgenda.ts +++ b/src/composables/useAgenda.ts @@ -2,10 +2,9 @@ // Composable pour la gestion de l'Agenda // ============================================ -import { ref, computed } from 'vue'; +import { ref } from 'vue'; import sfetch from '@/assets/utils/sfetch'; import { useToast } from './useToast'; -import { user } from '@/assets/var'; import type { CalendarEvent, CalendarEventWithDetails, @@ -39,12 +38,6 @@ const myReminders = ref([]); const loading = ref(false); const error = ref(null); -// Agenda affiché : soi-même par défaut, ou un membre dirigé (cascade Équipes). -// `null` = "moi" (résolu dynamiquement via `user`, jamais figé au chargement du module). -const viewingUserId = ref(null); - -const isViewingSelf = computed(() => !viewingUserId.value || viewingUserId.value === user.value?.id); - // ============================================ // Fonctions utilitaires internes // ============================================ @@ -58,17 +51,16 @@ function buildOccurrencePath(eventId: string, occurrenceStartAt: string): string // ============================================ /** - * Récupère les occurrences dans une plage de dates, pour soi ou (via le - * cascade Équipes) pour un membre dirigé. + * Récupère mes propres occurrences dans une plage de dates. Pour les + * calendriers partagés par des collègues, voir useCalendarAccess.ts:: + * fetchSharedOccurrences (state séparé, ne touche jamais `occurrences` ici). */ -async function fetchRange(orgId: string, from: string, to: string, userId?: string): Promise { +async function fetchRange(orgId: string, from: string, to: string): Promise { loading.value = true; error.value = null; try { - const targetUserId = userId ?? viewingUserId.value ?? undefined; const params = new URLSearchParams({ from, to }); - if (targetUserId) params.set('userId', targetUserId); const res = await sfetch(`/api/orgs/${orgId}/agenda/events?${params.toString()}`); @@ -498,20 +490,6 @@ async function listMyReminders(orgId: string): Promise { + const viewMode = computed({ + get: () => { + if (viewModeSetting.value === 'month' || viewModeSetting.value === 'week' || viewModeSetting.value === 'day') { + return viewModeSetting.value; + } + return isLittleScreen.value ? 'day' : 'week'; + }, + set: (val: AgendaViewMode) => { + viewModeSetting.value = val; + } + }); + + return { viewMode }; +}; diff --git a/src/composables/useCalendarAccess.ts b/src/composables/useCalendarAccess.ts new file mode 100644 index 00000000..30d22140 --- /dev/null +++ b/src/composables/useCalendarAccess.ts @@ -0,0 +1,236 @@ +// ============================================ +// Composable pour le partage d'agenda entre collègues +// (CalendarAccessGrant — demande/invitation, lecture seule ou modification) +// ============================================ + +import { ref, computed } from 'vue'; +import sfetch from '@/assets/utils/sfetch'; +import { useToast } from './useToast'; +import type { + CalendarAccessGrantAsOwner, + CalendarAccessGrantAsGrantee, + CalendarAccessLevel, + ListMyGrantsResponse, + GrantResponse, + ApiErrorResponse, + MergedOccurrence +} from '@/types/agenda'; + +// Palette de couleurs par défaut proposées pour un nouveau calendrier partagé +// (réutilisée dans l'ordre, cycliquement, si l'utilisateur n'en choisit pas). +const DEFAULT_COLORS = ['#6366f1', '#ec4899', '#f59e0b', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444']; + +const asOwner = ref([]); +const asGrantee = ref([]); +const sharedOccurrences = ref([]); +const loading = ref(false); + +// Demandes reçues sur MON agenda (quelqu'un demande à me lire/modifier) — +// c'est moi qui décide. +const incomingRequests = computed(() => asOwner.value.filter(g => g.status === 'PENDING' && g.initiatedBy === 'REQUESTER')); +// Invitations reçues à consulter/modifier l'agenda d'un tiers — c'est moi qui décide. +const incomingInvites = computed(() => asGrantee.value.filter(g => g.status === 'PENDING' && g.initiatedBy === 'OWNER')); +// Mes propres demandes/invitations envoyées, en attente de réponse de l'autre partie. +const outgoingRequests = computed(() => asGrantee.value.filter(g => g.status === 'PENDING' && g.initiatedBy === 'REQUESTER')); +const outgoingInvites = computed(() => asOwner.value.filter(g => g.status === 'PENDING' && g.initiatedBy === 'OWNER')); +const acceptedSharedCalendars = computed(() => asGrantee.value.filter(g => g.status === 'ACCEPTED')); + +function hiddenKey(orgId: string): string { + return `agenda-hidden-calendars:${orgId}`; +} + +function getHiddenIds(orgId: string): Set { + try { + const raw = localStorage.getItem(hiddenKey(orgId)); + return new Set(raw ? JSON.parse(raw) : []); + } catch { + return new Set(); + } +} + +function isVisible(orgId: string, grantId: string): boolean { + return !getHiddenIds(orgId).has(grantId); +} + +function toggleVisibility(orgId: string, grantId: string): void { + const hidden = getHiddenIds(orgId); + if (hidden.has(grantId)) hidden.delete(grantId); + else hidden.add(grantId); + localStorage.setItem(hiddenKey(orgId), JSON.stringify([...hidden])); +} + +function colorFor(grant: CalendarAccessGrantAsGrantee, index: number): string { + return grant.color || DEFAULT_COLORS[index % DEFAULT_COLORS.length] || DEFAULT_COLORS[0]!; +} + +async function fetchGrants(orgId: string): Promise { + loading.value = true; + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access`); + if (!res.ok) { + const err: ApiErrorResponse = await res.json(); + throw new Error(err.error || "Erreur lors du chargement des accès à l'agenda"); + } + const data: ListMyGrantsResponse = await res.json(); + asOwner.value = data.asOwner; + asGrantee.value = data.asGrantee; + } catch (err: any) { + useToast().show(err.message || 'Erreur inconnue', 'error'); + } finally { + loading.value = false; + } +} + +async function requestAccess(orgId: string, ownerId: string, level: CalendarAccessLevel): Promise { + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access/request`, { + method: 'POST', + body: JSON.stringify({ ownerId, level }) + }); + if (!res.ok) { + const err: ApiErrorResponse = await res.json(); + throw new Error(err.error || "Erreur lors de la demande d'accès"); + } + useToast().show('Demande envoyée', 'success'); + await fetchGrants(orgId); + return true; + } catch (err: any) { + useToast().show(err.message || 'Erreur inconnue', 'error'); + return false; + } +} + +async function inviteAccess(orgId: string, granteeId: string, level: CalendarAccessLevel): Promise { + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access/invite`, { + method: 'POST', + body: JSON.stringify({ granteeId, level }) + }); + if (!res.ok) { + const err: ApiErrorResponse = await res.json(); + throw new Error(err.error || "Erreur lors de l'invitation"); + } + useToast().show('Invitation envoyée', 'success'); + await fetchGrants(orgId); + return true; + } catch (err: any) { + useToast().show(err.message || 'Erreur inconnue', 'error'); + return false; + } +} + +async function respondToGrant(orgId: string, grantId: string, action: 'ACCEPT' | 'DECLINE', level?: CalendarAccessLevel): Promise { + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access/${grantId}/respond`, { + method: 'PATCH', + body: JSON.stringify({ action, level }) + }); + if (!res.ok) { + const err: ApiErrorResponse = await res.json(); + throw new Error(err.error || 'Erreur lors de la réponse'); + } + const data: GrantResponse = await res.json(); + useToast().show(action === 'ACCEPT' ? 'Accès accordé' : 'Demande refusée', 'success'); + await fetchGrants(orgId); + return data.grant.status === 'ACCEPTED'; + } catch (err: any) { + useToast().show(err.message || 'Erreur inconnue', 'error'); + return false; + } +} + +async function revokeGrant(orgId: string, grantId: string): Promise { + // Capturé avant l'appel : une fois révoqué, le grant peut disparaître des + // listes rechargées par fetchGrants, on ne pourrait plus retrouver son + // ownerId pour purger sharedOccurrences. + const ownerId = asGrantee.value.find(g => g.id === grantId)?.ownerId; + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access/${grantId}`, { method: 'DELETE' }); + if (!res.ok) { + const err: ApiErrorResponse = await res.json(); + throw new Error(err.error || "Erreur lors du retrait de l'accès"); + } + useToast().show('Accès retiré', 'success'); + await fetchGrants(orgId); + if (ownerId) sharedOccurrences.value = sharedOccurrences.value.filter(o => o.sourceOwnerId !== ownerId); + return true; + } catch (err: any) { + useToast().show(err.message || 'Erreur inconnue', 'error'); + return false; + } +} + +async function setColor(orgId: string, grantId: string, color: string): Promise { + try { + const res = await sfetch(`/api/orgs/${orgId}/agenda/access/${grantId}/color`, { + method: 'PATCH', + body: JSON.stringify({ color }) + }); + if (!res.ok) return false; + await fetchGrants(orgId); + return true; + } catch { + return false; + } +} + +// Récupère et fusionne les occurrences de tous les calendriers partagés +// actuellement visibles (accès accepté + non masqué), taguées par calendrier +// source pour l'affichage superposé. N'affecte jamais l'agenda "moi" (voir +// useAgenda.ts::fetchRange, séparé). +async function fetchSharedOccurrences(orgId: string, from: string, to: string): Promise { + const visible = acceptedSharedCalendars.value.filter(g => isVisible(orgId, g.id)); + if (visible.length === 0) { + sharedOccurrences.value = []; + return; + } + + const results = await Promise.all(visible.map(async (grant, index) => { + try { + const params = new URLSearchParams({ from, to, userId: grant.ownerId }); + const res = await sfetch(`/api/orgs/${orgId}/agenda/events?${params.toString()}`); + if (!res.ok) return []; + const data = await res.json(); + const color = colorFor(grant, index); + return (data.occurrences || []).map((o: any) => ({ ...o, sourceOwnerId: grant.ownerId, sourceColor: color })); + } catch { + return []; + } + })); + + sharedOccurrences.value = results.flat(); +} + +function resetState(): void { + asOwner.value = []; + asGrantee.value = []; + sharedOccurrences.value = []; +} + +export function useCalendarAccess() { + return { + asOwner, + asGrantee, + sharedOccurrences, + loading, + incomingRequests, + incomingInvites, + outgoingRequests, + outgoingInvites, + acceptedSharedCalendars, + + fetchGrants, + requestAccess, + inviteAccess, + respondToGrant, + revokeGrant, + setColor, + fetchSharedOccurrences, + + isVisible, + toggleVisibility, + colorFor, + + resetState + }; +} diff --git a/src/composables/useNotification.ts b/src/composables/useNotification.ts index a775f9ce..3b7bc9d5 100644 --- a/src/composables/useNotification.ts +++ b/src/composables/useNotification.ts @@ -500,6 +500,14 @@ export function useNotification() { router.push(notification.data.route); } break; + // EVENT_*/CALENDAR_ACCESS_* (et tout futur type) n'ont pas de route + // dédiée codée en dur ici — le backend fournit data.route directement + // (voir agendaService.ts / calendarAccessService.ts). + default: + if (notification.data?.route) { + router.push(notification.data.route); + } + break; } }; diff --git a/src/composables/useSettingsItem.ts b/src/composables/useSettingsItem.ts index 5fafa204..fa16c982 100644 --- a/src/composables/useSettingsItem.ts +++ b/src/composables/useSettingsItem.ts @@ -29,12 +29,18 @@ const useSettingsItem = (item: string, defaultValue: any) => { const value = await sdb.get(currentUser, item); - if (value === undefined || value === null) + if (value === undefined || value === null) { cacheEntry.Item.value = defaultValue; - await sdb.set(currentUser, item, defaultValue); - } - else + // `defaultValue === undefined` veut dire "pas de valeur par + // défaut à retenir" (ex: dépend du device au moment de la + // lecture) — ne rien persister tant que l'utilisateur n'a + // pas fait de choix explicite (voir useAgendaViewMode.ts). + if (defaultValue !== undefined) { + await sdb.set(currentUser, item, defaultValue); + } + } + else { cacheEntry.Item.value = value; } diff --git a/src/types/agenda.ts b/src/types/agenda.ts index 79284982..3d8ee0f2 100644 --- a/src/types/agenda.ts +++ b/src/types/agenda.ts @@ -89,6 +89,10 @@ export interface EventReminder { export interface CalendarEventWithDetails extends CalendarEvent { attendees: EventAttendee[]; reminders: EventReminder[]; // rappels de l'appelant uniquement + // Renseigné quand l'événement a été créé par un tiers ayant un accès en + // modification sur cet agenda (voir CalendarAccessGrant) — creatorId reste + // le propriétaire de l'agenda. + createdByDelegateId: string | null; } // ============================================ @@ -143,6 +147,10 @@ export interface CreateEventDTO { color?: string | null; recurrenceRule?: RecurrenceRule | null; attendeeIds?: string[]; + // Créer l'événement pour le compte d'un tiers dont on a l'accès en + // modification (voir CalendarAccessGrant) — l'événement apparaît sur son + // agenda, pas sur le sien. + onBehalfOfUserId?: string; } // PATCH accepte un sous-ensemble quelconque des mêmes champs @@ -241,3 +249,66 @@ export interface AgendaRsvpUpdatedEvent { eventId: string; attendee: EventAttendee; } + +// ============================================ +// Partage d'agenda (CalendarAccessGrant) +// ============================================ +export type CalendarAccessLevel = 'READ' | 'WRITE'; +export type CalendarAccessStatus = 'PENDING' | 'ACCEPTED' | 'DECLINED' | 'REVOKED'; +export type CalendarGrantInitiator = 'REQUESTER' | 'OWNER'; + +export interface UserSummary { + id: string; + name: string; + pseudo: string | null; + avatarUrl: string | null; +} + +export interface CalendarAccessGrant { + id: string; + organizationId: string; + ownerId: string; + granteeId: string; + level: CalendarAccessLevel; + status: CalendarAccessStatus; + initiatedBy: CalendarGrantInitiator; + color: string | null; + requestedAt: string; + respondedAt: string | null; + createdAt: string; + updatedAt: string; +} + +export interface CalendarAccessGrantAsOwner extends CalendarAccessGrant { + grantee: UserSummary; +} + +export interface CalendarAccessGrantAsGrantee extends CalendarAccessGrant { + owner: UserSummary; +} + +export interface ListMyGrantsResponse { + asOwner: CalendarAccessGrantAsOwner[]; + asGrantee: CalendarAccessGrantAsGrantee[]; +} + +export interface GrantResponse { + grant: CalendarAccessGrant; +} + +export interface RevokeGrantResponse { + success: true; + grantId: string; +} + +export interface AgendaAccessUpdatedEvent { + grant: CalendarAccessGrant; +} + +// Occurrence taguée par calendrier source, construite côté client en +// fusionnant mon agenda avec les agendas partagés visibles (voir +// useAgenda.ts::fetchRange) — jamais renvoyée telle quelle par l'API. +export interface MergedOccurrence extends OccurrenceInstance { + sourceOwnerId: string; + sourceColor: string; +} diff --git a/src/types/types.ts b/src/types/types.ts index 343c2deb..f4f9fcec 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -1,5 +1,9 @@ export type ThreadType = 'text' | 'vocal'; -export type NotificationType = 'MESSAGE' | 'CALL' | 'MENTION' | 'INVITATION' | 'CUSTOM'; +export type NotificationType = + | 'MESSAGE' | 'CALL' | 'MENTION' | 'INVITATION' | 'CUSTOM' + | 'EVENT_INVITE' | 'EVENT_RSVP' | 'EVENT_REMINDER' + | 'CALENDAR_ACCESS_REQUEST' | 'CALENDAR_ACCESS_INVITE' + | 'CALENDAR_ACCESS_GRANTED' | 'CALENDAR_ACCESS_DECLINED' | 'CALENDAR_ACCESS_REVOKED'; // export type UserStatus = 'online' | 'dnd' | 'idle' | 'offline'; export interface StoredFile { diff --git a/src/views/OrgSpace/OrgLayout.vue b/src/views/OrgSpace/OrgLayout.vue index 1c784f5b..e5931306 100644 --- a/src/views/OrgSpace/OrgLayout.vue +++ b/src/views/OrgSpace/OrgLayout.vue @@ -49,7 +49,7 @@ import { watch, toRaw } from 'vue'; // Dans Tâches/Fichiers, la barre des membres se masque par défaut, sans // toucher à la préférence enregistrée : on la restaure dès qu'on revient // sur un salon ou toute autre page (ex: ThreadLayout, OrgAI, Settings). -const USERSBAR_AUTOHIDE_ROUTES = new Set(['TasksSpace', 'TasksGlobal', 'SpaceFiles']); +const USERSBAR_AUTOHIDE_ROUTES = new Set(['TasksSpace', 'TasksGlobal', 'SpaceFiles', 'AgendaGlobal']); watch(() => route.name, (name) => { setUsersBarHiddenByRoute(USERSBAR_AUTOHIDE_ROUTES.has(name as string)); diff --git a/src/views/OrgSpace/views/Agenda/AgendaView.vue b/src/views/OrgSpace/views/Agenda/AgendaView.vue index 01b763d7..75b865f3 100644 --- a/src/views/OrgSpace/views/Agenda/AgendaView.vue +++ b/src/views/OrgSpace/views/Agenda/AgendaView.vue @@ -41,6 +41,7 @@ @pick-day="goToDay" @navigate-month="navigateMiniMonth" /> +
@@ -66,6 +67,7 @@ @open-event="openEditModal" @create="onGridCreate" @reschedule="onReschedule" + @navigate="onWeekNavigate" /> route.params.orgId as string); -const { occurrences, loading, viewingUserId, fetchRange, updateEvent, updateOccurrence } = useAgenda(); +const { occurrences, loading, fetchRange, updateEvent, updateOccurrence } = useAgenda(); +const { sharedOccurrences, fetchGrants, fetchSharedOccurrences } = useCalendarAccess(); // ── Échéances de tâches affichées comme événements dans l'agenda ────── // Pseudo-occurrences synthétisées côté front à partir des tâches qui me @@ -174,14 +180,14 @@ const taskDeadlineOccurrences = computed(() => { }); }); -// Fusion événements réels + échéances de tâches pour l'affichage dans les grilles. -const displayOccurrences = computed(() => [...occurrences.value, ...taskDeadlineOccurrences.value]); +// Fusion événements réels (mon agenda + agendas partagés visibles, voir +// useCalendarAccess.ts) + échéances de tâches pour l'affichage dans les grilles. +const displayOccurrences = computed(() => [...occurrences.value, ...sharedOccurrences.value, ...taskDeadlineOccurrences.value]); -type ViewMode = 'month' | 'week' | 'day'; -const viewMode = ref('month'); +const { viewMode } = useAgendaViewMode(); const cursorDate = ref(new Date()); -const views: { id: ViewMode; label: string }[] = [ +const views: { id: AgendaViewMode; label: string }[] = [ { id: 'month', label: 'Mois' }, { id: 'week', label: 'Semaine' }, { id: 'day', label: 'Jour' } @@ -200,7 +206,10 @@ const periodLabel = computed(() => { return cursorDate.value.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' }); } if (viewMode.value === 'week') { - const start = startOfWeek(cursorDate.value); + // Fenêtre glissante de 7 jours à partir du curseur (pas calée sur + // lundi-dimanche, voir WeekGrid.vue::startOfWindow). + const start = new Date(cursorDate.value); + start.setHours(0, 0, 0, 0); const end = new Date(start); end.setDate(end.getDate() + 6); const startLabel = start.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' }); @@ -222,7 +231,8 @@ function computeRangeISO(): { from: string; to: string } { return { from: gridStart.toISOString(), to: gridEnd.toISOString() }; } if (viewMode.value === 'week') { - const start = startOfWeek(cursorDate.value); + const start = new Date(cursorDate.value); + start.setHours(0, 0, 0, 0); const end = new Date(start); end.setDate(end.getDate() + 6); end.setHours(23, 59, 59, 999); @@ -237,7 +247,10 @@ function computeRangeISO(): { from: string; to: string } { async function refetch() { const { from, to } = computeRangeISO(); - await fetchRange(orgId.value, from, to); + await Promise.all([ + fetchRange(orgId.value, from, to), + fetchSharedOccurrences(orgId.value, from, to) + ]); } function goPrev() { @@ -260,6 +273,15 @@ function goToday() { cursorDate.value = new Date(); } +// Scroll horizontal (trackpad/molette) en vue semaine — voir WeekGrid.vue. +// Décale la fenêtre glissante de 7 jours d'un jour à la fois (contrairement +// aux boutons précédent/suivant, qui paginent par bloc de 7 jours). +function onWeekNavigate(direction: 1 | -1) { + const d = new Date(cursorDate.value); + d.setDate(d.getDate() + direction); + cursorDate.value = d; +} + function goToDay(date: Date) { cursorDate.value = date; viewMode.value = 'day'; @@ -378,11 +400,20 @@ async function onReschedule({ occ, start, end }: { occ: OccurrenceInstance; star refetch(); } -watch([viewMode, cursorDate, viewingUserId], () => { +watch([viewMode, cursorDate], () => { refetch(); }); +// Un changement d'accès (demande acceptée/refusée, partage retiré...) +// affecte quels agendas sont superposables : on recharge la liste des +// accès puis les occurrences partagées visibles en découlent. +async function onAccessUpdated() { + await fetchGrants(orgId.value); + refetch(); +} + onMounted(async () => { + await fetchGrants(orgId.value); refetch(); loadTaskDeadlines(); @@ -393,6 +424,7 @@ onMounted(async () => { socket.value?.on('agenda:occurrence-updated', refetch); socket.value?.on('agenda:occurrence-cancelled', refetch); socket.value?.on('agenda:rsvp-updated', refetch); + socket.value?.on('agenda:access-updated', onAccessUpdated); }); onUnmounted(async () => { @@ -403,6 +435,7 @@ onUnmounted(async () => { socket.value?.off('agenda:occurrence-updated', refetch); socket.value?.off('agenda:occurrence-cancelled', refetch); socket.value?.off('agenda:rsvp-updated', refetch); + socket.value?.off('agenda:access-updated', onAccessUpdated); }); diff --git a/src/views/OrgSpace/views/Agenda/components/CalendarAccessPanel.vue b/src/views/OrgSpace/views/Agenda/components/CalendarAccessPanel.vue new file mode 100644 index 00000000..1128a31f --- /dev/null +++ b/src/views/OrgSpace/views/Agenda/components/CalendarAccessPanel.vue @@ -0,0 +1,412 @@ + + + + + diff --git a/src/views/OrgSpace/views/Agenda/components/EventChip.vue b/src/views/OrgSpace/views/Agenda/components/EventChip.vue index 85c793a5..031e0f54 100644 --- a/src/views/OrgSpace/views/Agenda/components/EventChip.vue +++ b/src/views/OrgSpace/views/Agenda/components/EventChip.vue @@ -15,11 +15,11 @@