Performance optimization, applicant portal, and missing DB migration
Performance: - Convert admin dashboard from SSR to client-side tRPC (fixes 503/ChunkLoadError) - New dashboard.getStats tRPC endpoint batches 16 queries into single response - Parallelize jury dashboard queries (assignments + gracePeriods via Promise.all) - Add project.getFullDetail combined endpoint (project + assignments + stats) - Configure Prisma connection pool (connection_limit=20, pool_timeout=10) - Add optimizePackageImports for lucide-react tree-shaking - Increase React Query staleTime from 1min to 5min Applicant portal: - Add applicant layout, nav, dashboard, documents, team, and mentor pages - Add applicant router with document and team management endpoints - Add chunk error recovery utility - Update role nav and auth redirect for applicant role Database: - Add migration for missing schema elements (SpecialAward job tracking columns, WizardTemplate table, missing indexes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -35,6 +35,7 @@ import { messageRouter } from './message'
|
||||
import { webhookRouter } from './webhook'
|
||||
import { projectPoolRouter } from './project-pool'
|
||||
import { wizardTemplateRouter } from './wizard-template'
|
||||
import { dashboardRouter } from './dashboard'
|
||||
|
||||
/**
|
||||
* Root tRPC router that combines all domain routers
|
||||
@@ -76,6 +77,7 @@ export const appRouter = router({
|
||||
webhook: webhookRouter,
|
||||
projectPool: projectPoolRouter,
|
||||
wizardTemplate: wizardTemplateRouter,
|
||||
dashboard: dashboardRouter,
|
||||
})
|
||||
|
||||
export type AppRouter = typeof appRouter
|
||||
|
||||
@@ -1030,4 +1030,186 @@ export const applicantRouter = router({
|
||||
|
||||
return messages
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get the applicant's dashboard data: their project (latest edition),
|
||||
* team members, open rounds for document submission, and status timeline.
|
||||
*/
|
||||
getMyDashboard: protectedProcedure.query(async ({ ctx }) => {
|
||||
if (ctx.user.role !== 'APPLICANT') {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Only applicants can access this',
|
||||
})
|
||||
}
|
||||
|
||||
// Find the applicant's project (most recent, from active edition if possible)
|
||||
const project = await ctx.prisma.project.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ submittedByUserId: ctx.user.id },
|
||||
{ teamMembers: { some: { userId: ctx.user.id } } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
round: {
|
||||
include: {
|
||||
program: { select: { id: true, name: true, year: true, status: true } },
|
||||
},
|
||||
},
|
||||
files: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
teamMembers: {
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, name: true, email: true, status: true },
|
||||
},
|
||||
},
|
||||
orderBy: { joinedAt: 'asc' },
|
||||
},
|
||||
submittedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
mentorAssignment: {
|
||||
include: {
|
||||
mentor: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
wonAwards: {
|
||||
select: { id: true, name: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
|
||||
if (!project) {
|
||||
return { project: null, openRounds: [], timeline: [], currentStatus: null }
|
||||
}
|
||||
|
||||
const currentStatus = project.status ?? 'SUBMITTED'
|
||||
|
||||
// Fetch status history
|
||||
const statusHistory = await ctx.prisma.projectStatusHistory.findMany({
|
||||
where: { projectId: project.id },
|
||||
orderBy: { changedAt: 'asc' },
|
||||
select: { status: true, changedAt: true },
|
||||
})
|
||||
|
||||
const statusDateMap = new Map<string, Date>()
|
||||
for (const entry of statusHistory) {
|
||||
if (!statusDateMap.has(entry.status)) {
|
||||
statusDateMap.set(entry.status, entry.changedAt)
|
||||
}
|
||||
}
|
||||
|
||||
const isRejected = currentStatus === 'REJECTED'
|
||||
const hasWonAward = project.wonAwards.length > 0
|
||||
|
||||
// Build timeline
|
||||
const timeline = [
|
||||
{
|
||||
status: 'CREATED',
|
||||
label: 'Application Started',
|
||||
date: project.createdAt,
|
||||
completed: true,
|
||||
isTerminal: false,
|
||||
},
|
||||
{
|
||||
status: 'SUBMITTED',
|
||||
label: 'Application Submitted',
|
||||
date: project.submittedAt || statusDateMap.get('SUBMITTED') || null,
|
||||
completed: !!project.submittedAt || statusDateMap.has('SUBMITTED'),
|
||||
isTerminal: false,
|
||||
},
|
||||
{
|
||||
status: 'UNDER_REVIEW',
|
||||
label: 'Under Review',
|
||||
date: statusDateMap.get('ELIGIBLE') || statusDateMap.get('ASSIGNED') ||
|
||||
(currentStatus !== 'SUBMITTED' && project.submittedAt ? project.submittedAt : null),
|
||||
completed: ['ELIGIBLE', 'ASSIGNED', 'SEMIFINALIST', 'FINALIST', 'REJECTED'].includes(currentStatus),
|
||||
isTerminal: false,
|
||||
},
|
||||
]
|
||||
|
||||
if (isRejected) {
|
||||
timeline.push({
|
||||
status: 'REJECTED',
|
||||
label: 'Not Selected',
|
||||
date: statusDateMap.get('REJECTED') || null,
|
||||
completed: true,
|
||||
isTerminal: true,
|
||||
})
|
||||
} else {
|
||||
timeline.push(
|
||||
{
|
||||
status: 'SEMIFINALIST',
|
||||
label: 'Semi-finalist',
|
||||
date: statusDateMap.get('SEMIFINALIST') || null,
|
||||
completed: ['SEMIFINALIST', 'FINALIST'].includes(currentStatus) || hasWonAward,
|
||||
isTerminal: false,
|
||||
},
|
||||
{
|
||||
status: 'FINALIST',
|
||||
label: 'Finalist',
|
||||
date: statusDateMap.get('FINALIST') || null,
|
||||
completed: currentStatus === 'FINALIST' || hasWonAward,
|
||||
isTerminal: false,
|
||||
},
|
||||
)
|
||||
|
||||
if (hasWonAward) {
|
||||
timeline.push({
|
||||
status: 'WINNER',
|
||||
label: `Winner${project.wonAwards.length > 0 ? ` - ${project.wonAwards[0].name}` : ''}`,
|
||||
date: null,
|
||||
completed: true,
|
||||
isTerminal: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Find open rounds in the same program where documents can be submitted
|
||||
const programId = project.round?.programId || project.programId
|
||||
const now = new Date()
|
||||
|
||||
const openRounds = programId
|
||||
? await ctx.prisma.round.findMany({
|
||||
where: {
|
||||
programId,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
})
|
||||
: []
|
||||
|
||||
// Filter: only rounds that still accept uploads
|
||||
const uploadableRounds = openRounds.filter((round) => {
|
||||
const settings = round.settingsJson as Record<string, unknown> | null
|
||||
const uploadPolicy = settings?.uploadDeadlinePolicy as string | undefined
|
||||
const roundStarted = round.votingStartAt && now > round.votingStartAt
|
||||
|
||||
// If deadline passed and policy is BLOCK, skip
|
||||
if (roundStarted && uploadPolicy === 'BLOCK') return false
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
// Determine user's role in the project
|
||||
const userMembership = project.teamMembers.find((tm) => tm.userId === ctx.user.id)
|
||||
const isTeamLead = project.submittedByUserId === ctx.user.id || userMembership?.role === 'LEAD'
|
||||
|
||||
return {
|
||||
project: {
|
||||
...project,
|
||||
isTeamLead,
|
||||
userRole: userMembership?.role || (project.submittedByUserId === ctx.user.id ? 'LEAD' : null),
|
||||
},
|
||||
openRounds: uploadableRounds,
|
||||
timeline,
|
||||
currentStatus,
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
||||
184
src/server/routers/dashboard.ts
Normal file
184
src/server/routers/dashboard.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { z } from 'zod'
|
||||
import { router, adminProcedure } from '../trpc'
|
||||
|
||||
export const dashboardRouter = router({
|
||||
/**
|
||||
* Get all dashboard stats in a single query batch.
|
||||
* Replaces the 16 parallel Prisma queries that were previously
|
||||
* run during SSR, which blocked the event loop and caused 503s.
|
||||
*/
|
||||
getStats: adminProcedure
|
||||
.input(z.object({ editionId: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { editionId } = input
|
||||
|
||||
const edition = await ctx.prisma.program.findUnique({
|
||||
where: { id: editionId },
|
||||
select: { name: true, year: true },
|
||||
})
|
||||
|
||||
if (!edition) return null
|
||||
|
||||
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
||||
|
||||
const [
|
||||
activeRoundCount,
|
||||
totalRoundCount,
|
||||
projectCount,
|
||||
newProjectsThisWeek,
|
||||
totalJurors,
|
||||
activeJurors,
|
||||
evaluationStats,
|
||||
totalAssignments,
|
||||
recentRounds,
|
||||
latestProjects,
|
||||
categoryBreakdown,
|
||||
oceanIssueBreakdown,
|
||||
recentActivity,
|
||||
pendingCOIs,
|
||||
draftRounds,
|
||||
unassignedProjects,
|
||||
] = await Promise.all([
|
||||
ctx.prisma.round.count({
|
||||
where: { programId: editionId, status: 'ACTIVE' },
|
||||
}),
|
||||
ctx.prisma.round.count({
|
||||
where: { programId: editionId },
|
||||
}),
|
||||
ctx.prisma.project.count({
|
||||
where: { programId: editionId },
|
||||
}),
|
||||
ctx.prisma.project.count({
|
||||
where: {
|
||||
programId: editionId,
|
||||
createdAt: { gte: sevenDaysAgo },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.user.count({
|
||||
where: {
|
||||
role: 'JURY_MEMBER',
|
||||
status: { in: ['ACTIVE', 'INVITED', 'NONE'] },
|
||||
assignments: { some: { round: { programId: editionId } } },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.user.count({
|
||||
where: {
|
||||
role: 'JURY_MEMBER',
|
||||
status: 'ACTIVE',
|
||||
assignments: { some: { round: { programId: editionId } } },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.evaluation.groupBy({
|
||||
by: ['status'],
|
||||
where: { assignment: { round: { programId: editionId } } },
|
||||
_count: true,
|
||||
}),
|
||||
ctx.prisma.assignment.count({
|
||||
where: { round: { programId: editionId } },
|
||||
}),
|
||||
ctx.prisma.round.findMany({
|
||||
where: { programId: editionId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 5,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
votingStartAt: true,
|
||||
votingEndAt: true,
|
||||
submissionEndDate: true,
|
||||
_count: {
|
||||
select: {
|
||||
projects: true,
|
||||
assignments: true,
|
||||
},
|
||||
},
|
||||
assignments: {
|
||||
select: {
|
||||
evaluation: { select: { status: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
ctx.prisma.project.findMany({
|
||||
where: { programId: editionId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 8,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
teamName: true,
|
||||
country: true,
|
||||
competitionCategory: true,
|
||||
oceanIssue: true,
|
||||
logoKey: true,
|
||||
createdAt: true,
|
||||
submittedAt: true,
|
||||
status: true,
|
||||
round: { select: { name: true } },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.project.groupBy({
|
||||
by: ['competitionCategory'],
|
||||
where: { programId: editionId },
|
||||
_count: true,
|
||||
}),
|
||||
ctx.prisma.project.groupBy({
|
||||
by: ['oceanIssue'],
|
||||
where: { programId: editionId },
|
||||
_count: true,
|
||||
}),
|
||||
ctx.prisma.auditLog.findMany({
|
||||
where: {
|
||||
timestamp: { gte: sevenDaysAgo },
|
||||
},
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: 8,
|
||||
select: {
|
||||
id: true,
|
||||
action: true,
|
||||
entityType: true,
|
||||
timestamp: true,
|
||||
user: { select: { name: true } },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.conflictOfInterest.count({
|
||||
where: {
|
||||
hasConflict: true,
|
||||
reviewedAt: null,
|
||||
assignment: { round: { programId: editionId } },
|
||||
},
|
||||
}),
|
||||
ctx.prisma.round.count({
|
||||
where: { programId: editionId, status: 'DRAFT' },
|
||||
}),
|
||||
ctx.prisma.project.count({
|
||||
where: {
|
||||
programId: editionId,
|
||||
round: { status: 'ACTIVE' },
|
||||
assignments: { none: {} },
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
return {
|
||||
edition,
|
||||
activeRoundCount,
|
||||
totalRoundCount,
|
||||
projectCount,
|
||||
newProjectsThisWeek,
|
||||
totalJurors,
|
||||
activeJurors,
|
||||
evaluationStats,
|
||||
totalAssignments,
|
||||
recentRounds,
|
||||
latestProjects,
|
||||
categoryBreakdown,
|
||||
oceanIssueBreakdown,
|
||||
recentActivity,
|
||||
pendingCOIs,
|
||||
draftRounds,
|
||||
unassignedProjects,
|
||||
}
|
||||
}),
|
||||
})
|
||||
@@ -681,7 +681,7 @@ export const mentorRouter = router({
|
||||
type: 'MENTOR_MESSAGE',
|
||||
title: 'New Message from Mentor',
|
||||
message: `${ctx.user.name || 'Your mentor'} sent you a message`,
|
||||
linkUrl: `/my-submission/${input.projectId}`,
|
||||
linkUrl: `/applicant/mentor`,
|
||||
linkLabel: 'View Message',
|
||||
priority: 'normal',
|
||||
metadata: {
|
||||
|
||||
@@ -1164,4 +1164,121 @@ export const projectRouter = router({
|
||||
|
||||
return { projects, total, page, perPage, totalPages: Math.ceil(total / perPage) }
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get full project detail with assignments and evaluation stats in one call.
|
||||
* Reduces client-side waterfall by combining project.get + assignment.listByProject + evaluation.getProjectStats.
|
||||
*/
|
||||
getFullDetail: adminProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const [projectRaw, projectTags, assignments, submittedEvaluations] = await Promise.all([
|
||||
ctx.prisma.project.findUniqueOrThrow({
|
||||
where: { id: input.id },
|
||||
include: {
|
||||
files: true,
|
||||
round: true,
|
||||
teamMembers: {
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, name: true, email: true, profileImageKey: true, profileImageProvider: true },
|
||||
},
|
||||
},
|
||||
orderBy: { joinedAt: 'asc' },
|
||||
},
|
||||
mentorAssignment: {
|
||||
include: {
|
||||
mentor: {
|
||||
select: { id: true, name: true, email: true, expertiseTags: true, profileImageKey: true, profileImageProvider: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
ctx.prisma.projectTag.findMany({
|
||||
where: { projectId: input.id },
|
||||
include: { tag: { select: { id: true, name: true, category: true, color: true } } },
|
||||
orderBy: { confidence: 'desc' },
|
||||
}).catch(() => [] as { id: string; projectId: string; tagId: string; confidence: number; tag: { id: string; name: string; category: string | null; color: string | null } }[]),
|
||||
ctx.prisma.assignment.findMany({
|
||||
where: { projectId: input.id },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, expertiseTags: true, profileImageKey: true, profileImageProvider: true } },
|
||||
evaluation: { select: { status: true, submittedAt: true, globalScore: true, binaryDecision: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
ctx.prisma.evaluation.findMany({
|
||||
where: {
|
||||
status: 'SUBMITTED',
|
||||
assignment: { projectId: input.id },
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
// Compute evaluation stats
|
||||
let stats = null
|
||||
if (submittedEvaluations.length > 0) {
|
||||
const globalScores = submittedEvaluations
|
||||
.map((e) => e.globalScore)
|
||||
.filter((s): s is number => s !== null)
|
||||
const yesVotes = submittedEvaluations.filter((e) => e.binaryDecision === true).length
|
||||
stats = {
|
||||
totalEvaluations: submittedEvaluations.length,
|
||||
averageGlobalScore: globalScores.length > 0
|
||||
? globalScores.reduce((a, b) => a + b, 0) / globalScores.length
|
||||
: null,
|
||||
minScore: globalScores.length > 0 ? Math.min(...globalScores) : null,
|
||||
maxScore: globalScores.length > 0 ? Math.max(...globalScores) : null,
|
||||
yesVotes,
|
||||
noVotes: submittedEvaluations.length - yesVotes,
|
||||
yesPercentage: (yesVotes / submittedEvaluations.length) * 100,
|
||||
}
|
||||
}
|
||||
|
||||
// Attach avatar URLs in parallel
|
||||
const [teamMembersWithAvatars, assignmentsWithAvatars, mentorWithAvatar] = await Promise.all([
|
||||
Promise.all(
|
||||
projectRaw.teamMembers.map(async (member) => ({
|
||||
...member,
|
||||
user: {
|
||||
...member.user,
|
||||
avatarUrl: await getUserAvatarUrl(member.user.profileImageKey, member.user.profileImageProvider),
|
||||
},
|
||||
}))
|
||||
),
|
||||
Promise.all(
|
||||
assignments.map(async (a) => ({
|
||||
...a,
|
||||
user: {
|
||||
...a.user,
|
||||
avatarUrl: await getUserAvatarUrl(a.user.profileImageKey, a.user.profileImageProvider),
|
||||
},
|
||||
}))
|
||||
),
|
||||
projectRaw.mentorAssignment
|
||||
? (async () => ({
|
||||
...projectRaw.mentorAssignment!,
|
||||
mentor: {
|
||||
...projectRaw.mentorAssignment!.mentor,
|
||||
avatarUrl: await getUserAvatarUrl(
|
||||
projectRaw.mentorAssignment!.mentor.profileImageKey,
|
||||
projectRaw.mentorAssignment!.mentor.profileImageProvider
|
||||
),
|
||||
},
|
||||
}))()
|
||||
: Promise.resolve(null),
|
||||
])
|
||||
|
||||
return {
|
||||
project: {
|
||||
...projectRaw,
|
||||
projectTags,
|
||||
teamMembers: teamMembersWithAvatars,
|
||||
mentorAssignment: mentorWithAvatar,
|
||||
},
|
||||
assignments: assignmentsWithAvatars,
|
||||
stats,
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user