Files
backend/src/users/users.service.ts

113 lines
3.0 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@nestjs/common';
import { UserStatus, UserRole, Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
type UserWithProfiles = Prisma.UserGetPayload<{
include: { userProfile: true; agentProfile: true };
}>;
@Injectable()
export class UsersService {
constructor(private readonly prisma: PrismaService) {}
async findAll(page = 1, limit = 10, role?: UserRole) {
const skip = (page - 1) * limit;
// Build where clause for optional role filter
const where: Prisma.UserWhereInput = role ? { role } : {};
const [users, total] = await Promise.all([
this.prisma.user.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: {
userProfile: true,
agentProfile: true,
},
}) as Promise<UserWithProfiles[]>,
this.prisma.user.count({ where }),
]);
return {
users: users.map((user) => {
// Get the appropriate profile based on role
const profile = user.role === UserRole.AGENT ? user.agentProfile : user.userProfile;
return {
id: user.id,
email: user.email,
role: user.role,
status: user.status,
emailVerified: user.emailVerified,
authProvider: user.authProvider,
createdAt: user.createdAt,
lastLoginAt: user.lastLoginAt,
profile: profile
? {
firstName: profile.firstName,
lastName: profile.lastName,
avatar: profile.avatar,
phone: profile.phone,
city: profile.city,
state: profile.state,
country: profile.country,
}
: null,
};
}),
total,
page,
limit,
totalPages: Math.ceil(total / limit),
};
}
async findOne(id: string) {
const user = (await this.prisma.user.findUnique({
where: { id },
include: {
userProfile: true,
agentProfile: true,
},
})) as UserWithProfiles | null;
if (!user) {
return null;
}
// Get the appropriate profile based on role
const profile = user.role === UserRole.AGENT ? user.agentProfile : user.userProfile;
return {
id: user.id,
email: user.email,
role: user.role,
status: user.status,
emailVerified: user.emailVerified,
authProvider: user.authProvider,
createdAt: user.createdAt,
lastLoginAt: user.lastLoginAt,
profile: profile
? {
firstName: profile.firstName,
lastName: profile.lastName,
avatar: profile.avatar,
phone: profile.phone,
city: profile.city,
state: profile.state,
country: profile.country,
}
: null,
};
}
async updateStatus(id: string, status: UserStatus) {
return this.prisma.user.update({
where: { id },
data: { status },
});
}
}