Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 7 additions & 22 deletions app/api/notifications/count/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
193 changes: 92 additions & 101 deletions lib/services/application.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,11 @@ export class ApplicationService {
const land = await prisma.land.findUnique({
where: { id: data.landId },
include: {
landowner: true,
landowner: {
include: {
user: true,
},
},
},
});

Expand Down Expand Up @@ -181,7 +185,11 @@ export class ApplicationService {
include: {
land: {
include: {
landowner: true,
landowner: {
include: {
user: true,
},
},
},
},
farmer: true,
Expand Down Expand Up @@ -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;
}
Expand All @@ -257,7 +248,11 @@ export class ApplicationService {
include: {
land: {
include: {
landowner: true,
landowner: {
include: {
user: true, // Include user
},
},
},
},
farmer: true,
Expand All @@ -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);
}

Expand Down Expand Up @@ -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;
}
Expand All @@ -384,7 +369,11 @@ export class ApplicationService {
include: {
land: {
include: {
landowner: true,
landowner: {
include: {
user: true, // Include user
},
},
},
},
farmer: true,
Expand Down Expand Up @@ -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;
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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,
},
},
},
},
},
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -664,4 +655,4 @@ export class ApplicationService {

return sanitized;
}
}
}