diff --git a/app/api/notifications/count/route.ts b/app/api/notifications/count/route.ts index 7f4b104..56b99c2 100644 --- a/app/api/notifications/count/route.ts +++ b/app/api/notifications/count/route.ts @@ -5,35 +5,20 @@ import { prisma } from '@/lib/prisma'; export async function GET() { try { - const session = await auth(); + const { userId } = await auth(); - if (!session?.userId) { + if (!userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } - const user = await prisma.user.findUnique({ - where: { clerkUserId: session.userId }, - select: { id: true } - }); - - if (!user) { - return NextResponse.json({ error: 'User not found' }, { status: 404 }); - } - - const unreadCount = await prisma.notification.count({ + const count = await prisma.notification.count({ where: { - userId: user.id, - isRead: false - } + userId, + isRead: false, + }, }); - const response = NextResponse.json({ - unreadCount, - userId: user.id - }); - - response.headers.set('Cache-Control', 'no-store'); - return response; + return NextResponse.json({ count }); } catch (error) { console.error('Error fetching notification count:', error); return NextResponse.json( diff --git a/lib/services/application.service.ts b/lib/services/application.service.ts index 1a3acbb..d60ef5d 100644 --- a/lib/services/application.service.ts +++ b/lib/services/application.service.ts @@ -104,7 +104,11 @@ export class ApplicationService { const land = await prisma.land.findUnique({ where: { id: data.landId }, include: { - landowner: true, + landowner: { + include: { + user: true, + }, + }, }, }); @@ -181,7 +185,11 @@ export class ApplicationService { include: { land: { include: { - landowner: true, + landowner: { + include: { + user: true, + }, + }, }, }, farmer: true, @@ -212,34 +220,17 @@ export class ApplicationService { return app; }); - // 8. Send notification to landowner - try { - // Get the landowner user (land.landownerId is the user ID) - const landownerUser = await prisma.user.findUnique({ - where: { id: land.landownerId }, - select: { id: true, name: true }, - }); - - if (landownerUser) { - const notificationResult = await createNotification({ - userId: landownerUser.id, - type: "APPLICATION", - title: "📋 New Lease Application Received", - message: `${farmer.name} has applied to lease "${land.title}". Proposed rent: ${data.proposedRent ? `₹${data.proposedRent.toLocaleString('en-IN')}` : 'Not specified'}.`, - entityType: "Application", - entityId: application.id, - actionUrl: `/applications/${application.id}`, - priority: "HIGH", - }); - - console.log(`✅ Notification sent to landowner (${landownerUser.id}):`, notificationResult); - } else { - console.warn(`âš ī¸ Could not find landowner user for landownerId: ${land.landownerId}`); - } - } catch (notificationError) { - console.error('❌ Failed to send landowner notification:', notificationError); - // Don't throw - application was created successfully - } + // 8. Send notification using server action + await createNotification({ + userId: land.landowner.user.id, + type: "APPLICATION", + title: "New Lease Application Received", + message: `${farmer.name} has applied to lease "${land.title}"`, + entityType: "Application", + entityId: application.id, + actionUrl: `/landowner/applications/${application.id}`, + priority: "MEDIUM", + }); return application; } @@ -257,7 +248,11 @@ export class ApplicationService { include: { land: { include: { - landowner: true, + landowner: { + include: { + user: true, // Include user + }, + }, }, }, farmer: true, @@ -268,8 +263,8 @@ export class ApplicationService { throw new AppError("Application not found", 404); } - // Check if reviewer is the landowner - if (application.land.landownerId !== reviewerId) { + // Check against landowner.user.id + if (application.land.landowner.user.id !== reviewerId) { throw new AppError("Unauthorized to review this application", 403); } @@ -337,40 +332,30 @@ export class ApplicationService { return app; }); - // Send notifications - try { - // 1. Notify farmer - const farmerNotification = await createNotification({ - userId: application.farmerId, - type: "APPLICATION", - title: data.status === "APPROVED" - ? "✅ Application Approved!" - : "❌ Application Not Selected", - message: data.status === "APPROVED" + // Send notifications using server action + await createNotification({ + userId: application.farmerId, + type: "APPLICATION", + title: `Application ${data.status.toLowerCase()}`, + message: + data.status === "APPROVED" ? `Great news! Your application for "${application.land.title}" has been approved. Please review and sign the lease agreement.` - : `Your application for "${application.land.title}" was not accepted at this time.${sanitizedNotes ? ` Notes: ${sanitizedNotes}` : ''}`, - entityType: "Application", - entityId: applicationId, - actionUrl: `/applications/${applicationId}`, - priority: "HIGH", - }); - console.log(`✅ Notification sent to farmer (${application.farmerId}):`, farmerNotification); - - // 2. Notify landowner (reviewer confirmation) - const landownerNotification = await createNotification({ - userId: reviewerId, - type: "APPLICATION", - title: `Application ${data.status.toLowerCase()}`, - message: `You have ${data.status.toLowerCase()} the application from ${application.farmer.name} for "${application.land.title}".`, - entityType: "Application", - entityId: applicationId, - actionUrl: `/applications/${applicationId}`, - priority: "MEDIUM", - }); - console.log(`✅ Notification sent to landowner (${reviewerId}):`, landownerNotification); - } catch (notificationError) { - console.error('❌ Failed to send review notifications:', notificationError); - } + : `Your application for "${application.land.title}" was not accepted at this time.`, + entityType: "Application", + entityId: applicationId, + actionUrl: `/applications/${applicationId}`, + priority: "MEDIUM", + }); + + await createNotification({ + userId: reviewerId, + type: "APPLICATION", + title: `Application ${data.status.toLowerCase()}`, + message: `You have ${data.status.toLowerCase()} the application for "${application.land.title}".`, + entityType: "Application", + entityId: applicationId, + priority: "MEDIUM", + }); return updated; } @@ -384,7 +369,11 @@ export class ApplicationService { include: { land: { include: { - landowner: true, + landowner: { + include: { + user: true, // Include user + }, + }, }, }, farmer: true, @@ -428,22 +417,16 @@ export class ApplicationService { return app; }); - // Send notification to landowner - try { - const landownerNotification = await createNotification({ - userId: application.land.landownerId, - type: "APPLICATION", - title: "â†Šī¸ Application Withdrawn", - message: `${application.farmer.name} has withdrawn their application for "${application.land.title}".`, - entityType: "Application", - entityId: applicationId, - actionUrl: `/applications/${applicationId}`, - priority: "MEDIUM", - }); - console.log(`✅ Withdrawal notification sent to landowner (${application.land.landownerId}):`, landownerNotification); - } catch (notificationError) { - console.error('❌ Failed to send withdrawal notification:', notificationError); - } + // Send notification to landowner.user.id + await createNotification({ + userId: application.land.landowner.user.id, + type: "APPLICATION", + title: "Application Withdrawn", + message: `${application.farmer.name} has withdrawn their application for "${application.land.title}".`, + entityType: "Application", + entityId: applicationId, + priority: "MEDIUM", + }); return updated; } @@ -468,7 +451,7 @@ export class ApplicationService { if (role === "FARMER") { where.farmerId = userId; } else { - where.land = { landownerId: userId }; + where.land = { landowner: { userId } }; } if (filters?.status?.length) { @@ -498,13 +481,17 @@ export class ApplicationService { land: { include: { landowner: { - select: { - id: true, - name: true, - email: true, - imageUrl: true, - state: true, - district: true, + include: { + user: { + select: { + id: true, + name: true, + email: true, + imageUrl: true, + state: true, + district: true, + }, + }, }, }, }, @@ -556,14 +543,18 @@ export class ApplicationService { land: { include: { landowner: { - select: { - id: true, - name: true, - email: true, - imageUrl: true, - phone: true, - state: true, - district: true, + include: { + user: { + select: { + id: true, + name: true, + email: true, + imageUrl: true, + phone: true, + state: true, + district: true, + }, + }, }, }, images: { @@ -608,7 +599,7 @@ export class ApplicationService { } const isFarmer = application.farmerId === userId; - const isLandowner = application.land.landowner.id === userId; + const isLandowner = application.land.landowner.user.id === userId; const isAdmin = userRole === "ADMIN" || userRole === "SUPER_ADMIN"; if (!isFarmer && !isLandowner && !isAdmin) { @@ -664,4 +655,4 @@ export class ApplicationService { return sanitized; } -} \ No newline at end of file +}