Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | 11x 11x 11x 11x 11x 11x 11x | import {
Injectable,
ForbiddenException,
ConflictException,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { ApplyForAgencyDto } from '@app/modules/agencies/dto/apply-for-agency.dto';
import {
User,
Role,
ModerationType,
InvitationStatus,
Prisma,
} from '@prisma/client';
import { InviteAgentDto } from '@app/modules/agencies/dto/invite-agent.dto';
import { UpdateAgencyDto } from '@app/modules/agencies/dto/update-agency.dto';
import * as crypto from 'crypto';
import { BillingService } from '@app/modules/billing/billing.service';
@Injectable()
export class AgenciesService {
constructor(private readonly prisma: PrismaService, private readonly billing: BillingService) {}
async getMyApplications(user: User) {
return this.prisma.client.agencyApplication.findMany({
where: {
applicantId: user.id,
},
orderBy: {
createdAt: 'desc',
},
});
}
// Purchase seats via BillingService
createSeatSubscription(agencyId: number, seatCount: number) {
return this.billing.createSeatSubscription(agencyId, seatCount);
}
// Get agency insights from DailyAgentStats
async getInsights(agencyId: number) {
const agents = await this.prisma.client.user.findMany({
where: { agencyId },
select: { id: true, name: true }
});
const agentIds = agents.map((a: { id: number }) => a.id);
// Get last 30 days of stats
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const stats = await this.prisma.client.dailyAgentStats.findMany({
where: {
agentId: { in: agentIds },
day: { gte: thirtyDaysAgo }
},
orderBy: { day: 'desc' }
});
// Aggregate by agent
const agentStats = agents.map((agent: { id: number; name: string | null }) => {
const agentData = stats.filter((s: { agentId: number }) => s.agentId === agent.id);
return {
agentId: agent.id,
agentName: agent.name,
totalListingsPublished: agentData.reduce((sum: number, s: { listingsPublished: number }) => sum + s.listingsPublished, 0),
totalInquiriesReceived: agentData.reduce((sum: number, s: { inquiriesReceived: number }) => sum + s.inquiriesReceived, 0),
totalLeadsCreated: agentData.reduce((sum: number, s: { leadsCreated: number }) => sum + s.leadsCreated, 0),
avgDaysOnMarket: agentData.length > 0 ?
agentData.reduce((sum: number, s: { avgDaysOnMarket: number | null }) => sum + (s.avgDaysOnMarket || 0), 0) / agentData.length : 0
};
});
return {
agencyId,
period: '30_days',
agents: agentStats,
summary: {
totalListingsPublished: agentStats.reduce((sum: number, a: { totalListingsPublished: number }) => sum + a.totalListingsPublished, 0),
totalInquiriesReceived: agentStats.reduce((sum: number, a: { totalInquiriesReceived: number }) => sum + a.totalInquiriesReceived, 0),
totalLeadsCreated: agentStats.reduce((sum: number, a: { totalLeadsCreated: number }) => sum + a.totalLeadsCreated, 0),
avgDaysOnMarket: agentStats.length > 0 ?
agentStats.reduce((sum: number, a: { avgDaysOnMarket: number }) => sum + a.avgDaysOnMarket, 0) / agentStats.length : 0
}
};
}
async applyForAgency(applyForAgencyDto: ApplyForAgencyDto, user: User) {
Iif (user.role !== Role.AGENT) {
throw new ForbiddenException('Only agents can apply to create an agency.');
}
const existingApplication = await this.prisma.client.agencyApplication.findFirst({
where: {
applicantId: user.id,
status: 'PENDING',
},
});
Iif (existingApplication) {
throw new ConflictException('You already have a pending application.');
}
return this.prisma.client.$transaction(async (tx: Prisma.TransactionClient) => {
const application = await tx.agencyApplication.create({
data: {
agencyName: applyForAgencyDto.agencyName,
applicantId: user.id,
},
});
await tx.moderationQueue.create({
data: {
type: ModerationType.AGENCY_APPLICATION,
submittedById: user.id,
agencyApplicationId: application.id,
moderatedContent: {
agencyName: applyForAgencyDto.agencyName,
} as Prisma.InputJsonValue,
},
});
return application;
});
}
async getMyAgency(user: User) {
Iif (!user.agencyId) {
throw new NotFoundException('You are not part of any agency.');
}
return this.prisma.client.agency.findUnique({
where: { id: user.agencyId },
include: {
owner: {
select: { id: true, name: true, email: true },
},
agents: {
select: { id: true, name: true, email: true },
},
},
});
}
async getAgencyById(id: number) {
const agency = await this.prisma.client.agency.findUnique({
where: { id, isVerified: true },
include: {
owner: {
select: {
id: true,
name: true,
},
},
agents: {
select: {
id: true,
name: true,
email: true,
},
},
},
});
Iif (!agency) {
throw new NotFoundException(`Agency with ID ${id} not found.`);
}
// This logic is now incorrect as `agents` includes the owner.
// Let's return the full agent list for now.
// The frontend can filter if needed.
return agency;
}
async getAgencyAgents(agencyId: number) {
return this.prisma.client.user.findMany({
where: {
agencyId,
role: Role.AGENT,
},
select: {
id: true,
name: true,
email: true,
},
});
}
async updateAgencyProfile(user: User, updateAgencyDto: UpdateAgencyDto) {
Iif (!user.agencyId) {
throw new ForbiddenException('You are not part of any agency.');
}
const agency = await this.prisma.client.agency.findUnique({
where: { id: user.agencyId },
});
Iif (!agency || agency.ownerId !== user.id) {
throw new ForbiddenException('Only the agency owner can request updates.');
}
const pendingUpdate = await this.prisma.client.moderationQueue.findFirst({
where: {
type: ModerationType.AGENCY_PROFILE_UPDATE,
agencyId: agency.id,
status: 'PENDING',
},
});
Iif (pendingUpdate) {
throw new ConflictException(
'There is already a pending update request for this agency.',
);
}
return this.prisma.client.moderationQueue.create({
data: {
type: ModerationType.AGENCY_PROFILE_UPDATE,
agencyId: agency.id,
submittedById: user.id,
moderatedContent: updateAgencyDto as any,
},
});
}
async inviteAgent(inviter: User, { email }: InviteAgentDto) {
Iif (inviter.role !== Role.AGENT || !inviter.agencyId) {
throw new ForbiddenException('You must be an agent to invite others.');
}
const agency = await this.prisma.client.agency.findUnique({
where: { id: inviter.agencyId },
});
Iif (!agency || agency.ownerId !== inviter.id) {
throw new ForbiddenException(
'You must be the owner of the agency to invite agents.',
);
}
const invitee = await this.prisma.client.user.findUnique({ where: { email } });
Iif (!invitee || invitee.role !== Role.AGENT) {
throw new NotFoundException('User not found or is not an agent.');
}
Iif (invitee.agencyId) {
throw new ConflictException('This agent is already part of an agency.');
}
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours
await this.prisma.client.agencyInvitation.create({
data: {
agencyId: inviter.agencyId,
inviterId: inviter.id,
inviteeId: invitee.id,
token,
expiresAt,
},
});
// In a real app, you would email this link to the user
console.log(`Invitation link: /agencies/invitations/${token}/accept`);
return { message: 'Invitation sent successfully.' };
}
async acceptInvitation(user: User, token: string) {
const invitation = await this.prisma.client.agencyInvitation.findFirst({
where: {
token,
inviteeId: user.id,
status: InvitationStatus.PENDING,
expiresAt: {
gt: new Date(),
},
},
});
Iif (!invitation) {
throw new NotFoundException(
'Invitation not found, has expired, or is not for you.',
);
}
return this.prisma.client.$transaction(async (tx: Prisma.TransactionClient) => {
await tx.user.update({
where: { id: user.id },
data: { agencyId: invitation.agencyId },
});
return tx.agencyInvitation.update({
where: { id: invitation.id },
data: { status: InvitationStatus.ACCEPTED },
});
});
}
async declineInvitation(user: User, token: string) {
const invitation = await this.prisma.client.agencyInvitation.findFirst({
where: {
token,
inviteeId: user.id,
status: InvitationStatus.PENDING,
},
});
Iif (!invitation) {
throw new NotFoundException('Invitation not found or not pending.');
}
return this.prisma.client.agencyInvitation.update({
where: { id: invitation.id },
data: { status: InvitationStatus.DECLINED },
});
}
async removeAgent(remover: User, agencyId: number, userId: number) {
const agency = await this.prisma.client.agency.findUnique({
where: { id: agencyId },
});
Iif (!agency || agency.ownerId !== remover.id) {
throw new ForbiddenException(
'Only the agency owner can remove agents.',
);
}
Iif (remover.id === userId) {
throw new ForbiddenException('You cannot remove yourself.');
}
return this.prisma.client.user.update({
where: { id: userId, agencyId },
data: {
agencyId: null,
},
});
}
async requestUpdateMyAgency(user: User, updateAgencyDto: UpdateAgencyDto) {
Iif (user.role !== Role.AGENT || !user.agencyId) {
throw new ForbiddenException(
'You must be an agent part of an agency to perform this action.',
);
}
const agency = await this.prisma.client.agency.findUnique({
where: { id: user.agencyId },
});
Iif (!agency) {
throw new NotFoundException(`Agency with ID ${user.agencyId} not found.`);
}
Iif (agency.ownerId !== user.id) {
throw new ForbiddenException(
'Only the agency owner can request profile updates.',
);
}
await this.prisma.client.moderationQueue.create({
data: {
type: ModerationType.AGENCY_PROFILE_UPDATE,
agencyId: agency.id,
submittedById: user.id,
moderatedContent: updateAgencyDto as any,
},
});
return {
message:
'Your agency profile update request has been submitted for review.',
};
}
} |