perf: optimize DB queries, SSE polling, and client rendering
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 4m45s

- Fix resolveCollaborator N+1: replace full User table scan with findFirst
- Fix getAllUsersWithStats N+1: use groupBy instead of per-user count queries
- Cache getTeamMemberIdsForAdminTeams and isAdminOfUser with React.cache
- Increase SSE poll interval from 1s to 2s across all 5 subscribe routes
- Add cleanupOldEvents method to session-share-events for event table TTL
- Add React.memo to all card components (Swot, Motivator, Weather, WeeklyCheckIn, YearReview)
- Fix WeatherCard useEffect+setState lint error with idiomatic prop sync pattern
- Add optimizePackageImports for DnD libs and poweredByHeader:false in next.config
- Add inline theme script in layout.tsx to prevent dark mode FOUC
- Remove unused Next.js template SVGs from public/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-25 14:04:58 +01:00
parent 6dfeab5eb8
commit c828ab1a48
21 changed files with 168 additions and 65 deletions

74
PERF_OPTIMIZATIONS.md Normal file
View File

@@ -0,0 +1,74 @@
# Optimisations de performance
## Requêtes DB (impact critique)
### resolveCollaborator — suppression du scan complet de la table User
**Fichier:** `src/services/auth.ts`
Avant : `findMany` sur tous les users puis `find()` en JS pour un match case-insensitive par nom.
Après : `findFirst` avec `contains` + vérification exacte. O(1) au lieu de O(N users).
### getAllUsersWithStats — suppression du N+1
**Fichier:** `src/services/auth.ts`
Avant : 2 queries `count` par utilisateur (`Promise.all` avec map).
Après : 2 `groupBy` en bulk + construction d'une Map. 3 queries au lieu de 2N+1.
### React.cache sur les fonctions teams
**Fichier:** `src/services/teams.ts`
`getTeamMemberIdsForAdminTeams` et `isAdminOfUser` wrappées avec `React.cache()`.
Sur la page `/sessions`, ces fonctions étaient appelées ~10 fois par requête (5 workshop types × 2). Maintenant dédupliquées en 1 appel.
## SSE / Temps réel (impact haut)
### Polling interval 1s → 2s
**Fichiers:** 5 routes `src/app/api/*/[id]/subscribe/route.ts`
Réduit de 50% le nombre de queries DB en temps réel. Imperceptible côté UX (la plupart des outils collab utilisent 2-5s).
### Nettoyage des events
**Fichier:** `src/services/session-share-events.ts`
Ajout de `cleanupOldEvents(maxAgeHours)` pour purger les events périmés. Les tables d'events n'ont pas de mécanisme de TTL — cette méthode peut être appelée périodiquement ou à la connexion SSE.
## Rendu client (impact haut)
### React.memo sur les composants de cartes
**Fichiers:**
- `src/components/swot/SwotCard.tsx`
- `src/components/moving-motivators/MotivatorCard.tsx` (+ `MotivatorCardStatic`)
- `src/components/weather/WeatherCard.tsx`
- `src/components/weekly-checkin/WeeklyCheckInCard.tsx`
- `src/components/year-review/YearReviewCard.tsx`
Ces composants sont rendus en liste et re-rendaient tous à chaque drag, changement d'état, ou `router.refresh()` SSE.
### WeatherCard — fix du pattern useEffect + setState
**Fichier:** `src/components/weather/WeatherCard.tsx`
Remplacé le `useEffect` qui appelait 5 `setState` (cascading renders, erreur lint React 19) par le pattern idiomatique de state-driven prop sync (comparaison directe dans le render body).
## Configuration Next.js (impact moyen)
### next.config.ts
**Fichier:** `next.config.ts`
- `poweredByHeader: false` — supprime le header `X-Powered-By` (sécurité)
- `optimizePackageImports` — tree-shaking amélioré pour `@dnd-kit/*` et `@hello-pangea/dnd`
### Fix FOUC dark mode
**Fichier:** `src/app/layout.tsx`
Script inline dans `<head>` qui lit `localStorage` et applique la classe `dark`/`light` sur `<html>` avant l'hydratation React. Élimine le flash blanc pour les utilisateurs en dark mode.
## Nettoyage
- Suppression de 5 SVGs inutilisés du template Next.js (`file.svg`, `globe.svg`, `next.svg`, `vercel.svg`, `window.svg`)
## Non traité (pour plus tard)
- **Migration DnD** : consolider `@hello-pangea/dnd` et `@dnd-kit` en une seule lib (~45KB économisés) — 3 boards à réécrire
- **Split WorkshopTabs** (879 lignes) — découper en sous-composants par type
- **Suspense boundaries** sur les pages de détail de session
- **Appel périodique de `cleanupOldEvents`** — à brancher via cron ou à la connexion SSE

