feat: refactor session retrieval logic to utilize generic session queries, enhancing code maintainability and reducing duplication across session types
This commit is contained in:
@@ -1,198 +1,93 @@
|
||||
import { prisma } from '@/services/database';
|
||||
import { getTeamMemberIdsForAdminTeams, isAdminOfUser } from '@/services/teams';
|
||||
import { getTeamMemberIdsForAdminTeams } from '@/services/teams';
|
||||
import { createSessionPermissionChecks } from '@/services/session-permissions';
|
||||
import { createShareAndEventHandlers } from '@/services/session-share-events';
|
||||
import {
|
||||
mergeSessionsByUserId,
|
||||
fetchTeamCollaboratorSessions,
|
||||
getSessionByIdGeneric,
|
||||
} from '@/services/session-queries';
|
||||
import { getWeekBounds } from '@/lib/date-utils';
|
||||
import type { ShareRole } from '@prisma/client';
|
||||
|
||||
const weatherInclude = {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
shares: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
_count: { select: { entries: true } },
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Weather Session CRUD
|
||||
// ============================================
|
||||
|
||||
export async function getWeatherSessionsByUserId(userId: string) {
|
||||
// Get owned sessions + shared sessions
|
||||
const [owned, shared] = await Promise.all([
|
||||
prisma.weatherSession.findMany({
|
||||
where: { userId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
shares: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
entries: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
}),
|
||||
prisma.weatherSessionShare.findMany({
|
||||
where: { userId },
|
||||
include: {
|
||||
session: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
shares: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
entries: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
// Mark owned sessions and merge with shared
|
||||
const ownedWithRole = owned.map((s) => ({
|
||||
...s,
|
||||
isOwner: true as const,
|
||||
role: 'OWNER' as const,
|
||||
}));
|
||||
const sharedWithRole = shared.map((s) => ({
|
||||
...s.session,
|
||||
isOwner: false as const,
|
||||
role: s.role,
|
||||
sharedAt: s.createdAt,
|
||||
}));
|
||||
|
||||
const allSessions = [...ownedWithRole, ...sharedWithRole].sort(
|
||||
(a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
|
||||
return mergeSessionsByUserId(
|
||||
(uid) =>
|
||||
prisma.weatherSession.findMany({
|
||||
where: { userId: uid },
|
||||
include: weatherInclude,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
}),
|
||||
(uid) =>
|
||||
prisma.weatherSessionShare.findMany({
|
||||
where: { userId: uid },
|
||||
include: { session: { include: weatherInclude } },
|
||||
}),
|
||||
userId
|
||||
);
|
||||
|
||||
return allSessions;
|
||||
}
|
||||
|
||||
/** Sessions owned by team members (where user is team admin) that are NOT shared with the user. */
|
||||
export async function getTeamCollaboratorSessionsForAdmin(userId: string) {
|
||||
const teamMemberIds = await getTeamMemberIdsForAdminTeams(userId);
|
||||
if (teamMemberIds.length === 0) return [];
|
||||
|
||||
const sessions = await prisma.weatherSession.findMany({
|
||||
where: {
|
||||
userId: { in: teamMemberIds },
|
||||
shares: { none: { userId } },
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
shares: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
},
|
||||
_count: { select: { entries: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
|
||||
return sessions.map((s) => ({
|
||||
...s,
|
||||
isOwner: false as const,
|
||||
role: 'VIEWER' as const,
|
||||
isTeamCollab: true as const,
|
||||
canEdit: true as const, // Admin has full rights on team member sessions
|
||||
}));
|
||||
return fetchTeamCollaboratorSessions(
|
||||
(teamMemberIds, uid) =>
|
||||
prisma.weatherSession.findMany({
|
||||
where: { userId: { in: teamMemberIds }, shares: { none: { userId: uid } } },
|
||||
include: weatherInclude,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
}),
|
||||
getTeamMemberIdsForAdminTeams,
|
||||
userId
|
||||
);
|
||||
}
|
||||
|
||||
const weatherByIdInclude = {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
entries: {
|
||||
include: { user: { select: { id: true, name: true, email: true } } },
|
||||
orderBy: { createdAt: 'asc' } as const,
|
||||
},
|
||||
shares: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
};
|
||||
|
||||
export async function getWeatherSessionById(sessionId: string, userId: string) {
|
||||
// Check if user owns the session, has it shared, or is team admin of owner
|
||||
let session = await prisma.weatherSession.findFirst({
|
||||
where: {
|
||||
id: sessionId,
|
||||
OR: [
|
||||
{ userId }, // Owner
|
||||
{ shares: { some: { userId } } }, // Shared with user
|
||||
],
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
entries: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
shares: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
const raw = await prisma.weatherSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
entries: {
|
||||
include: { user: { select: { id: true, name: true, email: true } } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
shares: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
},
|
||||
});
|
||||
if (!raw || !(await isAdminOfUser(raw.userId, userId))) return null;
|
||||
session = raw;
|
||||
}
|
||||
|
||||
// Determine user's role
|
||||
const isOwner = session.userId === userId;
|
||||
const share = session.shares.find((s) => s.userId === userId);
|
||||
const isAdminOfOwner = !isOwner && !share && (await isAdminOfUser(session.userId, userId));
|
||||
const role = isOwner ? ('OWNER' as const) : share?.role || ('VIEWER' as const);
|
||||
const canEdit = isOwner || role === 'EDITOR' || isAdminOfOwner;
|
||||
|
||||
return { ...session, isOwner, role, canEdit };
|
||||
return getSessionByIdGeneric(
|
||||
sessionId,
|
||||
userId,
|
||||
(sid, uid) =>
|
||||
prisma.weatherSession.findFirst({
|
||||
where: { id: sid, OR: [{ userId: uid }, { shares: { some: { userId: uid } } }] },
|
||||
include: weatherByIdInclude,
|
||||
}),
|
||||
(sid) =>
|
||||
prisma.weatherSession.findUnique({ where: { id: sid }, include: weatherByIdInclude })
|
||||
);
|
||||
}
|
||||
|
||||
// Check if user can access session (owner, shared, or team admin of owner)
|
||||
export async function canAccessWeatherSession(sessionId: string, userId: string) {
|
||||
const count = await prisma.weatherSession.count({
|
||||
where: {
|
||||
id: sessionId,
|
||||
OR: [{ userId }, { shares: { some: { userId } } }],
|
||||
},
|
||||
});
|
||||
if (count > 0) return true;
|
||||
const session = await prisma.weatherSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { userId: true },
|
||||
});
|
||||
return session ? isAdminOfUser(session.userId, userId) : false;
|
||||
}
|
||||
const weatherPermissions = createSessionPermissionChecks(prisma.weatherSession);
|
||||
|
||||
// Check if user can edit session (owner, EDITOR role, or team admin of owner)
|
||||
export async function canEditWeatherSession(sessionId: string, userId: string) {
|
||||
const count = await prisma.weatherSession.count({
|
||||
where: {
|
||||
id: sessionId,
|
||||
OR: [{ userId }, { shares: { some: { userId, role: 'EDITOR' } } }],
|
||||
},
|
||||
});
|
||||
if (count > 0) return true;
|
||||
const session = await prisma.weatherSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { userId: true },
|
||||
});
|
||||
return session ? isAdminOfUser(session.userId, userId) : false;
|
||||
}
|
||||
const weatherShareEvents = createShareAndEventHandlers<
|
||||
'ENTRY_CREATED' | 'ENTRY_UPDATED' | 'ENTRY_DELETED' | 'SESSION_UPDATED'
|
||||
>(
|
||||
prisma.weatherSession,
|
||||
prisma.weatherSessionShare,
|
||||
prisma.weatherSessionEvent,
|
||||
weatherPermissions.canAccess
|
||||
);
|
||||
|
||||
// Check if user can delete session (owner or team admin only - NOT EDITOR)
|
||||
export async function canDeleteWeatherSession(sessionId: string, userId: string) {
|
||||
const session = await prisma.weatherSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!session) return false;
|
||||
return session.userId === userId || isAdminOfUser(session.userId, userId);
|
||||
}
|
||||
export const canAccessWeatherSession = weatherPermissions.canAccess;
|
||||
export const canEditWeatherSession = weatherPermissions.canEdit;
|
||||
export const canDeleteWeatherSession = weatherPermissions.canDelete;
|
||||
|
||||
export async function createWeatherSession(userId: string, data: { title: string; date?: Date }) {
|
||||
return prisma.weatherSession.create({
|
||||
@@ -286,49 +181,7 @@ export async function deleteWeatherEntry(sessionId: string, userId: string) {
|
||||
// Session Sharing
|
||||
// ============================================
|
||||
|
||||
export async function shareWeatherSession(
|
||||
sessionId: string,
|
||||
ownerId: string,
|
||||
targetEmail: string,
|
||||
role: ShareRole = 'EDITOR'
|
||||
) {
|
||||
// Verify owner
|
||||
const session = await prisma.weatherSession.findFirst({
|
||||
where: { id: sessionId, userId: ownerId },
|
||||
});
|
||||
if (!session) {
|
||||
throw new Error('Session not found or not owned');
|
||||
}
|
||||
|
||||
// Find target user
|
||||
const targetUser = await prisma.user.findUnique({
|
||||
where: { email: targetEmail },
|
||||
});
|
||||
if (!targetUser) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
// Can't share with yourself
|
||||
if (targetUser.id === ownerId) {
|
||||
throw new Error('Cannot share session with yourself');
|
||||
}
|
||||
|
||||
// Create or update share
|
||||
return prisma.weatherSessionShare.upsert({
|
||||
where: {
|
||||
sessionId_userId: { sessionId, userId: targetUser.id },
|
||||
},
|
||||
update: { role },
|
||||
create: {
|
||||
sessionId,
|
||||
userId: targetUser.id,
|
||||
role,
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
export const shareWeatherSession = weatherShareEvents.share;
|
||||
|
||||
export async function shareWeatherSessionToTeam(
|
||||
sessionId: string,
|
||||
@@ -403,37 +256,8 @@ export async function shareWeatherSessionToTeam(
|
||||
return shares;
|
||||
}
|
||||
|
||||
export async function removeWeatherShare(
|
||||
sessionId: string,
|
||||
ownerId: string,
|
||||
shareUserId: string
|
||||
) {
|
||||
// Verify owner
|
||||
const session = await prisma.weatherSession.findFirst({
|
||||
where: { id: sessionId, userId: ownerId },
|
||||
});
|
||||
if (!session) {
|
||||
throw new Error('Session not found or not owned');
|
||||
}
|
||||
|
||||
return prisma.weatherSessionShare.deleteMany({
|
||||
where: { sessionId, userId: shareUserId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getWeatherSessionShares(sessionId: string, userId: string) {
|
||||
// Verify access
|
||||
if (!(await canAccessWeatherSession(sessionId, userId))) {
|
||||
throw new Error('Access denied');
|
||||
}
|
||||
|
||||
return prisma.weatherSessionShare.findMany({
|
||||
where: { sessionId },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
export const removeWeatherShare = weatherShareEvents.removeShare;
|
||||
export const getWeatherSessionShares = weatherShareEvents.getShares;
|
||||
|
||||
// ============================================
|
||||
// Session Events (for real-time sync)
|
||||
@@ -445,40 +269,6 @@ export type WeatherSessionEventType =
|
||||
| 'ENTRY_DELETED'
|
||||
| 'SESSION_UPDATED';
|
||||
|
||||
export async function createWeatherSessionEvent(
|
||||
sessionId: string,
|
||||
userId: string,
|
||||
type: WeatherSessionEventType,
|
||||
payload: Record<string, unknown>
|
||||
) {
|
||||
return prisma.weatherSessionEvent.create({
|
||||
data: {
|
||||
sessionId,
|
||||
userId,
|
||||
type,
|
||||
payload: JSON.stringify(payload),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getWeatherSessionEvents(sessionId: string, since?: Date) {
|
||||
return prisma.weatherSessionEvent.findMany({
|
||||
where: {
|
||||
sessionId,
|
||||
...(since && { createdAt: { gt: since } }),
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getLatestWeatherEventTimestamp(sessionId: string) {
|
||||
const event = await prisma.weatherSessionEvent.findFirst({
|
||||
where: { sessionId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: { createdAt: true },
|
||||
});
|
||||
return event?.createdAt;
|
||||
}
|
||||
export const createWeatherSessionEvent = weatherShareEvents.createEvent;
|
||||
export const getWeatherSessionEvents = weatherShareEvents.getEvents;
|
||||
export const getLatestWeatherEventTimestamp = weatherShareEvents.getLatestEventTimestamp;
|
||||
|
||||
Reference in New Issue
Block a user