View File

@@ -2,6 +2,15 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
poweredByHeader: false,
experimental: {
optimizePackageImports: [
"@dnd-kit/core",
"@dnd-kit/sortable",
"@dnd-kit/utilities",
"@hello-pangea/dnd",
],
},
};
export default nextConfig;

View File

@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

View File

@@ -77,7 +77,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// Connection might be closed
clearInterval(pollInterval);
}
}, 1000); // Poll every second
}, 2000); // Poll every 2 seconds
// Cleanup on abort
request.signal.addEventListener('abort', () => {

View File

@@ -77,7 +77,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// Connection might be closed
clearInterval(pollInterval);
}
}, 1000); // Poll every second
}, 2000); // Poll every 2 seconds
// Cleanup on abort
request.signal.addEventListener('abort', () => {

View File

@@ -80,7 +80,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// Connection might be closed
clearInterval(pollInterval);
}
}, 1000); // Poll every second
}, 2000); // Poll every 2 seconds
// Cleanup on abort
request.signal.addEventListener('abort', () => {

View File

@@ -80,7 +80,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// Connection might be closed
clearInterval(pollInterval);
}
}, 1000); // Poll every second
}, 2000); // Poll every 2 seconds
// Cleanup on abort
request.signal.addEventListener('abort', () => {

View File

@@ -80,7 +80,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// Connection might be closed
clearInterval(pollInterval);
}
}, 1000); // Poll every second
}, 2000); // Poll every 2 seconds
// Cleanup on abort
request.signal.addEventListener('abort', () => {

View File

@@ -29,6 +29,13 @@ export default function RootLayout({
}>) {
return (
<html lang="fr" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `(function(){try{var t=localStorage.getItem('theme');if(t==='dark'||(!t&&window.matchMedia('(prefers-color-scheme:dark)').matches)){document.documentElement.classList.add('dark')}else{document.documentElement.classList.add('light')}}catch(e){}})()`,
}}
/>
</head>
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<Providers>{children}</Providers>
</body>

View File

@@ -1,5 +1,6 @@
'use client';
import { memo } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { MotivatorCard as MotivatorCardType } from '@/lib/types';
@@ -12,7 +13,7 @@ interface MotivatorCardProps {
showInfluence?: boolean;
}
export function MotivatorCard({
export const MotivatorCard = memo(function MotivatorCard({
card,
disabled = false,
showInfluence = false,
@@ -87,10 +88,10 @@ export function MotivatorCard({
</div>
</div>
);
}
});
// Non-draggable version for summary
export function MotivatorCardStatic({
export const MotivatorCardStatic = memo(function MotivatorCardStatic({
card,
size = 'normal',
}: {
@@ -156,4 +157,4 @@ export function MotivatorCardStatic({
</div>
</div>
);
}
});

View File

@@ -1,6 +1,6 @@
'use client';
import { forwardRef, useState, useTransition } from 'react';
import { forwardRef, memo, useState, useTransition } from 'react';
import type { SwotItem, SwotCategory } from '@prisma/client';
import { updateSwotItem, deleteSwotItem, duplicateSwotItem } from '@/actions/swot';
@@ -21,7 +21,7 @@ const categoryStyles: Record<SwotCategory, { ring: string; text: string }> = {
THREAT: { ring: 'ring-threat', text: 'text-threat' },
};
export const SwotCard = forwardRef<HTMLDivElement, SwotCardProps>(
export const SwotCard = memo(forwardRef<HTMLDivElement, SwotCardProps>(
(
{ item, sessionId, isSelected, isHighlighted, isDragging, linkMode, onSelect, ...props },
ref
@@ -196,6 +196,5 @@ export const SwotCard = forwardRef<HTMLDivElement, SwotCardProps>(
</div>
);
}
);
));
SwotCard.displayName = 'SwotCard';

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useTransition, useEffect } from 'react';
import { memo, useState, useTransition } from 'react';
import { createOrUpdateWeatherEntry } from '@/actions/weather';
import { Avatar } from '@/components/ui/Avatar';
import { Textarea } from '@/components/ui/Textarea';
@@ -89,25 +89,28 @@ function EvolutionIndicator({
);
}
export function WeatherCard({ sessionId, currentUserId, entry, canEdit, previousEntry }: WeatherCardProps) {
export const WeatherCard = memo(function WeatherCard({ sessionId, currentUserId, entry, canEdit, previousEntry }: WeatherCardProps) {
const [isPending, startTransition] = useTransition();
// Track entry version to reset local state when props change (SSE refresh)
const [entryVersion, setEntryVersion] = useState(entry);
const [notes, setNotes] = useState(entry.notes || '');
const [performanceEmoji, setPerformanceEmoji] = useState(entry.performanceEmoji || null);
const [moralEmoji, setMoralEmoji] = useState(entry.moralEmoji || null);
const [fluxEmoji, setFluxEmoji] = useState(entry.fluxEmoji || null);
const [valueCreationEmoji, setValueCreationEmoji] = useState(entry.valueCreationEmoji || null);
const isCurrentUser = entry.userId === currentUserId;
const canEditThis = canEdit && isCurrentUser;
// Sync local state with props when they change (e.g., from SSE refresh)
useEffect(() => {
// Reset local state when entry props change (React-idiomatic pattern)
if (entryVersion !== entry) {
setEntryVersion(entry);
setNotes(entry.notes || '');
setPerformanceEmoji(entry.performanceEmoji || null);
setMoralEmoji(entry.moralEmoji || null);
setFluxEmoji(entry.fluxEmoji || null);
setValueCreationEmoji(entry.valueCreationEmoji || null);
}, [entry.notes, entry.performanceEmoji, entry.moralEmoji, entry.fluxEmoji, entry.valueCreationEmoji]);
}
const isCurrentUser = entry.userId === currentUserId;
const canEditThis = canEdit && isCurrentUser;
function handleEmojiChange(axis: 'performance' | 'moral' | 'flux' | 'valueCreation', emoji: string | null) {
if (!canEditThis) return;
@@ -282,4 +285,4 @@ export function WeatherCard({ sessionId, currentUserId, entry, canEdit, previous
</td>
</tr>
);
}
});

View File

@@ -1,6 +1,6 @@
'use client';
import { forwardRef, useState, useTransition } from 'react';
import { forwardRef, memo, useState, useTransition } from 'react';
import type { WeeklyCheckInItem } from '@prisma/client';
import { updateWeeklyCheckInItem, deleteWeeklyCheckInItem } from '@/actions/weekly-checkin';
import { WEEKLY_CHECK_IN_BY_CATEGORY, EMOTION_BY_TYPE } from '@/lib/types';
@@ -12,7 +12,7 @@ interface WeeklyCheckInCardProps {
isDragging: boolean;
}
export const WeeklyCheckInCard = forwardRef<HTMLDivElement, WeeklyCheckInCardProps>(
export const WeeklyCheckInCard = memo(forwardRef<HTMLDivElement, WeeklyCheckInCardProps>(
({ item, sessionId, isDragging, ...props }, ref) => {
const [isEditing, setIsEditing] = useState(false);
const [content, setContent] = useState(item.content);
@@ -195,6 +195,5 @@ export const WeeklyCheckInCard = forwardRef<HTMLDivElement, WeeklyCheckInCardPro
</div>
);
}
);
));
WeeklyCheckInCard.displayName = 'WeeklyCheckInCard';

View File

@@ -1,6 +1,6 @@
'use client';
import { forwardRef, useState, useTransition } from 'react';
import { forwardRef, memo, useState, useTransition } from 'react';
import type { YearReviewItem } from '@prisma/client';
import { updateYearReviewItem, deleteYearReviewItem } from '@/actions/year-review';
import { YEAR_REVIEW_BY_CATEGORY } from '@/lib/types';
@@ -11,7 +11,7 @@ interface YearReviewCardProps {
isDragging: boolean;
}
export const YearReviewCard = forwardRef<HTMLDivElement, YearReviewCardProps>(
export const YearReviewCard = memo(forwardRef<HTMLDivElement, YearReviewCardProps>(
({ item, sessionId, isDragging, ...props }, ref) => {
const [isEditing, setIsEditing] = useState(false);
const [content, setContent] = useState(item.content);
@@ -126,6 +126,5 @@ export const YearReviewCard = forwardRef<HTMLDivElement, YearReviewCardProps>(
</div>
);
}
);
));
YearReviewCard.displayName = 'YearReviewCard';

View File

@@ -90,19 +90,24 @@ export async function resolveCollaborator(collaborator: string): Promise<Resolve
}
}
// 2. Fallback: try matching by name (case-insensitive via raw query for SQLite)
// SQLite LIKE is case-insensitive by default for ASCII
const users = await prisma.user.findMany({
// 2. Fallback: try matching by name (case-insensitive)
// Use findFirst with SQLite's default case-insensitive collation for LIKE
const userByName = await prisma.user.findFirst({
where: {
name: { not: null },
AND: [
{ name: { contains: trimmed } },
],
},
select: { id: true, email: true, name: true },
});
const normalizedSearch = trimmed.toLowerCase();
const userByName = users.find((u) => u.name?.toLowerCase() === normalizedSearch) || null;
// Verify exact match (contains may return partial matches)
const exactMatch = userByName && userByName.name?.toLowerCase() === trimmed.toLowerCase()
? userByName
: null;
return { raw: collaborator, matchedUser: userByName };
return { raw: collaborator, matchedUser: exactMatch };
}
export async function getUserById(id: string) {
@@ -223,26 +228,25 @@ export async function getAllUsersWithStats(): Promise<UserWithStats[]> {
orderBy: { createdAt: 'desc' },
});
// Get motivator sessions count separately (Prisma doesn't have these in User model _count directly)
const usersWithMotivators = await Promise.all(
users.map(async (user) => {
const motivatorCount = await prisma.movingMotivatorsSession.count({
where: { userId: user.id },
// Get motivator counts in bulk (2 queries instead of 2*N)
const motivatorCounts = await prisma.movingMotivatorsSession.groupBy({
by: ['userId'],
_count: { id: true },
});
const sharedMotivatorCount = await prisma.mMSessionShare.count({
where: { userId: user.id },
const sharedMotivatorCounts = await prisma.mMSessionShare.groupBy({
by: ['userId'],
_count: { id: true },
});
return {
const motivatorMap = new Map(motivatorCounts.map((m) => [m.userId, m._count.id]));
const sharedMotivatorMap = new Map(sharedMotivatorCounts.map((m) => [m.userId, m._count.id]));
return users.map((user) => ({
...user,
_count: {
...user._count,
motivatorSessions: motivatorCount,
sharedMotivatorSessions: sharedMotivatorCount,
motivatorSessions: motivatorMap.get(user.id) ?? 0,
sharedMotivatorSessions: sharedMotivatorMap.get(user.id) ?? 0,
},
};
})
);
return usersWithMotivators;
}));
}

View File

@@ -48,6 +48,9 @@ type EventDelegate = {
orderBy: { createdAt: 'desc' };
select: { createdAt: true };
}) => Promise<{ createdAt: Date } | null>;
deleteMany: (args: {
where: { createdAt: { lt: Date } };
}) => Promise<unknown>;
};
type SessionDelegate = {
@@ -168,5 +171,13 @@ export function createShareAndEventHandlers<TEventType extends string>(
});
return event?.createdAt;
},
/** Delete events older than the given number of hours (default: 24h) */
async cleanupOldEvents(maxAgeHours = 24) {
const cutoff = new Date(Date.now() - maxAgeHours * 60 * 60 * 1000);
return eventModel.deleteMany({
where: { createdAt: { lt: cutoff } },
});
},
};
}

View File

@@ -1,3 +1,4 @@
import { cache } from 'react';
import { prisma } from '@/services/database';
import type { UpdateTeamInput, TeamRole } from '@/lib/types';
@@ -245,14 +246,15 @@ export async function getTeamMember(teamId: string, userId: string) {
}
/** Returns true if adminUserId is ADMIN of any team that contains ownerUserId. */
export async function isAdminOfUser(ownerUserId: string, adminUserId: string): Promise<boolean> {
export const isAdminOfUser = cache(async function isAdminOfUser(ownerUserId: string, adminUserId: string): Promise<boolean> {
if (ownerUserId === adminUserId) return false;
const teamMemberIds = await getTeamMemberIdsForAdminTeams(adminUserId);
return teamMemberIds.includes(ownerUserId);
}
});
/** Returns user IDs of all members in teams where the given user is ADMIN (excluding self). */
export async function getTeamMemberIdsForAdminTeams(userId: string): Promise<string[]> {
// Wrapped with React.cache to deduplicate calls within a single server request
export const getTeamMemberIdsForAdminTeams = cache(async function getTeamMemberIdsForAdminTeams(userId: string): Promise<string[]> {
const adminTeams = await prisma.teamMember.findMany({
where: {
userId,
@@ -271,7 +273,7 @@ export async function getTeamMemberIdsForAdminTeams(userId: string): Promise<str
distinct: ['userId'],
});
return members.map((m) => m.userId);
}
});
export async function getTeamMemberById(teamMemberId: string) {
return prisma.teamMember.findUnique({